SAIFIINDUSTRIES commited on
Commit
751ed1a
·
verified ·
1 Parent(s): 5231820

Add Repo: chili-chips-ba_openCologne (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. chili-chips-ba_openCologne/4.Advanced--4--Yamaha-OPL3-FM-Synth/4.dac/3.build/luttable_lut_module/3.sw/systemverilog/sinewave_code_generator.py +120 -0
  2. chili-chips-ba_openCologne/4.Advanced--4--Yamaha-OPL3-FM-Synth/4.dac/3.build/luttable_lut_module/3.sw/verilog/sinewave_code_generator.py +118 -0
  3. chili-chips-ba_openCologne/4.Advanced--4--Yamaha-OPL3-FM-Synth/README.md +27 -0
  4. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/debounce.v +53 -0
  5. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/gatemate_25MHz_pll.v +47 -0
  6. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/picorv32.v +2977 -0
  7. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/picosoc.sdc +1 -0
  8. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/picosoc_noflash.v +266 -0
  9. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/progmem.v +0 -0
  10. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/simpleuart.v +132 -0
  11. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/top.v +315 -0
  12. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/uart_rx.v +238 -0
  13. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/uart_tx.v +183 -0
  14. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/vga_controller.v +141 -0
  15. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/vga_map_ram.v +30 -0
  16. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/vga_ram.v +30 -0
  17. chili-chips-ba_openCologne/5.TetriSaraj/1.hw/vga_wrapper.v +89 -0
  18. chili-chips-ba_openCologne/5.TetriSaraj/2.sim/README.md +44 -0
  19. chili-chips-ba_openCologne/5.TetriSaraj/2.sw/main.c +1212 -0
  20. chili-chips-ba_openCologne/5.TetriSaraj/README.md +94 -0
  21. chili-chips-ba_openCologne/6.PCB.advanced/README.md +59 -0
  22. chili-chips-ba_openCologne/7.SerDes/1.serdestool_by_gm/README.md +145 -0
  23. chili-chips-ba_openCologne/7.SerDes/1.serdestool_by_gm/serdes_lb.v +473 -0
  24. chili-chips-ba_openCologne/7.SerDes/1.serdestool_by_gm/serdestool.py +1584 -0
  25. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/README.md +102 -0
  26. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/__init__.py +0 -0
  27. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo.py +45 -0
  28. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/README.md +102 -0
  29. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/__init__.py +0 -0
  30. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/demo.py +45 -0
  31. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/donut.c +68 -0
  32. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/helloc.c +6 -0
  33. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/hellocpp.cpp +7 -0
  34. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/main.c +210 -0
  35. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/donut.c +68 -0
  36. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/helloc.c +6 -0
  37. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/hellocpp.cpp +7 -0
  38. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/main.c +210 -0
  39. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/4.migen/liteiclink/serdes/serdes_gm.py +472 -0
  40. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/4.migen/litex/litex-boards/litex_boards/platforms/colognechip_gatemate_evb.py +141 -0
  41. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/4.migen/litex/litex-boards/litex_boards/targets/colognechip_gatemate_evb.py +123 -0
  42. chili-chips-ba_openCologne/7.SerDes/2.liteiclink/README.md +148 -0
  43. chili-chips-ba_openCologne/7.SerDes/README.md +57 -0
  44. chili-chips-ba_openCologne/8.StressTest/0.doc/Gowin-Arora/README.md +4 -0
  45. chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/README.md +98 -0
  46. chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/corescore_0.eda.yml +138 -0
  47. chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/corescore_0_00.v +0 -0
  48. chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/corescore_0_synth.v +0 -0
  49. chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/edalize_yosys_procs.tcl +51 -0
  50. chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/generator_cache/corescore-corescorecore_0-74191c27a08ab212740fbebfd133ec752b0d1793bbf6f7c086d8a99a1c975264/corescorecore.v +105 -0
chili-chips-ba_openCologne/4.Advanced--4--Yamaha-OPL3-FM-Synth/4.dac/3.build/luttable_lut_module/3.sw/systemverilog/sinewave_code_generator.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import numpy as np
3
+ import math
4
+
5
+ def generate_unsigned_table(lut_depth, data_width):
6
+ table_entries = 1 << lut_depth
7
+ max_value = (1 << data_width) - 1
8
+
9
+ sine_data = np.zeros(table_entries, dtype=np.int64)
10
+
11
+ for k in range(table_entries):
12
+ phase = 2.0 * math.pi * k / table_entries
13
+ # Offset sine wave to start from mid-range (unsigned)
14
+ sine_data[k] = int((max_value / 2) * (1 + math.sin(phase)))
15
+
16
+ return sine_data
17
+
18
+ def generate_verilog_lut_module(lut_depth, data_width, filename):
19
+ sine_data = generate_unsigned_table(lut_depth, data_width)
20
+ table_entries = len(sine_data)
21
+
22
+ verilog_code = f"""
23
+ module sinewave_table #(
24
+ parameter LUT_DEPTH = {lut_depth},
25
+ parameter DATA_WIDTH = {data_width}
26
+ )(
27
+ input logic [LUT_DEPTH-1 :0] address, // {lut_depth}-bit address signal for {table_entries} values
28
+ output logic [DATA_WIDTH-1:0] value // {data_width}-bit output signal
29
+ );
30
+
31
+ always @(*) begin
32
+ unique case (address)
33
+ """
34
+ for i, value in enumerate(sine_data):
35
+ verilog_code += f" {lut_depth}'d{i}: value = {data_width}'h{value:X};\n"
36
+
37
+ verilog_code += f""" default: value = {data_width}'h0;
38
+ endcase
39
+ end
40
+
41
+ endmodule
42
+ """
43
+ with open(filename, "w") as f:
44
+ f.write(verilog_code)
45
+
46
+ return verilog_code
47
+
48
+ def generate_verilog_sinewave_generator(lut_depth, data_width, phase_width, filename):
49
+ verilog_code = f"""
50
+ module sinewave_generator #(
51
+ parameter DATA_WIDTH = {data_width},
52
+ LUT_DEPTH = {lut_depth},
53
+ PHASE_WIDTH = {phase_width}
54
+ ) (
55
+ input logic clk,
56
+ input logic arst,
57
+ input logic sample_clk_ce,
58
+ input logic signed [PHASE_WIDTH-1:0] phase_increment,
59
+ output logic [DATA_WIDTH -1:0] sinewave,
60
+ output logic [DATA_WIDTH -1:0] cosinewave
61
+ );
62
+
63
+ logic [PHASE_WIDTH-1:0] phase_accumulator;
64
+
65
+ sinewave_table #(
66
+ .DATA_WIDTH(DATA_WIDTH),
67
+ .LUT_DEPTH(LUT_DEPTH)
68
+ ) sinewave_inst (
69
+ .address(phase_accumulator[PHASE_WIDTH-1:PHASE_WIDTH-LUT_DEPTH]),
70
+ .value(sinewave)
71
+ );
72
+
73
+ sinewave_table #(
74
+ .DATA_WIDTH(DATA_WIDTH),
75
+ .LUT_DEPTH(LUT_DEPTH)
76
+ ) cosinewave_inst (
77
+ .address((phase_accumulator[PHASE_WIDTH-1:PHASE_WIDTH-LUT_DEPTH] + (1<<(LUT_DEPTH-2))) % (1<<LUT_DEPTH)),
78
+ .value(cosinewave)
79
+ );
80
+
81
+ always @(posedge clk or posedge arst) begin
82
+ if (arst == 1'b1)
83
+ phase_accumulator <= '0;
84
+ else if (sample_clk_ce == 1'b1)
85
+ phase_accumulator <= PHASE_WIDTH'(phase_accumulator + phase_increment);
86
+ end
87
+
88
+ //=============================//
89
+ // For sim only //
90
+ //=============================//
91
+ //`ifdef SIMULATION
92
+ initial begin
93
+ $dumpfile("sinewave_waves.vcd");
94
+ $dumpvars(0, sinewave_generator);
95
+ end
96
+ //`endif
97
+
98
+
99
+ endmodule
100
+ """
101
+ with open(filename, "w") as f:
102
+ f.write(verilog_code)
103
+
104
+ return verilog_code
105
+
106
+ if __name__ == "__main__":
107
+ parser = argparse.ArgumentParser(description="Generate Verilog sinewave modules")
108
+ parser.add_argument("--lut_depth", "-ld", type=int, default=8, help="Number of address bits for the LUT (default: 8)")
109
+ parser.add_argument("--data_width", "-dw", type=int, default=7, help="Number of output bits for the sine wave (default: 7)")
110
+ parser.add_argument("--phase_width", "-pw", type=int, default=64, help="Number of bits for the phase accumulator (default: 64)")
111
+ parser.add_argument("--lut_filename", "-lf", type=str, default="sinewave_table.sv", help="Output filename for the LUT module (default: sinewave_table.sv)")
112
+ parser.add_argument("--generator_filename", "-gf", type=str, default="sinewave_generator.sv", help="Output filename for the sinewave generator module (default: sinewave_generator.sv)")
113
+
114
+ args = parser.parse_args()
115
+
116
+ # Generate the LUT Verilog module
117
+ generate_verilog_lut_module(args.lut_depth, args.data_width, args.lut_filename)
118
+
119
+ # Generate the sinewave generator Verilog module
120
+ generate_verilog_sinewave_generator(args.lut_depth, args.data_width, args.phase_width, args.generator_filename)
chili-chips-ba_openCologne/4.Advanced--4--Yamaha-OPL3-FM-Synth/4.dac/3.build/luttable_lut_module/3.sw/verilog/sinewave_code_generator.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import numpy as np
3
+ import math
4
+
5
+ def generate_unsigned_table(lut_depth, data_width):
6
+ table_entries = 1 << lut_depth
7
+ max_value = (1 << data_width) - 1 # Maximum unsigned value for the given data width
8
+
9
+ sine_data = np.zeros(table_entries, dtype=np.int64)
10
+
11
+ for k in range(table_entries):
12
+ phase = 2.0 * math.pi * k / table_entries
13
+ # Offset sine wave to start from mid-range (unsigned)
14
+ sine_data[k] = int((max_value / 2) * (1 + math.sin(phase)))
15
+
16
+ return sine_data
17
+
18
+ def generate_verilog_lut_module(lut_depth, data_width, filename):
19
+ sine_data = generate_unsigned_table(lut_depth, data_width)
20
+ table_entries = len(sine_data)
21
+
22
+ verilog_code = f"""
23
+ module sinewave_table #(
24
+ parameter LUT_DEPTH = {lut_depth},
25
+ parameter DATA_WIDTH = {data_width}
26
+ )(
27
+ input wire [LUT_DEPTH-1:0] address, // {lut_depth}-bit address signal for {table_entries} values
28
+ output reg [DATA_WIDTH-1:0] value // {data_width}-bit unsigned output signal
29
+ );
30
+
31
+ always @(*) begin
32
+ unique case (address)
33
+ """
34
+ for i, value in enumerate(sine_data):
35
+ verilog_code += f" {lut_depth}'d{i}: value = {data_width}'h{value:X};\n"
36
+
37
+ verilog_code += f""" default: value = {data_width}'h0;
38
+ endcase
39
+ end
40
+
41
+ endmodule
42
+ """
43
+ with open(filename, "w") as f:
44
+ f.write(verilog_code)
45
+
46
+ return verilog_code
47
+
48
+ def generate_verilog_sinewave_generator(lut_depth, data_width, phase_width, filename):
49
+ verilog_code = f"""
50
+ module sinewave_generator #(
51
+ parameter DATA_WIDTH = {data_width},
52
+ LUT_DEPTH = {lut_depth},
53
+ PHASE_WIDTH = {phase_width}
54
+ ) (
55
+ input wire clk,
56
+ input wire arst,
57
+ input wire sample_clk_ce,
58
+ input wire [PHASE_WIDTH-1:0] phase_increment,
59
+ output reg [DATA_WIDTH-1:0] sinewave,
60
+ output reg [DATA_WIDTH-1:0] cosinewave
61
+ );
62
+
63
+ reg [PHASE_WIDTH-1:0] phase_accumulator;
64
+
65
+ sinewave_table #(
66
+ .DATA_WIDTH(DATA_WIDTH),
67
+ .LUT_DEPTH(LUT_DEPTH)
68
+ ) sinewave_inst (
69
+ .address(phase_accumulator[PHASE_WIDTH-1:PHASE_WIDTH-LUT_DEPTH]),
70
+ .value(sinewave)
71
+ );
72
+
73
+ sinewave_table #(
74
+ .DATA_WIDTH(DATA_WIDTH),
75
+ .LUT_DEPTH(LUT_DEPTH)
76
+ ) cosinewave_inst (
77
+ .address((phase_accumulator[PHASE_WIDTH-1:PHASE_WIDTH-LUT_DEPTH] + (1<<(LUT_DEPTH-2))) % (1<<LUT_DEPTH)),
78
+ .value(cosinewave)
79
+ );
80
+
81
+ always @(posedge clk or posedge arst) begin
82
+ if (arst == 1'b1)
83
+ phase_accumulator <= 0;
84
+ else if (sample_clk_ce == 1'b1)
85
+ phase_accumulator <= phase_accumulator + phase_increment;
86
+ end
87
+
88
+ //=============================//
89
+ // For sim only //
90
+ //=============================//
91
+ //`ifdef SIMULATION
92
+ initial begin
93
+ $dumpfile("sinewave_waves.vcd");
94
+ $dumpvars(0, sinewave_generator);
95
+ end
96
+ //`endif
97
+ endmodule
98
+ """
99
+ with open(filename, "w") as f:
100
+ f.write(verilog_code)
101
+
102
+ return verilog_code
103
+
104
+ if __name__ == "__main__":
105
+ parser = argparse.ArgumentParser(description="Generate Verilog sinewave modules")
106
+ parser.add_argument("--lut_depth", "-ld", type=int, default=8, help="Number of address bits for the LUT (default: 8)")
107
+ parser.add_argument("--data_width", "-dw", type=int, default=7, help="Number of output bits for the sine wave (default: 7)")
108
+ parser.add_argument("--phase_width", "-pw", type=int, default=64, help="Number of bits for the phase accumulator (default: 64)")
109
+ parser.add_argument("--lut_filename", "-lf", type=str, default="sinewave_table.v", help="Output filename for the LUT module (default: sinewave_table.v)")
110
+ parser.add_argument("--generator_filename", "-gf", type=str, default="sinewave_generator.v", help="Output filename for the sinewave generator module (default: sinewave_generator.v)")
111
+
112
+ args = parser.parse_args()
113
+
114
+ # Generate the LUT Verilog module
115
+ generate_verilog_lut_module(args.lut_depth, args.data_width, args.lut_filename)
116
+
117
+ # Generate the sinewave generator Verilog module
118
+ generate_verilog_sinewave_generator(args.lut_depth, args.data_width, args.phase_width, args.generator_filename)
chili-chips-ba_openCologne/4.Advanced--4--Yamaha-OPL3-FM-Synth/README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # openCologne - Yamaha OPL3 FM Audio Synth
2
+ ## * WORK IN PROGRESS * UNDER CONSTRUCTION *
3
+ > WHILE THIS NOTICE IS PRESENT, DON'T EXPECT DESIGN, SIM, OR ANY OTHER FILE IN HERE 2BE DOIN' WHAT IT'S SAYIN'
4
+
5
+ This is a triple exciting port of @gtaylormb [project](https://github.com/gtaylormb/opl3_fpga) to _Yosys_ and _GateMate_ FPGA.
6
+ - **Excitment#1**: Original design is super cool on its own, as it is about the heart of the uber-popular _SoundblasterPro_ audio card from the turbulent '90s.
7
+ - **Excitment#2**: RTL is written in, for opensource, unusally rich complement of _SystemVerilog_. The original project had vetted this RTL only with Xilinx-proprietary Vivado. These two circumstances make this codebase a formidable [challenge](https://github.com/chili-chips-ba/openCologne/issues/3) for opensource [Yosys](https://github.com/YosysHQ/yosys) synthesis. And yes, with every challenge comes an opportunity :blush:.
8
+ - **Excitment#3**: As of yet, there are no GateMate designs of this complexity. We are therefore buckled up for a fun, bumpy rollercoaster ride.
9
+
10
+ Regarding excitment/challenge#2, having tried [Synlig plugin](https://github.com/chipsalliance/synlig) and [Yosys-Slang](https://github.com/povik/yosys-slang), we ended up converging on @zachjs's [SV2V](https://github.com/zachjs/sv2v). This can also be viewed as an independant validation and confirmation of @pu-cc's advice on the opensource flow that works best for _SystemVerilog_.
11
+
12
+ To get started, first install SV2V and other tools, as explained in [0.doc](https://github.com/chili-chips-ba/openCologne/blob/main/0.doc/1.README.Tool-Installs.txt). Then:
13
+ ```
14
+ % cd 3.build
15
+ % make synth
16
+ ```
17
+
18
+ This OPL3 design produces 100% digital audio in I2S format. To hear anything, it needs to be complemented with an external compatible audio CODEC, such as:
19
+ > - https://github.com/goran-mahovlic/ulx3s-extensions
20
+ > - https://www.waveshare.com/wm8960-audio-board.htm
21
+
22
+ For fun, also see OPL3 software emulators. Beware, they are not as good and not as precise as this pure hardware, re-engineered Yamaha chip.
23
+ > - https://github.com/Wohlstand/libADLMIDI
24
+ > - https://github.com/nukeykt/Nuked-OPL3
25
+
26
+
27
+ #### End of Document
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/debounce.v ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //fpga4student.com: FPGA projects, Verilog projects, VHDL projects
2
+ // Verilog code for button debouncing on FPGA
3
+ // debouncing module without creating another clock domain
4
+ // by using clock enable signal
5
+ module debounce(
6
+ input clk,
7
+ input in,
8
+ output out
9
+ );
10
+
11
+ wire slow_clk_en;
12
+ wire Q1,Q2,Q2_bar,Q0;
13
+
14
+ clock_enable u1(clk,slow_clk_en);
15
+ my_dff_en d0(clk,slow_clk_en,in,Q0);
16
+ my_dff_en d1(clk,slow_clk_en,Q0,Q1);
17
+ my_dff_en d2(clk,slow_clk_en,Q1,Q2);
18
+
19
+ assign Q2_bar = ~Q2;
20
+ assign out = Q1 & Q2_bar;
21
+ endmodule
22
+
23
+ // Slow clock enable for debouncing button
24
+ module clock_enable(
25
+ input Clk_100M,
26
+ output slow_clk_en
27
+ );
28
+ reg [26:0]counter=0;
29
+
30
+ always @(posedge Clk_100M)
31
+ begin
32
+ counter <= (counter>=24999) ? 0 : counter + 1;
33
+ end
34
+
35
+ assign slow_clk_en = (counter == 24999) ? 1'b1 : 1'b0;
36
+ endmodule
37
+
38
+ // D-flip-flop with clock enable signal for debouncing module
39
+ module my_dff_en(
40
+ input DFF_CLOCK,
41
+ input clock_enable,
42
+ input D,
43
+ output reg Q=0
44
+ );
45
+
46
+ always @ (posedge DFF_CLOCK)
47
+ begin
48
+ if(clock_enable==1)
49
+ Q <= D;
50
+ end
51
+
52
+ endmodule
53
+
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/gatemate_25MHz_pll.v ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * gatemate_25MHz_pll.v
3
+ *
4
+ * Copyright (C) 2022-2024 Gwenhael Goavec-Merou <gwenhael.goavec-merou@trabucayre.com>
5
+ * SPDX-License-Identifier: MIT
6
+ */
7
+ module pll (
8
+ input wire clock_in,
9
+ input wire rst_in,
10
+ output wire clock_out,
11
+ output reg locked
12
+ );
13
+
14
+ wire clk270, clk180, clk90, clk0, usr_ref_out;
15
+ wire usr_pll_lock;
16
+
17
+ wire pll_clk_nobuf;
18
+ CC_PLL #(
19
+ .REF_CLK("10.0"), // reference input in MHz
20
+ .OUT_CLK("25.0"), // pll output frequency in MHz
21
+ .LOCK_REQ(0), // 1: Lock status required before PLL output enable
22
+ // 0: PLL output before lock
23
+ .PERF_MD("SPEED"), // LOWPOWER, ECONOMY, SPEED
24
+ .LOW_JITTER(1), // 0: disable, 1: enable low jitter mode
25
+ .CI_FILTER_CONST(2), // optional CI filter constant
26
+ .CP_FILTER_CONST(4) // optional CP filter constant
27
+ ) pll25 (
28
+ .CLK_REF(clock_in), .CLK_FEEDBACK(1'b0), .USR_CLK_REF(1'b0),
29
+ /* USR_LOCKED_STDY_RST and USR_PLL_LOCKED_STDY are more or less
30
+ * for debug purpose. USR_PLL_LOCKED_STDY is high after first lock
31
+ * goes low if PLL unlock and stay low until USR_LOCKED_STDY_RST is
32
+ * set during 2 clock cycles
33
+ */
34
+ .USR_LOCKED_STDY_RST(1'b0), .USR_PLL_LOCKED_STDY(),
35
+ .USR_PLL_LOCKED(usr_pll_lock),
36
+ .CLK270(clk270), .CLK180(clk180), .CLK90(clk90), .CLK0(pll_clk_nobuf), .CLK_REF_OUT(usr_ref_out)
37
+ );
38
+ CC_BUFG pll_bufg (.I(pll_clk_nobuf), .O(clock_out));
39
+
40
+ // reset is synced the clock
41
+ reg locked_s1;
42
+ always @(posedge clock_out) begin
43
+ locked_s1 <= usr_pll_lock & ~rst_in;
44
+ locked <= locked_s1;
45
+ end
46
+
47
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/picorv32.v ADDED
@@ -0,0 +1,2977 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * PicoRV32 -- A Small RISC-V (RV32I) Processor Core
3
+ *
4
+ * Copyright (C) 2015 Clifford Wolf <clifford@clifford.at>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ `timescale 1 ns / 1 ps
21
+ // `default_nettype none
22
+ // `define DEBUGNETS
23
+ // `define DEBUGREGS
24
+ // `define DEBUGASM
25
+ // `define DEBUG
26
+
27
+ `ifdef DEBUG
28
+ `define debug(debug_command) debug_command
29
+ `else
30
+ `define debug(debug_command)
31
+ `endif
32
+
33
+ `ifdef FORMAL
34
+ `define FORMAL_KEEP (* keep *)
35
+ `define assert(assert_expr) assert(assert_expr)
36
+ `else
37
+ `ifdef DEBUGNETS
38
+ `define FORMAL_KEEP (* keep *)
39
+ `else
40
+ `define FORMAL_KEEP
41
+ `endif
42
+ `define assert(assert_expr) empty_statement
43
+ `endif
44
+
45
+ // uncomment this for register file in extra module
46
+ // `define PICORV32_REGS picorv32_regs
47
+
48
+ // this macro can be used to check if the verilog files in your
49
+ // design are read in the correct order.
50
+ `define PICORV32_V
51
+
52
+
53
+ /***************************************************************
54
+ * picorv32
55
+ ***************************************************************/
56
+
57
+ module picorv32 #(
58
+ parameter [ 0:0] ENABLE_COUNTERS = 1,
59
+ parameter [ 0:0] ENABLE_COUNTERS64 = 1,
60
+ parameter [ 0:0] ENABLE_REGS_16_31 = 1,
61
+ parameter [ 0:0] ENABLE_REGS_DUALPORT = 1,
62
+ parameter [ 0:0] LATCHED_MEM_RDATA = 0,
63
+ parameter [ 0:0] TWO_STAGE_SHIFT = 1,
64
+ parameter [ 0:0] BARREL_SHIFTER = 0,
65
+ parameter [ 0:0] TWO_CYCLE_COMPARE = 0,
66
+ parameter [ 0:0] TWO_CYCLE_ALU = 0,
67
+ parameter [ 0:0] COMPRESSED_ISA = 0,
68
+ parameter [ 0:0] CATCH_MISALIGN = 1,
69
+ parameter [ 0:0] CATCH_ILLINSN = 1,
70
+ parameter [ 0:0] ENABLE_PCPI = 0,
71
+ parameter [ 0:0] ENABLE_MUL = 0,
72
+ parameter [ 0:0] ENABLE_FAST_MUL = 0,
73
+ parameter [ 0:0] ENABLE_DIV = 0,
74
+ parameter [ 0:0] ENABLE_IRQ = 0,
75
+ parameter [ 0:0] ENABLE_IRQ_QREGS = 1,
76
+ parameter [ 0:0] ENABLE_IRQ_TIMER = 1,
77
+ parameter [ 0:0] ENABLE_TRACE = 0,
78
+ parameter [ 0:0] REGS_INIT_ZERO = 0,
79
+ parameter [31:0] MASKED_IRQ = 32'h 0000_0000,
80
+ parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff,
81
+ parameter [31:0] PROGADDR_RESET = 32'h 0010_0000,
82
+ parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010,
83
+ parameter [31:0] STACKADDR = 32'h ffff_ffff
84
+ ) (
85
+ input clk, resetn,
86
+ output reg trap,
87
+
88
+ output reg mem_valid,
89
+ output reg mem_instr,
90
+ input mem_ready,
91
+
92
+ output reg [31:0] mem_addr,
93
+ output reg [31:0] mem_wdata,
94
+ output reg [ 3:0] mem_wstrb,
95
+ input [31:0] mem_rdata,
96
+
97
+ // Look-Ahead Interface
98
+ output mem_la_read,
99
+ output mem_la_write,
100
+ output [31:0] mem_la_addr,
101
+ output reg [31:0] mem_la_wdata,
102
+ output reg [ 3:0] mem_la_wstrb,
103
+
104
+ // Pico Co-Processor Interface (PCPI)
105
+ output reg pcpi_valid,
106
+ output reg [31:0] pcpi_insn,
107
+ output [31:0] pcpi_rs1,
108
+ output [31:0] pcpi_rs2,
109
+ input pcpi_wr,
110
+ input [31:0] pcpi_rd,
111
+ input pcpi_wait,
112
+ input pcpi_ready,
113
+
114
+ // IRQ Interface
115
+ input [31:0] irq,
116
+ output reg [31:0] eoi,
117
+
118
+ `ifdef RISCV_FORMAL
119
+ output reg rvfi_valid,
120
+ output reg [63:0] rvfi_order,
121
+ output reg [31:0] rvfi_insn,
122
+ output reg rvfi_trap,
123
+ output reg rvfi_halt,
124
+ output reg rvfi_intr,
125
+ output reg [ 4:0] rvfi_rs1_addr,
126
+ output reg [ 4:0] rvfi_rs2_addr,
127
+ output reg [31:0] rvfi_rs1_rdata,
128
+ output reg [31:0] rvfi_rs2_rdata,
129
+ output reg [ 4:0] rvfi_rd_addr,
130
+ output reg [31:0] rvfi_rd_wdata,
131
+ output reg [31:0] rvfi_pc_rdata,
132
+ output reg [31:0] rvfi_pc_wdata,
133
+ output reg [31:0] rvfi_mem_addr,
134
+ output reg [ 3:0] rvfi_mem_rmask,
135
+ output reg [ 3:0] rvfi_mem_wmask,
136
+ output reg [31:0] rvfi_mem_rdata,
137
+ output reg [31:0] rvfi_mem_wdata,
138
+ `endif
139
+
140
+ // Trace Interface
141
+ output reg trace_valid,
142
+ output reg [35:0] trace_data
143
+ );
144
+ localparam integer irq_timer = 0;
145
+ localparam integer irq_ebreak = 1;
146
+ localparam integer irq_buserror = 2;
147
+
148
+ localparam integer irqregs_offset = ENABLE_REGS_16_31 ? 32 : 16;
149
+ localparam integer regfile_size = (ENABLE_REGS_16_31 ? 32 : 16) + 4*ENABLE_IRQ*ENABLE_IRQ_QREGS;
150
+ localparam integer regindex_bits = (ENABLE_REGS_16_31 ? 5 : 4) + ENABLE_IRQ*ENABLE_IRQ_QREGS;
151
+
152
+ localparam WITH_PCPI = ENABLE_PCPI || ENABLE_MUL || ENABLE_FAST_MUL || ENABLE_DIV;
153
+
154
+ localparam [35:0] TRACE_BRANCH = {4'b 0001, 32'b 0};
155
+ localparam [35:0] TRACE_ADDR = {4'b 0010, 32'b 0};
156
+ localparam [35:0] TRACE_IRQ = {4'b 1000, 32'b 0};
157
+
158
+ reg [63:0] count_cycle, count_instr;
159
+ reg [31:0] reg_pc, reg_next_pc, reg_op1, reg_op2, reg_out;
160
+ reg [4:0] reg_sh;
161
+
162
+ reg [31:0] next_insn_opcode;
163
+ reg [31:0] dbg_insn_opcode;
164
+ reg [31:0] dbg_insn_addr;
165
+
166
+ wire dbg_mem_valid = mem_valid;
167
+ wire dbg_mem_instr = mem_instr;
168
+ wire dbg_mem_ready = mem_ready;
169
+ wire [31:0] dbg_mem_addr = mem_addr;
170
+ wire [31:0] dbg_mem_wdata = mem_wdata;
171
+ wire [ 3:0] dbg_mem_wstrb = mem_wstrb;
172
+ wire [31:0] dbg_mem_rdata = mem_rdata;
173
+
174
+ assign pcpi_rs1 = reg_op1;
175
+ assign pcpi_rs2 = reg_op2;
176
+
177
+ wire [31:0] next_pc;
178
+
179
+ reg irq_delay;
180
+ reg irq_active;
181
+ reg [31:0] irq_mask;
182
+ reg [31:0] irq_pending;
183
+ reg [31:0] timer;
184
+
185
+ `ifndef PICORV32_REGS
186
+ reg [31:0] cpuregs [0:regfile_size-1];
187
+
188
+ integer i;
189
+ initial begin
190
+ if (REGS_INIT_ZERO) begin
191
+ for (i = 0; i < regfile_size; i = i+1)
192
+ cpuregs[i] = 0;
193
+ end
194
+ end
195
+ `endif
196
+
197
+ task empty_statement;
198
+ // This task is used by the `assert directive in non-formal mode to
199
+ // avoid empty statement (which are unsupported by plain Verilog syntax).
200
+ begin end
201
+ endtask
202
+
203
+ `ifdef DEBUGREGS
204
+ wire [31:0] dbg_reg_x0 = 0;
205
+ wire [31:0] dbg_reg_x1 = cpuregs[1];
206
+ wire [31:0] dbg_reg_x2 = cpuregs[2];
207
+ wire [31:0] dbg_reg_x3 = cpuregs[3];
208
+ wire [31:0] dbg_reg_x4 = cpuregs[4];
209
+ wire [31:0] dbg_reg_x5 = cpuregs[5];
210
+ wire [31:0] dbg_reg_x6 = cpuregs[6];
211
+ wire [31:0] dbg_reg_x7 = cpuregs[7];
212
+ wire [31:0] dbg_reg_x8 = cpuregs[8];
213
+ wire [31:0] dbg_reg_x9 = cpuregs[9];
214
+ wire [31:0] dbg_reg_x10 = cpuregs[10];
215
+ wire [31:0] dbg_reg_x11 = cpuregs[11];
216
+ wire [31:0] dbg_reg_x12 = cpuregs[12];
217
+ wire [31:0] dbg_reg_x13 = cpuregs[13];
218
+ wire [31:0] dbg_reg_x14 = cpuregs[14];
219
+ wire [31:0] dbg_reg_x15 = cpuregs[15];
220
+ wire [31:0] dbg_reg_x16 = cpuregs[16];
221
+ wire [31:0] dbg_reg_x17 = cpuregs[17];
222
+ wire [31:0] dbg_reg_x18 = cpuregs[18];
223
+ wire [31:0] dbg_reg_x19 = cpuregs[19];
224
+ wire [31:0] dbg_reg_x20 = cpuregs[20];
225
+ wire [31:0] dbg_reg_x21 = cpuregs[21];
226
+ wire [31:0] dbg_reg_x22 = cpuregs[22];
227
+ wire [31:0] dbg_reg_x23 = cpuregs[23];
228
+ wire [31:0] dbg_reg_x24 = cpuregs[24];
229
+ wire [31:0] dbg_reg_x25 = cpuregs[25];
230
+ wire [31:0] dbg_reg_x26 = cpuregs[26];
231
+ wire [31:0] dbg_reg_x27 = cpuregs[27];
232
+ wire [31:0] dbg_reg_x28 = cpuregs[28];
233
+ wire [31:0] dbg_reg_x29 = cpuregs[29];
234
+ wire [31:0] dbg_reg_x30 = cpuregs[30];
235
+ wire [31:0] dbg_reg_x31 = cpuregs[31];
236
+ `endif
237
+
238
+ // Internal PCPI Cores
239
+
240
+ wire pcpi_mul_wr;
241
+ wire [31:0] pcpi_mul_rd;
242
+ wire pcpi_mul_wait;
243
+ wire pcpi_mul_ready;
244
+
245
+ wire pcpi_div_wr;
246
+ wire [31:0] pcpi_div_rd;
247
+ wire pcpi_div_wait;
248
+ wire pcpi_div_ready;
249
+
250
+ reg pcpi_int_wr;
251
+ reg [31:0] pcpi_int_rd;
252
+ reg pcpi_int_wait;
253
+ reg pcpi_int_ready;
254
+
255
+ generate if (ENABLE_FAST_MUL) begin
256
+ picorv32_pcpi_fast_mul pcpi_mul (
257
+ .clk (clk ),
258
+ .resetn (resetn ),
259
+ .pcpi_valid(pcpi_valid ),
260
+ .pcpi_insn (pcpi_insn ),
261
+ .pcpi_rs1 (pcpi_rs1 ),
262
+ .pcpi_rs2 (pcpi_rs2 ),
263
+ .pcpi_wr (pcpi_mul_wr ),
264
+ .pcpi_rd (pcpi_mul_rd ),
265
+ .pcpi_wait (pcpi_mul_wait ),
266
+ .pcpi_ready(pcpi_mul_ready )
267
+ );
268
+ end else if (ENABLE_MUL) begin
269
+ picorv32_pcpi_mul pcpi_mul (
270
+ .clk (clk ),
271
+ .resetn (resetn ),
272
+ .pcpi_valid(pcpi_valid ),
273
+ .pcpi_insn (pcpi_insn ),
274
+ .pcpi_rs1 (pcpi_rs1 ),
275
+ .pcpi_rs2 (pcpi_rs2 ),
276
+ .pcpi_wr (pcpi_mul_wr ),
277
+ .pcpi_rd (pcpi_mul_rd ),
278
+ .pcpi_wait (pcpi_mul_wait ),
279
+ .pcpi_ready(pcpi_mul_ready )
280
+ );
281
+ end else begin
282
+ assign pcpi_mul_wr = 0;
283
+ assign pcpi_mul_rd = 32'bx;
284
+ assign pcpi_mul_wait = 0;
285
+ assign pcpi_mul_ready = 0;
286
+ end endgenerate
287
+
288
+ generate if (ENABLE_DIV) begin
289
+ picorv32_pcpi_div pcpi_div (
290
+ .clk (clk ),
291
+ .resetn (resetn ),
292
+ .pcpi_valid(pcpi_valid ),
293
+ .pcpi_insn (pcpi_insn ),
294
+ .pcpi_rs1 (pcpi_rs1 ),
295
+ .pcpi_rs2 (pcpi_rs2 ),
296
+ .pcpi_wr (pcpi_div_wr ),
297
+ .pcpi_rd (pcpi_div_rd ),
298
+ .pcpi_wait (pcpi_div_wait ),
299
+ .pcpi_ready(pcpi_div_ready )
300
+ );
301
+ end else begin
302
+ assign pcpi_div_wr = 0;
303
+ assign pcpi_div_rd = 32'bx;
304
+ assign pcpi_div_wait = 0;
305
+ assign pcpi_div_ready = 0;
306
+ end endgenerate
307
+
308
+ always @* begin
309
+ pcpi_int_wr = 0;
310
+ pcpi_int_rd = 32'bx;
311
+ pcpi_int_wait = |{ENABLE_PCPI && pcpi_wait, (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_wait, ENABLE_DIV && pcpi_div_wait};
312
+ pcpi_int_ready = |{ENABLE_PCPI && pcpi_ready, (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_ready, ENABLE_DIV && pcpi_div_ready};
313
+
314
+ (* parallel_case *)
315
+ case (1'b1)
316
+ ENABLE_PCPI && pcpi_ready: begin
317
+ pcpi_int_wr = ENABLE_PCPI ? pcpi_wr : 0;
318
+ pcpi_int_rd = ENABLE_PCPI ? pcpi_rd : 0;
319
+ end
320
+ (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_ready: begin
321
+ pcpi_int_wr = pcpi_mul_wr;
322
+ pcpi_int_rd = pcpi_mul_rd;
323
+ end
324
+ ENABLE_DIV && pcpi_div_ready: begin
325
+ pcpi_int_wr = pcpi_div_wr;
326
+ pcpi_int_rd = pcpi_div_rd;
327
+ end
328
+ endcase
329
+ end
330
+
331
+
332
+ // Memory Interface
333
+
334
+ reg [1:0] mem_state;
335
+ reg [1:0] mem_wordsize;
336
+ reg [31:0] mem_rdata_word;
337
+ reg [31:0] mem_rdata_q;
338
+ reg mem_do_prefetch;
339
+ reg mem_do_rinst;
340
+ reg mem_do_rdata;
341
+ reg mem_do_wdata;
342
+
343
+ wire mem_xfer;
344
+ reg mem_la_secondword, mem_la_firstword_reg, last_mem_valid;
345
+ wire mem_la_firstword = COMPRESSED_ISA && (mem_do_prefetch || mem_do_rinst) && next_pc[1] && !mem_la_secondword;
346
+ wire mem_la_firstword_xfer = COMPRESSED_ISA && mem_xfer && (!last_mem_valid ? mem_la_firstword : mem_la_firstword_reg);
347
+
348
+ reg prefetched_high_word;
349
+ reg clear_prefetched_high_word;
350
+ reg [15:0] mem_16bit_buffer;
351
+
352
+ wire [31:0] mem_rdata_latched_noshuffle;
353
+ wire [31:0] mem_rdata_latched;
354
+
355
+ wire mem_la_use_prefetched_high_word = COMPRESSED_ISA && mem_la_firstword && prefetched_high_word && !clear_prefetched_high_word;
356
+ assign mem_xfer = (mem_valid && mem_ready) || (mem_la_use_prefetched_high_word && mem_do_rinst);
357
+
358
+ wire mem_busy = |{mem_do_prefetch, mem_do_rinst, mem_do_rdata, mem_do_wdata};
359
+ wire mem_done = resetn && ((mem_xfer && |mem_state && (mem_do_rinst || mem_do_rdata || mem_do_wdata)) || (&mem_state && mem_do_rinst)) &&
360
+ (!mem_la_firstword || (~&mem_rdata_latched[1:0] && mem_xfer));
361
+
362
+ assign mem_la_write = resetn && !mem_state && mem_do_wdata;
363
+ assign mem_la_read = resetn && ((!mem_la_use_prefetched_high_word && !mem_state && (mem_do_rinst || mem_do_prefetch || mem_do_rdata)) ||
364
+ (COMPRESSED_ISA && mem_xfer && (!last_mem_valid ? mem_la_firstword : mem_la_firstword_reg) && !mem_la_secondword && &mem_rdata_latched[1:0]));
365
+ assign mem_la_addr = (mem_do_prefetch || mem_do_rinst) ? {next_pc[31:2] + mem_la_firstword_xfer, 2'b00} : {reg_op1[31:2], 2'b00};
366
+
367
+ assign mem_rdata_latched_noshuffle = (mem_xfer || LATCHED_MEM_RDATA) ? mem_rdata : mem_rdata_q;
368
+
369
+ assign mem_rdata_latched = COMPRESSED_ISA && mem_la_use_prefetched_high_word ? {16'bx, mem_16bit_buffer} :
370
+ COMPRESSED_ISA && mem_la_secondword ? {mem_rdata_latched_noshuffle[15:0], mem_16bit_buffer} :
371
+ COMPRESSED_ISA && mem_la_firstword ? {16'bx, mem_rdata_latched_noshuffle[31:16]} : mem_rdata_latched_noshuffle;
372
+
373
+ always @(posedge clk) begin
374
+ if (!resetn) begin
375
+ mem_la_firstword_reg <= 0;
376
+ last_mem_valid <= 0;
377
+ end else begin
378
+ if (!last_mem_valid)
379
+ mem_la_firstword_reg <= mem_la_firstword;
380
+ last_mem_valid <= mem_valid && !mem_ready;
381
+ end
382
+ end
383
+
384
+ always @* begin
385
+ (* full_case *)
386
+ case (mem_wordsize)
387
+ 0: begin
388
+ mem_la_wdata = reg_op2;
389
+ mem_la_wstrb = 4'b1111;
390
+ mem_rdata_word = mem_rdata;
391
+ end
392
+ 1: begin
393
+ mem_la_wdata = {2{reg_op2[15:0]}};
394
+ mem_la_wstrb = reg_op1[1] ? 4'b1100 : 4'b0011;
395
+ case (reg_op1[1])
396
+ 1'b0: mem_rdata_word = {16'b0, mem_rdata[15: 0]};
397
+ 1'b1: mem_rdata_word = {16'b0, mem_rdata[31:16]};
398
+ endcase
399
+ end
400
+ 2: begin
401
+ mem_la_wdata = {4{reg_op2[7:0]}};
402
+ mem_la_wstrb = 4'b0001 << reg_op1[1:0];
403
+ case (reg_op1[1:0])
404
+ 2'b00: mem_rdata_word = {24'b0, mem_rdata[ 7: 0]};
405
+ 2'b01: mem_rdata_word = {24'b0, mem_rdata[15: 8]};
406
+ 2'b10: mem_rdata_word = {24'b0, mem_rdata[23:16]};
407
+ 2'b11: mem_rdata_word = {24'b0, mem_rdata[31:24]};
408
+ endcase
409
+ end
410
+ endcase
411
+ end
412
+
413
+ always @(posedge clk) begin
414
+ if (mem_xfer) begin
415
+ mem_rdata_q <= COMPRESSED_ISA ? mem_rdata_latched : mem_rdata;
416
+ next_insn_opcode <= COMPRESSED_ISA ? mem_rdata_latched : mem_rdata;
417
+ end
418
+
419
+ if (COMPRESSED_ISA && mem_done && (mem_do_prefetch || mem_do_rinst)) begin
420
+ case (mem_rdata_latched[1:0])
421
+ 2'b00: begin // Quadrant 0
422
+ case (mem_rdata_latched[15:13])
423
+ 3'b000: begin // C.ADDI4SPN
424
+ mem_rdata_q[14:12] <= 3'b000;
425
+ mem_rdata_q[31:20] <= {2'b0, mem_rdata_latched[10:7], mem_rdata_latched[12:11], mem_rdata_latched[5], mem_rdata_latched[6], 2'b00};
426
+ end
427
+ 3'b010: begin // C.LW
428
+ mem_rdata_q[31:20] <= {5'b0, mem_rdata_latched[5], mem_rdata_latched[12:10], mem_rdata_latched[6], 2'b00};
429
+ mem_rdata_q[14:12] <= 3'b 010;
430
+ end
431
+ 3'b 110: begin // C.SW
432
+ {mem_rdata_q[31:25], mem_rdata_q[11:7]} <= {5'b0, mem_rdata_latched[5], mem_rdata_latched[12:10], mem_rdata_latched[6], 2'b00};
433
+ mem_rdata_q[14:12] <= 3'b 010;
434
+ end
435
+ endcase
436
+ end
437
+ 2'b01: begin // Quadrant 1
438
+ case (mem_rdata_latched[15:13])
439
+ 3'b 000: begin // C.ADDI
440
+ mem_rdata_q[14:12] <= 3'b000;
441
+ mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]});
442
+ end
443
+ 3'b 010: begin // C.LI
444
+ mem_rdata_q[14:12] <= 3'b000;
445
+ mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]});
446
+ end
447
+ 3'b 011: begin
448
+ if (mem_rdata_latched[11:7] == 2) begin // C.ADDI16SP
449
+ mem_rdata_q[14:12] <= 3'b000;
450
+ mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[4:3],
451
+ mem_rdata_latched[5], mem_rdata_latched[2], mem_rdata_latched[6], 4'b 0000});
452
+ end else begin // C.LUI
453
+ mem_rdata_q[31:12] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]});
454
+ end
455
+ end
456
+ 3'b100: begin
457
+ if (mem_rdata_latched[11:10] == 2'b00) begin // C.SRLI
458
+ mem_rdata_q[31:25] <= 7'b0000000;
459
+ mem_rdata_q[14:12] <= 3'b 101;
460
+ end
461
+ if (mem_rdata_latched[11:10] == 2'b01) begin // C.SRAI
462
+ mem_rdata_q[31:25] <= 7'b0100000;
463
+ mem_rdata_q[14:12] <= 3'b 101;
464
+ end
465
+ if (mem_rdata_latched[11:10] == 2'b10) begin // C.ANDI
466
+ mem_rdata_q[14:12] <= 3'b111;
467
+ mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]});
468
+ end
469
+ if (mem_rdata_latched[12:10] == 3'b011) begin // C.SUB, C.XOR, C.OR, C.AND
470
+ if (mem_rdata_latched[6:5] == 2'b00) mem_rdata_q[14:12] <= 3'b000;
471
+ if (mem_rdata_latched[6:5] == 2'b01) mem_rdata_q[14:12] <= 3'b100;
472
+ if (mem_rdata_latched[6:5] == 2'b10) mem_rdata_q[14:12] <= 3'b110;
473
+ if (mem_rdata_latched[6:5] == 2'b11) mem_rdata_q[14:12] <= 3'b111;
474
+ mem_rdata_q[31:25] <= mem_rdata_latched[6:5] == 2'b00 ? 7'b0100000 : 7'b0000000;
475
+ end
476
+ end
477
+ 3'b 110: begin // C.BEQZ
478
+ mem_rdata_q[14:12] <= 3'b000;
479
+ { mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8] } <=
480
+ $signed({mem_rdata_latched[12], mem_rdata_latched[6:5], mem_rdata_latched[2],
481
+ mem_rdata_latched[11:10], mem_rdata_latched[4:3]});
482
+ end
483
+ 3'b 111: begin // C.BNEZ
484
+ mem_rdata_q[14:12] <= 3'b001;
485
+ { mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8] } <=
486
+ $signed({mem_rdata_latched[12], mem_rdata_latched[6:5], mem_rdata_latched[2],
487
+ mem_rdata_latched[11:10], mem_rdata_latched[4:3]});
488
+ end
489
+ endcase
490
+ end
491
+ 2'b10: begin // Quadrant 2
492
+ case (mem_rdata_latched[15:13])
493
+ 3'b000: begin // C.SLLI
494
+ mem_rdata_q[31:25] <= 7'b0000000;
495
+ mem_rdata_q[14:12] <= 3'b 001;
496
+ end
497
+ 3'b010: begin // C.LWSP
498
+ mem_rdata_q[31:20] <= {4'b0, mem_rdata_latched[3:2], mem_rdata_latched[12], mem_rdata_latched[6:4], 2'b00};
499
+ mem_rdata_q[14:12] <= 3'b 010;
500
+ end
501
+ 3'b100: begin
502
+ if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] == 0) begin // C.JR
503
+ mem_rdata_q[14:12] <= 3'b000;
504
+ mem_rdata_q[31:20] <= 12'b0;
505
+ end
506
+ if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] != 0) begin // C.MV
507
+ mem_rdata_q[14:12] <= 3'b000;
508
+ mem_rdata_q[31:25] <= 7'b0000000;
509
+ end
510
+ if (mem_rdata_latched[12] != 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JALR
511
+ mem_rdata_q[14:12] <= 3'b000;
512
+ mem_rdata_q[31:20] <= 12'b0;
513
+ end
514
+ if (mem_rdata_latched[12] != 0 && mem_rdata_latched[6:2] != 0) begin // C.ADD
515
+ mem_rdata_q[14:12] <= 3'b000;
516
+ mem_rdata_q[31:25] <= 7'b0000000;
517
+ end
518
+ end
519
+ 3'b110: begin // C.SWSP
520
+ {mem_rdata_q[31:25], mem_rdata_q[11:7]} <= {4'b0, mem_rdata_latched[8:7], mem_rdata_latched[12:9], 2'b00};
521
+ mem_rdata_q[14:12] <= 3'b 010;
522
+ end
523
+ endcase
524
+ end
525
+ endcase
526
+ end
527
+ end
528
+
529
+ always @(posedge clk) begin
530
+ if (resetn && !trap) begin
531
+ if (mem_do_prefetch || mem_do_rinst || mem_do_rdata)
532
+ `assert(!mem_do_wdata);
533
+
534
+ if (mem_do_prefetch || mem_do_rinst)
535
+ `assert(!mem_do_rdata);
536
+
537
+ if (mem_do_rdata)
538
+ `assert(!mem_do_prefetch && !mem_do_rinst);
539
+
540
+ if (mem_do_wdata)
541
+ `assert(!(mem_do_prefetch || mem_do_rinst || mem_do_rdata));
542
+
543
+ if (mem_state == 2 || mem_state == 3)
544
+ `assert(mem_valid || mem_do_prefetch);
545
+ end
546
+ end
547
+
548
+ always @(posedge clk) begin
549
+ if (!resetn || trap) begin
550
+ if (!resetn)
551
+ mem_state <= 0;
552
+ if (!resetn || mem_ready)
553
+ mem_valid <= 0;
554
+ mem_la_secondword <= 0;
555
+ prefetched_high_word <= 0;
556
+ end else begin
557
+ if (mem_la_read || mem_la_write) begin
558
+ mem_addr <= mem_la_addr;
559
+ mem_wstrb <= mem_la_wstrb & {4{mem_la_write}};
560
+ end
561
+ if (mem_la_write) begin
562
+ mem_wdata <= mem_la_wdata;
563
+ end
564
+ case (mem_state)
565
+ 0: begin
566
+ if (mem_do_prefetch || mem_do_rinst || mem_do_rdata) begin
567
+ mem_valid <= !mem_la_use_prefetched_high_word;
568
+ mem_instr <= mem_do_prefetch || mem_do_rinst;
569
+ mem_wstrb <= 0;
570
+ mem_state <= 1;
571
+ end
572
+ if (mem_do_wdata) begin
573
+ mem_valid <= 1;
574
+ mem_instr <= 0;
575
+ mem_state <= 2;
576
+ end
577
+ end
578
+ 1: begin
579
+ `assert(mem_wstrb == 0);
580
+ `assert(mem_do_prefetch || mem_do_rinst || mem_do_rdata);
581
+ `assert(mem_valid == !mem_la_use_prefetched_high_word);
582
+ `assert(mem_instr == (mem_do_prefetch || mem_do_rinst));
583
+ if (mem_xfer) begin
584
+ if (COMPRESSED_ISA && mem_la_read) begin
585
+ mem_valid <= 1;
586
+ mem_la_secondword <= 1;
587
+ if (!mem_la_use_prefetched_high_word)
588
+ mem_16bit_buffer <= mem_rdata[31:16];
589
+ end else begin
590
+ mem_valid <= 0;
591
+ mem_la_secondword <= 0;
592
+ if (COMPRESSED_ISA && !mem_do_rdata) begin
593
+ if (~&mem_rdata[1:0] || mem_la_secondword) begin
594
+ mem_16bit_buffer <= mem_rdata[31:16];
595
+ prefetched_high_word <= 1;
596
+ end else begin
597
+ prefetched_high_word <= 0;
598
+ end
599
+ end
600
+ mem_state <= mem_do_rinst || mem_do_rdata ? 0 : 3;
601
+ end
602
+ end
603
+ end
604
+ 2: begin
605
+ `assert(mem_wstrb != 0);
606
+ `assert(mem_do_wdata);
607
+ if (mem_xfer) begin
608
+ mem_valid <= 0;
609
+ mem_state <= 0;
610
+ end
611
+ end
612
+ 3: begin
613
+ `assert(mem_wstrb == 0);
614
+ `assert(mem_do_prefetch);
615
+ if (mem_do_rinst) begin
616
+ mem_state <= 0;
617
+ end
618
+ end
619
+ endcase
620
+ end
621
+
622
+ if (clear_prefetched_high_word)
623
+ prefetched_high_word <= 0;
624
+ end
625
+
626
+
627
+ // Instruction Decoder
628
+
629
+ reg instr_lui, instr_auipc, instr_jal, instr_jalr;
630
+ reg instr_beq, instr_bne, instr_blt, instr_bge, instr_bltu, instr_bgeu;
631
+ reg instr_lb, instr_lh, instr_lw, instr_lbu, instr_lhu, instr_sb, instr_sh, instr_sw;
632
+ reg instr_addi, instr_slti, instr_sltiu, instr_xori, instr_ori, instr_andi, instr_slli, instr_srli, instr_srai;
633
+ reg instr_add, instr_sub, instr_sll, instr_slt, instr_sltu, instr_xor, instr_srl, instr_sra, instr_or, instr_and;
634
+ reg instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh, instr_ecall_ebreak;
635
+ reg instr_getq, instr_setq, instr_retirq, instr_maskirq, instr_waitirq, instr_timer;
636
+ wire instr_trap;
637
+
638
+ reg [regindex_bits-1:0] decoded_rd, decoded_rs1, decoded_rs2;
639
+ reg [31:0] decoded_imm, decoded_imm_uj;
640
+ reg decoder_trigger;
641
+ reg decoder_trigger_q;
642
+ reg decoder_pseudo_trigger;
643
+ reg decoder_pseudo_trigger_q;
644
+ reg compressed_instr;
645
+
646
+ reg is_lui_auipc_jal;
647
+ reg is_lb_lh_lw_lbu_lhu;
648
+ reg is_slli_srli_srai;
649
+ reg is_jalr_addi_slti_sltiu_xori_ori_andi;
650
+ reg is_sb_sh_sw;
651
+ reg is_sll_srl_sra;
652
+ reg is_lui_auipc_jal_jalr_addi_add_sub;
653
+ reg is_slti_blt_slt;
654
+ reg is_sltiu_bltu_sltu;
655
+ reg is_beq_bne_blt_bge_bltu_bgeu;
656
+ reg is_lbu_lhu_lw;
657
+ reg is_alu_reg_imm;
658
+ reg is_alu_reg_reg;
659
+ reg is_compare;
660
+
661
+ assign instr_trap = (CATCH_ILLINSN || WITH_PCPI) && !{instr_lui, instr_auipc, instr_jal, instr_jalr,
662
+ instr_beq, instr_bne, instr_blt, instr_bge, instr_bltu, instr_bgeu,
663
+ instr_lb, instr_lh, instr_lw, instr_lbu, instr_lhu, instr_sb, instr_sh, instr_sw,
664
+ instr_addi, instr_slti, instr_sltiu, instr_xori, instr_ori, instr_andi, instr_slli, instr_srli, instr_srai,
665
+ instr_add, instr_sub, instr_sll, instr_slt, instr_sltu, instr_xor, instr_srl, instr_sra, instr_or, instr_and,
666
+ instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh,
667
+ instr_getq, instr_setq, instr_retirq, instr_maskirq, instr_waitirq, instr_timer};
668
+
669
+ wire is_rdcycle_rdcycleh_rdinstr_rdinstrh;
670
+ assign is_rdcycle_rdcycleh_rdinstr_rdinstrh = |{instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh};
671
+
672
+ reg [63:0] new_ascii_instr;
673
+ `FORMAL_KEEP reg [63:0] dbg_ascii_instr;
674
+ `FORMAL_KEEP reg [31:0] dbg_insn_imm;
675
+ `FORMAL_KEEP reg [4:0] dbg_insn_rs1;
676
+ `FORMAL_KEEP reg [4:0] dbg_insn_rs2;
677
+ `FORMAL_KEEP reg [4:0] dbg_insn_rd;
678
+ `FORMAL_KEEP reg [31:0] dbg_rs1val;
679
+ `FORMAL_KEEP reg [31:0] dbg_rs2val;
680
+ `FORMAL_KEEP reg dbg_rs1val_valid;
681
+ `FORMAL_KEEP reg dbg_rs2val_valid;
682
+
683
+ always @* begin
684
+ new_ascii_instr = "";
685
+
686
+ if (instr_lui) new_ascii_instr = "lui";
687
+ if (instr_auipc) new_ascii_instr = "auipc";
688
+ if (instr_jal) new_ascii_instr = "jal";
689
+ if (instr_jalr) new_ascii_instr = "jalr";
690
+
691
+ if (instr_beq) new_ascii_instr = "beq";
692
+ if (instr_bne) new_ascii_instr = "bne";
693
+ if (instr_blt) new_ascii_instr = "blt";
694
+ if (instr_bge) new_ascii_instr = "bge";
695
+ if (instr_bltu) new_ascii_instr = "bltu";
696
+ if (instr_bgeu) new_ascii_instr = "bgeu";
697
+
698
+ if (instr_lb) new_ascii_instr = "lb";
699
+ if (instr_lh) new_ascii_instr = "lh";
700
+ if (instr_lw) new_ascii_instr = "lw";
701
+ if (instr_lbu) new_ascii_instr = "lbu";
702
+ if (instr_lhu) new_ascii_instr = "lhu";
703
+ if (instr_sb) new_ascii_instr = "sb";
704
+ if (instr_sh) new_ascii_instr = "sh";
705
+ if (instr_sw) new_ascii_instr = "sw";
706
+
707
+ if (instr_addi) new_ascii_instr = "addi";
708
+ if (instr_slti) new_ascii_instr = "slti";
709
+ if (instr_sltiu) new_ascii_instr = "sltiu";
710
+ if (instr_xori) new_ascii_instr = "xori";
711
+ if (instr_ori) new_ascii_instr = "ori";
712
+ if (instr_andi) new_ascii_instr = "andi";
713
+ if (instr_slli) new_ascii_instr = "slli";
714
+ if (instr_srli) new_ascii_instr = "srli";
715
+ if (instr_srai) new_ascii_instr = "srai";
716
+
717
+ if (instr_add) new_ascii_instr = "add";
718
+ if (instr_sub) new_ascii_instr = "sub";
719
+ if (instr_sll) new_ascii_instr = "sll";
720
+ if (instr_slt) new_ascii_instr = "slt";
721
+ if (instr_sltu) new_ascii_instr = "sltu";
722
+ if (instr_xor) new_ascii_instr = "xor";
723
+ if (instr_srl) new_ascii_instr = "srl";
724
+ if (instr_sra) new_ascii_instr = "sra";
725
+ if (instr_or) new_ascii_instr = "or";
726
+ if (instr_and) new_ascii_instr = "and";
727
+
728
+ if (instr_rdcycle) new_ascii_instr = "rdcycle";
729
+ if (instr_rdcycleh) new_ascii_instr = "rdcycleh";
730
+ if (instr_rdinstr) new_ascii_instr = "rdinstr";
731
+ if (instr_rdinstrh) new_ascii_instr = "rdinstrh";
732
+
733
+ if (instr_getq) new_ascii_instr = "getq";
734
+ if (instr_setq) new_ascii_instr = "setq";
735
+ if (instr_retirq) new_ascii_instr = "retirq";
736
+ if (instr_maskirq) new_ascii_instr = "maskirq";
737
+ if (instr_waitirq) new_ascii_instr = "waitirq";
738
+ if (instr_timer) new_ascii_instr = "timer";
739
+ end
740
+
741
+ reg [63:0] q_ascii_instr;
742
+ reg [31:0] q_insn_imm;
743
+ reg [31:0] q_insn_opcode;
744
+ reg [4:0] q_insn_rs1;
745
+ reg [4:0] q_insn_rs2;
746
+ reg [4:0] q_insn_rd;
747
+ reg dbg_next;
748
+
749
+ wire launch_next_insn;
750
+ reg dbg_valid_insn;
751
+
752
+ reg [63:0] cached_ascii_instr;
753
+ reg [31:0] cached_insn_imm;
754
+ reg [31:0] cached_insn_opcode;
755
+ reg [4:0] cached_insn_rs1;
756
+ reg [4:0] cached_insn_rs2;
757
+ reg [4:0] cached_insn_rd;
758
+
759
+ always @(posedge clk) begin
760
+ q_ascii_instr <= dbg_ascii_instr;
761
+ q_insn_imm <= dbg_insn_imm;
762
+ q_insn_opcode <= dbg_insn_opcode;
763
+ q_insn_rs1 <= dbg_insn_rs1;
764
+ q_insn_rs2 <= dbg_insn_rs2;
765
+ q_insn_rd <= dbg_insn_rd;
766
+ dbg_next <= launch_next_insn;
767
+
768
+ if (!resetn || trap)
769
+ dbg_valid_insn <= 0;
770
+ else if (launch_next_insn)
771
+ dbg_valid_insn <= 1;
772
+
773
+ if (decoder_trigger_q) begin
774
+ cached_ascii_instr <= new_ascii_instr;
775
+ cached_insn_imm <= decoded_imm;
776
+ if (&next_insn_opcode[1:0])
777
+ cached_insn_opcode <= next_insn_opcode;
778
+ else
779
+ cached_insn_opcode <= {16'b0, next_insn_opcode[15:0]};
780
+ cached_insn_rs1 <= decoded_rs1;
781
+ cached_insn_rs2 <= decoded_rs2;
782
+ cached_insn_rd <= decoded_rd;
783
+ end
784
+
785
+ if (launch_next_insn) begin
786
+ dbg_insn_addr <= next_pc;
787
+ end
788
+ end
789
+
790
+ always @* begin
791
+ dbg_ascii_instr = q_ascii_instr;
792
+ dbg_insn_imm = q_insn_imm;
793
+ dbg_insn_opcode = q_insn_opcode;
794
+ dbg_insn_rs1 = q_insn_rs1;
795
+ dbg_insn_rs2 = q_insn_rs2;
796
+ dbg_insn_rd = q_insn_rd;
797
+
798
+ if (dbg_next) begin
799
+ if (decoder_pseudo_trigger_q) begin
800
+ dbg_ascii_instr = cached_ascii_instr;
801
+ dbg_insn_imm = cached_insn_imm;
802
+ dbg_insn_opcode = cached_insn_opcode;
803
+ dbg_insn_rs1 = cached_insn_rs1;
804
+ dbg_insn_rs2 = cached_insn_rs2;
805
+ dbg_insn_rd = cached_insn_rd;
806
+ end else begin
807
+ dbg_ascii_instr = new_ascii_instr;
808
+ if (&next_insn_opcode[1:0])
809
+ dbg_insn_opcode = next_insn_opcode;
810
+ else
811
+ dbg_insn_opcode = {16'b0, next_insn_opcode[15:0]};
812
+ dbg_insn_imm = decoded_imm;
813
+ dbg_insn_rs1 = decoded_rs1;
814
+ dbg_insn_rs2 = decoded_rs2;
815
+ dbg_insn_rd = decoded_rd;
816
+ end
817
+ end
818
+ end
819
+
820
+ `ifdef DEBUGASM
821
+ always @(posedge clk) begin
822
+ if (dbg_next) begin
823
+ $display("debugasm %x %x %s", dbg_insn_addr, dbg_insn_opcode, dbg_ascii_instr ? dbg_ascii_instr : "*");
824
+ end
825
+ end
826
+ `endif
827
+
828
+ `ifdef DEBUG
829
+ always @(posedge clk) begin
830
+ if (dbg_next) begin
831
+ if (&dbg_insn_opcode[1:0])
832
+ $display("DECODE: 0x%08x 0x%08x %-0s", dbg_insn_addr, dbg_insn_opcode, dbg_ascii_instr ? dbg_ascii_instr : "UNKNOWN");
833
+ else
834
+ $display("DECODE: 0x%08x 0x%04x %-0s", dbg_insn_addr, dbg_insn_opcode[15:0], dbg_ascii_instr ? dbg_ascii_instr : "UNKNOWN");
835
+ end
836
+ end
837
+ `endif
838
+
839
+ always @(posedge clk) begin
840
+ is_lui_auipc_jal <= |{instr_lui, instr_auipc, instr_jal};
841
+ is_lui_auipc_jal_jalr_addi_add_sub <= |{instr_lui, instr_auipc, instr_jal, instr_jalr, instr_addi, instr_add, instr_sub};
842
+ is_slti_blt_slt <= |{instr_slti, instr_blt, instr_slt};
843
+ is_sltiu_bltu_sltu <= |{instr_sltiu, instr_bltu, instr_sltu};
844
+ is_lbu_lhu_lw <= |{instr_lbu, instr_lhu, instr_lw};
845
+ is_compare <= |{is_beq_bne_blt_bge_bltu_bgeu, instr_slti, instr_slt, instr_sltiu, instr_sltu};
846
+
847
+ if (mem_do_rinst && mem_done) begin
848
+ instr_lui <= mem_rdata_latched[6:0] == 7'b0110111;
849
+ instr_auipc <= mem_rdata_latched[6:0] == 7'b0010111;
850
+ instr_jal <= mem_rdata_latched[6:0] == 7'b1101111;
851
+ instr_jalr <= mem_rdata_latched[6:0] == 7'b1100111 && mem_rdata_latched[14:12] == 3'b000;
852
+ instr_retirq <= mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000010 && ENABLE_IRQ;
853
+ instr_waitirq <= mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000100 && ENABLE_IRQ;
854
+
855
+ is_beq_bne_blt_bge_bltu_bgeu <= mem_rdata_latched[6:0] == 7'b1100011;
856
+ is_lb_lh_lw_lbu_lhu <= mem_rdata_latched[6:0] == 7'b0000011;
857
+ is_sb_sh_sw <= mem_rdata_latched[6:0] == 7'b0100011;
858
+ is_alu_reg_imm <= mem_rdata_latched[6:0] == 7'b0010011;
859
+ is_alu_reg_reg <= mem_rdata_latched[6:0] == 7'b0110011;
860
+
861
+ { decoded_imm_uj[31:20], decoded_imm_uj[10:1], decoded_imm_uj[11], decoded_imm_uj[19:12], decoded_imm_uj[0] } <= $signed({mem_rdata_latched[31:12], 1'b0});
862
+
863
+ decoded_rd <= mem_rdata_latched[11:7];
864
+ decoded_rs1 <= mem_rdata_latched[19:15];
865
+ decoded_rs2 <= mem_rdata_latched[24:20];
866
+
867
+ if (mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000000 && ENABLE_IRQ && ENABLE_IRQ_QREGS)
868
+ decoded_rs1[regindex_bits-1] <= 1; // instr_getq
869
+
870
+ if (mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000010 && ENABLE_IRQ)
871
+ decoded_rs1 <= ENABLE_IRQ_QREGS ? irqregs_offset : 3; // instr_retirq
872
+
873
+ compressed_instr <= 0;
874
+ if (COMPRESSED_ISA && mem_rdata_latched[1:0] != 2'b11) begin
875
+ compressed_instr <= 1;
876
+ decoded_rd <= 0;
877
+ decoded_rs1 <= 0;
878
+ decoded_rs2 <= 0;
879
+
880
+ { decoded_imm_uj[31:11], decoded_imm_uj[4], decoded_imm_uj[9:8], decoded_imm_uj[10], decoded_imm_uj[6],
881
+ decoded_imm_uj[7], decoded_imm_uj[3:1], decoded_imm_uj[5], decoded_imm_uj[0] } <= $signed({mem_rdata_latched[12:2], 1'b0});
882
+
883
+ case (mem_rdata_latched[1:0])
884
+ 2'b00: begin // Quadrant 0
885
+ case (mem_rdata_latched[15:13])
886
+ 3'b000: begin // C.ADDI4SPN
887
+ is_alu_reg_imm <= |mem_rdata_latched[12:5];
888
+ decoded_rs1 <= 2;
889
+ decoded_rd <= 8 + mem_rdata_latched[4:2];
890
+ end
891
+ 3'b010: begin // C.LW
892
+ is_lb_lh_lw_lbu_lhu <= 1;
893
+ decoded_rs1 <= 8 + mem_rdata_latched[9:7];
894
+ decoded_rd <= 8 + mem_rdata_latched[4:2];
895
+ end
896
+ 3'b110: begin // C.SW
897
+ is_sb_sh_sw <= 1;
898
+ decoded_rs1 <= 8 + mem_rdata_latched[9:7];
899
+ decoded_rs2 <= 8 + mem_rdata_latched[4:2];
900
+ end
901
+ endcase
902
+ end
903
+ 2'b01: begin // Quadrant 1
904
+ case (mem_rdata_latched[15:13])
905
+ 3'b000: begin // C.NOP / C.ADDI
906
+ is_alu_reg_imm <= 1;
907
+ decoded_rd <= mem_rdata_latched[11:7];
908
+ decoded_rs1 <= mem_rdata_latched[11:7];
909
+ end
910
+ 3'b001: begin // C.JAL
911
+ instr_jal <= 1;
912
+ decoded_rd <= 1;
913
+ end
914
+ 3'b 010: begin // C.LI
915
+ is_alu_reg_imm <= 1;
916
+ decoded_rd <= mem_rdata_latched[11:7];
917
+ decoded_rs1 <= 0;
918
+ end
919
+ 3'b 011: begin
920
+ if (mem_rdata_latched[12] || mem_rdata_latched[6:2]) begin
921
+ if (mem_rdata_latched[11:7] == 2) begin // C.ADDI16SP
922
+ is_alu_reg_imm <= 1;
923
+ decoded_rd <= mem_rdata_latched[11:7];
924
+ decoded_rs1 <= mem_rdata_latched[11:7];
925
+ end else begin // C.LUI
926
+ instr_lui <= 1;
927
+ decoded_rd <= mem_rdata_latched[11:7];
928
+ decoded_rs1 <= 0;
929
+ end
930
+ end
931
+ end
932
+ 3'b100: begin
933
+ if (!mem_rdata_latched[11] && !mem_rdata_latched[12]) begin // C.SRLI, C.SRAI
934
+ is_alu_reg_imm <= 1;
935
+ decoded_rd <= 8 + mem_rdata_latched[9:7];
936
+ decoded_rs1 <= 8 + mem_rdata_latched[9:7];
937
+ decoded_rs2 <= {mem_rdata_latched[12], mem_rdata_latched[6:2]};
938
+ end
939
+ if (mem_rdata_latched[11:10] == 2'b10) begin // C.ANDI
940
+ is_alu_reg_imm <= 1;
941
+ decoded_rd <= 8 + mem_rdata_latched[9:7];
942
+ decoded_rs1 <= 8 + mem_rdata_latched[9:7];
943
+ end
944
+ if (mem_rdata_latched[12:10] == 3'b011) begin // C.SUB, C.XOR, C.OR, C.AND
945
+ is_alu_reg_reg <= 1;
946
+ decoded_rd <= 8 + mem_rdata_latched[9:7];
947
+ decoded_rs1 <= 8 + mem_rdata_latched[9:7];
948
+ decoded_rs2 <= 8 + mem_rdata_latched[4:2];
949
+ end
950
+ end
951
+ 3'b101: begin // C.J
952
+ instr_jal <= 1;
953
+ end
954
+ 3'b110: begin // C.BEQZ
955
+ is_beq_bne_blt_bge_bltu_bgeu <= 1;
956
+ decoded_rs1 <= 8 + mem_rdata_latched[9:7];
957
+ decoded_rs2 <= 0;
958
+ end
959
+ 3'b111: begin // C.BNEZ
960
+ is_beq_bne_blt_bge_bltu_bgeu <= 1;
961
+ decoded_rs1 <= 8 + mem_rdata_latched[9:7];
962
+ decoded_rs2 <= 0;
963
+ end
964
+ endcase
965
+ end
966
+ 2'b10: begin // Quadrant 2
967
+ case (mem_rdata_latched[15:13])
968
+ 3'b000: begin // C.SLLI
969
+ if (!mem_rdata_latched[12]) begin
970
+ is_alu_reg_imm <= 1;
971
+ decoded_rd <= mem_rdata_latched[11:7];
972
+ decoded_rs1 <= mem_rdata_latched[11:7];
973
+ decoded_rs2 <= {mem_rdata_latched[12], mem_rdata_latched[6:2]};
974
+ end
975
+ end
976
+ 3'b010: begin // C.LWSP
977
+ if (mem_rdata_latched[11:7]) begin
978
+ is_lb_lh_lw_lbu_lhu <= 1;
979
+ decoded_rd <= mem_rdata_latched[11:7];
980
+ decoded_rs1 <= 2;
981
+ end
982
+ end
983
+ 3'b100: begin
984
+ if (mem_rdata_latched[12] == 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JR
985
+ instr_jalr <= 1;
986
+ decoded_rd <= 0;
987
+ decoded_rs1 <= mem_rdata_latched[11:7];
988
+ end
989
+ if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] != 0) begin // C.MV
990
+ is_alu_reg_reg <= 1;
991
+ decoded_rd <= mem_rdata_latched[11:7];
992
+ decoded_rs1 <= 0;
993
+ decoded_rs2 <= mem_rdata_latched[6:2];
994
+ end
995
+ if (mem_rdata_latched[12] != 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JALR
996
+ instr_jalr <= 1;
997
+ decoded_rd <= 1;
998
+ decoded_rs1 <= mem_rdata_latched[11:7];
999
+ end
1000
+ if (mem_rdata_latched[12] != 0 && mem_rdata_latched[6:2] != 0) begin // C.ADD
1001
+ is_alu_reg_reg <= 1;
1002
+ decoded_rd <= mem_rdata_latched[11:7];
1003
+ decoded_rs1 <= mem_rdata_latched[11:7];
1004
+ decoded_rs2 <= mem_rdata_latched[6:2];
1005
+ end
1006
+ end
1007
+ 3'b110: begin // C.SWSP
1008
+ is_sb_sh_sw <= 1;
1009
+ decoded_rs1 <= 2;
1010
+ decoded_rs2 <= mem_rdata_latched[6:2];
1011
+ end
1012
+ endcase
1013
+ end
1014
+ endcase
1015
+ end
1016
+ end
1017
+
1018
+ if (decoder_trigger && !decoder_pseudo_trigger) begin
1019
+ pcpi_insn <= WITH_PCPI ? mem_rdata_q : 'bx;
1020
+
1021
+ instr_beq <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b000;
1022
+ instr_bne <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b001;
1023
+ instr_blt <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b100;
1024
+ instr_bge <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b101;
1025
+ instr_bltu <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b110;
1026
+ instr_bgeu <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b111;
1027
+
1028
+ instr_lb <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b000;
1029
+ instr_lh <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b001;
1030
+ instr_lw <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b010;
1031
+ instr_lbu <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b100;
1032
+ instr_lhu <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b101;
1033
+
1034
+ instr_sb <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b000;
1035
+ instr_sh <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b001;
1036
+ instr_sw <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b010;
1037
+
1038
+ instr_addi <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b000;
1039
+ instr_slti <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b010;
1040
+ instr_sltiu <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b011;
1041
+ instr_xori <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b100;
1042
+ instr_ori <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b110;
1043
+ instr_andi <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b111;
1044
+
1045
+ instr_slli <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000;
1046
+ instr_srli <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000;
1047
+ instr_srai <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000;
1048
+
1049
+ instr_add <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b000 && mem_rdata_q[31:25] == 7'b0000000;
1050
+ instr_sub <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b000 && mem_rdata_q[31:25] == 7'b0100000;
1051
+ instr_sll <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000;
1052
+ instr_slt <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b010 && mem_rdata_q[31:25] == 7'b0000000;
1053
+ instr_sltu <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b011 && mem_rdata_q[31:25] == 7'b0000000;
1054
+ instr_xor <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b100 && mem_rdata_q[31:25] == 7'b0000000;
1055
+ instr_srl <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000;
1056
+ instr_sra <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000;
1057
+ instr_or <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b110 && mem_rdata_q[31:25] == 7'b0000000;
1058
+ instr_and <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b111 && mem_rdata_q[31:25] == 7'b0000000;
1059
+
1060
+ instr_rdcycle <= ((mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000000000000010) ||
1061
+ (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000000100000010)) && ENABLE_COUNTERS;
1062
+ instr_rdcycleh <= ((mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000000000000010) ||
1063
+ (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000000100000010)) && ENABLE_COUNTERS && ENABLE_COUNTERS64;
1064
+ instr_rdinstr <= (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000001000000010) && ENABLE_COUNTERS;
1065
+ instr_rdinstrh <= (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000001000000010) && ENABLE_COUNTERS && ENABLE_COUNTERS64;
1066
+
1067
+ instr_ecall_ebreak <= ((mem_rdata_q[6:0] == 7'b1110011 && !mem_rdata_q[31:21] && !mem_rdata_q[19:7]) ||
1068
+ (COMPRESSED_ISA && mem_rdata_q[15:0] == 16'h9002));
1069
+
1070
+ instr_getq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000000 && ENABLE_IRQ && ENABLE_IRQ_QREGS;
1071
+ instr_setq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000001 && ENABLE_IRQ && ENABLE_IRQ_QREGS;
1072
+ instr_maskirq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000011 && ENABLE_IRQ;
1073
+ instr_timer <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000101 && ENABLE_IRQ && ENABLE_IRQ_TIMER;
1074
+
1075
+ is_slli_srli_srai <= is_alu_reg_imm && |{
1076
+ mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000,
1077
+ mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000,
1078
+ mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000
1079
+ };
1080
+
1081
+ is_jalr_addi_slti_sltiu_xori_ori_andi <= instr_jalr || is_alu_reg_imm && |{
1082
+ mem_rdata_q[14:12] == 3'b000,
1083
+ mem_rdata_q[14:12] == 3'b010,
1084
+ mem_rdata_q[14:12] == 3'b011,
1085
+ mem_rdata_q[14:12] == 3'b100,
1086
+ mem_rdata_q[14:12] == 3'b110,
1087
+ mem_rdata_q[14:12] == 3'b111
1088
+ };
1089
+
1090
+ is_sll_srl_sra <= is_alu_reg_reg && |{
1091
+ mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000,
1092
+ mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000,
1093
+ mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000
1094
+ };
1095
+
1096
+ is_lui_auipc_jal_jalr_addi_add_sub <= 0;
1097
+ is_compare <= 0;
1098
+
1099
+ (* parallel_case *)
1100
+ case (1'b1)
1101
+ instr_jal:
1102
+ decoded_imm <= decoded_imm_uj;
1103
+ |{instr_lui, instr_auipc}:
1104
+ decoded_imm <= mem_rdata_q[31:12] << 12;
1105
+ |{instr_jalr, is_lb_lh_lw_lbu_lhu, is_alu_reg_imm}:
1106
+ decoded_imm <= $signed(mem_rdata_q[31:20]);
1107
+ is_beq_bne_blt_bge_bltu_bgeu:
1108
+ decoded_imm <= $signed({mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8], 1'b0});
1109
+ is_sb_sh_sw:
1110
+ decoded_imm <= $signed({mem_rdata_q[31:25], mem_rdata_q[11:7]});
1111
+ default:
1112
+ decoded_imm <= 1'bx;
1113
+ endcase
1114
+ end
1115
+
1116
+ if (!resetn) begin
1117
+ is_beq_bne_blt_bge_bltu_bgeu <= 0;
1118
+ is_compare <= 0;
1119
+
1120
+ instr_beq <= 0;
1121
+ instr_bne <= 0;
1122
+ instr_blt <= 0;
1123
+ instr_bge <= 0;
1124
+ instr_bltu <= 0;
1125
+ instr_bgeu <= 0;
1126
+
1127
+ instr_addi <= 0;
1128
+ instr_slti <= 0;
1129
+ instr_sltiu <= 0;
1130
+ instr_xori <= 0;
1131
+ instr_ori <= 0;
1132
+ instr_andi <= 0;
1133
+
1134
+ instr_add <= 0;
1135
+ instr_sub <= 0;
1136
+ instr_sll <= 0;
1137
+ instr_slt <= 0;
1138
+ instr_sltu <= 0;
1139
+ instr_xor <= 0;
1140
+ instr_srl <= 0;
1141
+ instr_sra <= 0;
1142
+ instr_or <= 0;
1143
+ instr_and <= 0;
1144
+ end
1145
+ end
1146
+
1147
+
1148
+ // Main State Machine
1149
+
1150
+ localparam cpu_state_trap = 8'b10000000;
1151
+ localparam cpu_state_fetch = 8'b01000000;
1152
+ localparam cpu_state_ld_rs1 = 8'b00100000;
1153
+ localparam cpu_state_ld_rs2 = 8'b00010000;
1154
+ localparam cpu_state_exec = 8'b00001000;
1155
+ localparam cpu_state_shift = 8'b00000100;
1156
+ localparam cpu_state_stmem = 8'b00000010;
1157
+ localparam cpu_state_ldmem = 8'b00000001;
1158
+
1159
+ reg [7:0] cpu_state;
1160
+ reg [1:0] irq_state;
1161
+
1162
+ `FORMAL_KEEP reg [127:0] dbg_ascii_state;
1163
+
1164
+ always @* begin
1165
+ dbg_ascii_state = "";
1166
+ if (cpu_state == cpu_state_trap) dbg_ascii_state = "trap";
1167
+ if (cpu_state == cpu_state_fetch) dbg_ascii_state = "fetch";
1168
+ if (cpu_state == cpu_state_ld_rs1) dbg_ascii_state = "ld_rs1";
1169
+ if (cpu_state == cpu_state_ld_rs2) dbg_ascii_state = "ld_rs2";
1170
+ if (cpu_state == cpu_state_exec) dbg_ascii_state = "exec";
1171
+ if (cpu_state == cpu_state_shift) dbg_ascii_state = "shift";
1172
+ if (cpu_state == cpu_state_stmem) dbg_ascii_state = "stmem";
1173
+ if (cpu_state == cpu_state_ldmem) dbg_ascii_state = "ldmem";
1174
+ end
1175
+
1176
+ reg set_mem_do_rinst;
1177
+ reg set_mem_do_rdata;
1178
+ reg set_mem_do_wdata;
1179
+
1180
+ reg latched_store;
1181
+ reg latched_stalu;
1182
+ reg latched_branch;
1183
+ reg latched_compr;
1184
+ reg latched_trace;
1185
+ reg latched_is_lu;
1186
+ reg latched_is_lh;
1187
+ reg latched_is_lb;
1188
+ reg [regindex_bits-1:0] latched_rd;
1189
+
1190
+ reg [31:0] current_pc;
1191
+ assign next_pc = latched_store && latched_branch ? reg_out & ~1 : reg_next_pc;
1192
+
1193
+ reg [3:0] pcpi_timeout_counter;
1194
+ reg pcpi_timeout;
1195
+
1196
+ reg [31:0] next_irq_pending;
1197
+ reg do_waitirq;
1198
+
1199
+ reg [31:0] alu_out, alu_out_q;
1200
+ reg alu_out_0, alu_out_0_q;
1201
+ reg alu_wait, alu_wait_2;
1202
+
1203
+ reg [31:0] alu_add_sub;
1204
+ reg [31:0] alu_shl, alu_shr;
1205
+ reg alu_eq, alu_ltu, alu_lts;
1206
+
1207
+ generate if (TWO_CYCLE_ALU) begin
1208
+ always @(posedge clk) begin
1209
+ alu_add_sub <= instr_sub ? reg_op1 - reg_op2 : reg_op1 + reg_op2;
1210
+ alu_eq <= reg_op1 == reg_op2;
1211
+ alu_lts <= $signed(reg_op1) < $signed(reg_op2);
1212
+ alu_ltu <= reg_op1 < reg_op2;
1213
+ alu_shl <= reg_op1 << reg_op2[4:0];
1214
+ alu_shr <= $signed({instr_sra || instr_srai ? reg_op1[31] : 1'b0, reg_op1}) >>> reg_op2[4:0];
1215
+ end
1216
+ end else begin
1217
+ always @* begin
1218
+ alu_add_sub = instr_sub ? reg_op1 - reg_op2 : reg_op1 + reg_op2;
1219
+ alu_eq = reg_op1 == reg_op2;
1220
+ alu_lts = $signed(reg_op1) < $signed(reg_op2);
1221
+ alu_ltu = reg_op1 < reg_op2;
1222
+ alu_shl = reg_op1 << reg_op2[4:0];
1223
+ alu_shr = $signed({instr_sra || instr_srai ? reg_op1[31] : 1'b0, reg_op1}) >>> reg_op2[4:0];
1224
+ end
1225
+ end endgenerate
1226
+
1227
+ always @* begin
1228
+ alu_out_0 = 'bx;
1229
+ (* parallel_case, full_case *)
1230
+ case (1'b1)
1231
+ instr_beq:
1232
+ alu_out_0 = alu_eq;
1233
+ instr_bne:
1234
+ alu_out_0 = !alu_eq;
1235
+ instr_bge:
1236
+ alu_out_0 = !alu_lts;
1237
+ instr_bgeu:
1238
+ alu_out_0 = !alu_ltu;
1239
+ is_slti_blt_slt && (!TWO_CYCLE_COMPARE || !{instr_beq,instr_bne,instr_bge,instr_bgeu}):
1240
+ alu_out_0 = alu_lts;
1241
+ is_sltiu_bltu_sltu && (!TWO_CYCLE_COMPARE || !{instr_beq,instr_bne,instr_bge,instr_bgeu}):
1242
+ alu_out_0 = alu_ltu;
1243
+ endcase
1244
+
1245
+ alu_out = 'bx;
1246
+ (* parallel_case, full_case *)
1247
+ case (1'b1)
1248
+ is_lui_auipc_jal_jalr_addi_add_sub:
1249
+ alu_out = alu_add_sub;
1250
+ is_compare:
1251
+ alu_out = alu_out_0;
1252
+ instr_xori || instr_xor:
1253
+ alu_out = reg_op1 ^ reg_op2;
1254
+ instr_ori || instr_or:
1255
+ alu_out = reg_op1 | reg_op2;
1256
+ instr_andi || instr_and:
1257
+ alu_out = reg_op1 & reg_op2;
1258
+ BARREL_SHIFTER && (instr_sll || instr_slli):
1259
+ alu_out = alu_shl;
1260
+ BARREL_SHIFTER && (instr_srl || instr_srli || instr_sra || instr_srai):
1261
+ alu_out = alu_shr;
1262
+ endcase
1263
+
1264
+ `ifdef RISCV_FORMAL_BLACKBOX_ALU
1265
+ alu_out_0 = $anyseq;
1266
+ alu_out = $anyseq;
1267
+ `endif
1268
+ end
1269
+
1270
+ reg clear_prefetched_high_word_q;
1271
+ always @(posedge clk) clear_prefetched_high_word_q <= clear_prefetched_high_word;
1272
+
1273
+ always @* begin
1274
+ clear_prefetched_high_word = clear_prefetched_high_word_q;
1275
+ if (!prefetched_high_word)
1276
+ clear_prefetched_high_word = 0;
1277
+ if (latched_branch || irq_state || !resetn)
1278
+ clear_prefetched_high_word = COMPRESSED_ISA;
1279
+ end
1280
+
1281
+ reg cpuregs_write;
1282
+ reg [31:0] cpuregs_wrdata;
1283
+ reg [31:0] cpuregs_rs1;
1284
+ reg [31:0] cpuregs_rs2;
1285
+ reg [regindex_bits-1:0] decoded_rs;
1286
+
1287
+ always @* begin
1288
+ cpuregs_write = 0;
1289
+ cpuregs_wrdata = 'bx;
1290
+
1291
+ if (cpu_state == cpu_state_fetch) begin
1292
+ (* parallel_case *)
1293
+ case (1'b1)
1294
+ latched_branch: begin
1295
+ cpuregs_wrdata = reg_pc + (latched_compr ? 2 : 4);
1296
+ cpuregs_write = 1;
1297
+ end
1298
+ latched_store && !latched_branch: begin
1299
+ cpuregs_wrdata = latched_stalu ? alu_out_q : reg_out;
1300
+ cpuregs_write = 1;
1301
+ end
1302
+ ENABLE_IRQ && irq_state[0]: begin
1303
+ cpuregs_wrdata = reg_next_pc | latched_compr;
1304
+ cpuregs_write = 1;
1305
+ end
1306
+ ENABLE_IRQ && irq_state[1]: begin
1307
+ cpuregs_wrdata = irq_pending & ~irq_mask;
1308
+ cpuregs_write = 1;
1309
+ end
1310
+ endcase
1311
+ end
1312
+ end
1313
+
1314
+ `ifndef PICORV32_REGS
1315
+ always @(posedge clk) begin
1316
+ if (resetn && cpuregs_write && latched_rd)
1317
+ cpuregs[latched_rd] <= cpuregs_wrdata;
1318
+ end
1319
+
1320
+ always @* begin
1321
+ decoded_rs = 'bx;
1322
+ if (ENABLE_REGS_DUALPORT) begin
1323
+ `ifndef RISCV_FORMAL_BLACKBOX_REGS
1324
+ cpuregs_rs1 = decoded_rs1 ? cpuregs[decoded_rs1] : 0;
1325
+ cpuregs_rs2 = decoded_rs2 ? cpuregs[decoded_rs2] : 0;
1326
+ `else
1327
+ cpuregs_rs1 = decoded_rs1 ? $anyseq : 0;
1328
+ cpuregs_rs2 = decoded_rs2 ? $anyseq : 0;
1329
+ `endif
1330
+ end else begin
1331
+ decoded_rs = (cpu_state == cpu_state_ld_rs2) ? decoded_rs2 : decoded_rs1;
1332
+ `ifndef RISCV_FORMAL_BLACKBOX_REGS
1333
+ cpuregs_rs1 = decoded_rs ? cpuregs[decoded_rs] : 0;
1334
+ `else
1335
+ cpuregs_rs1 = decoded_rs ? $anyseq : 0;
1336
+ `endif
1337
+ cpuregs_rs2 = cpuregs_rs1;
1338
+ end
1339
+ end
1340
+ `else
1341
+ wire[31:0] cpuregs_rdata1;
1342
+ wire[31:0] cpuregs_rdata2;
1343
+
1344
+ wire [5:0] cpuregs_waddr = latched_rd;
1345
+ wire [5:0] cpuregs_raddr1 = ENABLE_REGS_DUALPORT ? decoded_rs1 : decoded_rs;
1346
+ wire [5:0] cpuregs_raddr2 = ENABLE_REGS_DUALPORT ? decoded_rs2 : 0;
1347
+
1348
+ `PICORV32_REGS cpuregs (
1349
+ .clk(clk),
1350
+ .wen(resetn && cpuregs_write && latched_rd),
1351
+ .waddr(cpuregs_waddr),
1352
+ .raddr1(cpuregs_raddr1),
1353
+ .raddr2(cpuregs_raddr2),
1354
+ .wdata(cpuregs_wrdata),
1355
+ .rdata1(cpuregs_rdata1),
1356
+ .rdata2(cpuregs_rdata2)
1357
+ );
1358
+
1359
+ always @* begin
1360
+ decoded_rs = 'bx;
1361
+ if (ENABLE_REGS_DUALPORT) begin
1362
+ cpuregs_rs1 = decoded_rs1 ? cpuregs_rdata1 : 0;
1363
+ cpuregs_rs2 = decoded_rs2 ? cpuregs_rdata2 : 0;
1364
+ end else begin
1365
+ decoded_rs = (cpu_state == cpu_state_ld_rs2) ? decoded_rs2 : decoded_rs1;
1366
+ cpuregs_rs1 = decoded_rs ? cpuregs_rdata1 : 0;
1367
+ cpuregs_rs2 = cpuregs_rs1;
1368
+ end
1369
+ end
1370
+ `endif
1371
+
1372
+ assign launch_next_insn = cpu_state == cpu_state_fetch && decoder_trigger && (!ENABLE_IRQ || irq_delay || irq_active || !(irq_pending & ~irq_mask));
1373
+
1374
+ always @(posedge clk) begin
1375
+ trap <= 0;
1376
+ reg_sh <= 'bx;
1377
+ reg_out <= 'bx;
1378
+ set_mem_do_rinst = 0;
1379
+ set_mem_do_rdata = 0;
1380
+ set_mem_do_wdata = 0;
1381
+
1382
+ alu_out_0_q <= alu_out_0;
1383
+ alu_out_q <= alu_out;
1384
+
1385
+ alu_wait <= 0;
1386
+ alu_wait_2 <= 0;
1387
+
1388
+ if (launch_next_insn) begin
1389
+ dbg_rs1val <= 'bx;
1390
+ dbg_rs2val <= 'bx;
1391
+ dbg_rs1val_valid <= 0;
1392
+ dbg_rs2val_valid <= 0;
1393
+ end
1394
+
1395
+ if (WITH_PCPI && CATCH_ILLINSN) begin
1396
+ if (resetn && pcpi_valid && !pcpi_int_wait) begin
1397
+ if (pcpi_timeout_counter)
1398
+ pcpi_timeout_counter <= pcpi_timeout_counter - 1;
1399
+ end else
1400
+ pcpi_timeout_counter <= ~0;
1401
+ pcpi_timeout <= !pcpi_timeout_counter;
1402
+ end
1403
+
1404
+ if (ENABLE_COUNTERS) begin
1405
+ count_cycle <= resetn ? count_cycle + 1 : 0;
1406
+ if (!ENABLE_COUNTERS64) count_cycle[63:32] <= 0;
1407
+ end else begin
1408
+ count_cycle <= 'bx;
1409
+ count_instr <= 'bx;
1410
+ end
1411
+
1412
+ next_irq_pending = ENABLE_IRQ ? irq_pending & LATCHED_IRQ : 'bx;
1413
+
1414
+ if (ENABLE_IRQ && ENABLE_IRQ_TIMER && timer) begin
1415
+ if (timer - 1 == 0)
1416
+ next_irq_pending[irq_timer] = 1;
1417
+ timer <= timer - 1;
1418
+ end
1419
+
1420
+ if (ENABLE_IRQ) begin
1421
+ next_irq_pending = next_irq_pending | irq;
1422
+ end
1423
+
1424
+ decoder_trigger <= mem_do_rinst && mem_done;
1425
+ decoder_trigger_q <= decoder_trigger;
1426
+ decoder_pseudo_trigger <= 0;
1427
+ decoder_pseudo_trigger_q <= decoder_pseudo_trigger;
1428
+ do_waitirq <= 0;
1429
+
1430
+ trace_valid <= 0;
1431
+
1432
+ if (!ENABLE_TRACE)
1433
+ trace_data <= 'bx;
1434
+
1435
+ if (!resetn) begin
1436
+ reg_pc <= PROGADDR_RESET;
1437
+ reg_next_pc <= PROGADDR_RESET;
1438
+ if (ENABLE_COUNTERS)
1439
+ count_instr <= 0;
1440
+ latched_store <= 0;
1441
+ latched_stalu <= 0;
1442
+ latched_branch <= 0;
1443
+ latched_trace <= 0;
1444
+ latched_is_lu <= 0;
1445
+ latched_is_lh <= 0;
1446
+ latched_is_lb <= 0;
1447
+ pcpi_valid <= 0;
1448
+ pcpi_timeout <= 0;
1449
+ irq_active <= 0;
1450
+ irq_delay <= 0;
1451
+ irq_mask <= ~0;
1452
+ next_irq_pending = 0;
1453
+ irq_state <= 0;
1454
+ eoi <= 0;
1455
+ timer <= 0;
1456
+ if (~STACKADDR) begin
1457
+ latched_store <= 1;
1458
+ latched_rd <= 2;
1459
+ reg_out <= STACKADDR;
1460
+ end
1461
+ cpu_state <= cpu_state_fetch;
1462
+ end else
1463
+ (* parallel_case, full_case *)
1464
+ case (cpu_state)
1465
+ cpu_state_trap: begin
1466
+ trap <= 1;
1467
+ end
1468
+
1469
+ cpu_state_fetch: begin
1470
+ mem_do_rinst <= !decoder_trigger && !do_waitirq;
1471
+ mem_wordsize <= 0;
1472
+
1473
+ current_pc = reg_next_pc;
1474
+
1475
+ (* parallel_case *)
1476
+ case (1'b1)
1477
+ latched_branch: begin
1478
+ current_pc = latched_store ? (latched_stalu ? alu_out_q : reg_out) & ~1 : reg_next_pc;
1479
+ `debug($display("ST_RD: %2d 0x%08x, BRANCH 0x%08x", latched_rd, reg_pc + (latched_compr ? 2 : 4), current_pc);)
1480
+ end
1481
+ latched_store && !latched_branch: begin
1482
+ `debug($display("ST_RD: %2d 0x%08x", latched_rd, latched_stalu ? alu_out_q : reg_out);)
1483
+ end
1484
+ ENABLE_IRQ && irq_state[0]: begin
1485
+ current_pc = PROGADDR_IRQ;
1486
+ irq_active <= 1;
1487
+ mem_do_rinst <= 1;
1488
+ end
1489
+ ENABLE_IRQ && irq_state[1]: begin
1490
+ eoi <= irq_pending & ~irq_mask;
1491
+ next_irq_pending = next_irq_pending & irq_mask;
1492
+ end
1493
+ endcase
1494
+
1495
+ if (ENABLE_TRACE && latched_trace) begin
1496
+ latched_trace <= 0;
1497
+ trace_valid <= 1;
1498
+ if (latched_branch)
1499
+ trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_BRANCH | (current_pc & 32'hfffffffe);
1500
+ else
1501
+ trace_data <= (irq_active ? TRACE_IRQ : 0) | (latched_stalu ? alu_out_q : reg_out);
1502
+ end
1503
+
1504
+ reg_pc <= current_pc;
1505
+ reg_next_pc <= current_pc;
1506
+
1507
+ latched_store <= 0;
1508
+ latched_stalu <= 0;
1509
+ latched_branch <= 0;
1510
+ latched_is_lu <= 0;
1511
+ latched_is_lh <= 0;
1512
+ latched_is_lb <= 0;
1513
+ latched_rd <= decoded_rd;
1514
+ latched_compr <= compressed_instr;
1515
+
1516
+ if (ENABLE_IRQ && ((decoder_trigger && !irq_active && !irq_delay && |(irq_pending & ~irq_mask)) || irq_state)) begin
1517
+ irq_state <=
1518
+ irq_state == 2'b00 ? 2'b01 :
1519
+ irq_state == 2'b01 ? 2'b10 : 2'b00;
1520
+ latched_compr <= latched_compr;
1521
+ if (ENABLE_IRQ_QREGS)
1522
+ latched_rd <= irqregs_offset | irq_state[0];
1523
+ else
1524
+ latched_rd <= irq_state[0] ? 4 : 3;
1525
+ end else
1526
+ if (ENABLE_IRQ && (decoder_trigger || do_waitirq) && instr_waitirq) begin
1527
+ if (irq_pending) begin
1528
+ latched_store <= 1;
1529
+ reg_out <= irq_pending;
1530
+ reg_next_pc <= current_pc + (compressed_instr ? 2 : 4);
1531
+ mem_do_rinst <= 1;
1532
+ end else
1533
+ do_waitirq <= 1;
1534
+ end else
1535
+ if (decoder_trigger) begin
1536
+ `debug($display("-- %-0t", $time);)
1537
+ irq_delay <= irq_active;
1538
+ reg_next_pc <= current_pc + (compressed_instr ? 2 : 4);
1539
+ if (ENABLE_TRACE)
1540
+ latched_trace <= 1;
1541
+ if (ENABLE_COUNTERS) begin
1542
+ count_instr <= count_instr + 1;
1543
+ if (!ENABLE_COUNTERS64) count_instr[63:32] <= 0;
1544
+ end
1545
+ if (instr_jal) begin
1546
+ mem_do_rinst <= 1;
1547
+ reg_next_pc <= current_pc + decoded_imm_uj;
1548
+ latched_branch <= 1;
1549
+ end else begin
1550
+ mem_do_rinst <= 0;
1551
+ mem_do_prefetch <= !instr_jalr && !instr_retirq;
1552
+ cpu_state <= cpu_state_ld_rs1;
1553
+ end
1554
+ end
1555
+ end
1556
+
1557
+ cpu_state_ld_rs1: begin
1558
+ reg_op1 <= 'bx;
1559
+ reg_op2 <= 'bx;
1560
+
1561
+ (* parallel_case *)
1562
+ case (1'b1)
1563
+ (CATCH_ILLINSN || WITH_PCPI) && instr_trap: begin
1564
+ if (WITH_PCPI) begin
1565
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1566
+ reg_op1 <= cpuregs_rs1;
1567
+ dbg_rs1val <= cpuregs_rs1;
1568
+ dbg_rs1val_valid <= 1;
1569
+ if (ENABLE_REGS_DUALPORT) begin
1570
+ pcpi_valid <= 1;
1571
+ `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);)
1572
+ reg_sh <= cpuregs_rs2;
1573
+ reg_op2 <= cpuregs_rs2;
1574
+ dbg_rs2val <= cpuregs_rs2;
1575
+ dbg_rs2val_valid <= 1;
1576
+ if (pcpi_int_ready) begin
1577
+ mem_do_rinst <= 1;
1578
+ pcpi_valid <= 0;
1579
+ reg_out <= pcpi_int_rd;
1580
+ latched_store <= pcpi_int_wr;
1581
+ cpu_state <= cpu_state_fetch;
1582
+ end else
1583
+ if (CATCH_ILLINSN && (pcpi_timeout || instr_ecall_ebreak)) begin
1584
+ pcpi_valid <= 0;
1585
+ `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);)
1586
+ if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin
1587
+ next_irq_pending[irq_ebreak] = 1;
1588
+ cpu_state <= cpu_state_fetch;
1589
+ end else
1590
+ cpu_state <= cpu_state_trap;
1591
+ end
1592
+ end else begin
1593
+ cpu_state <= cpu_state_ld_rs2;
1594
+ end
1595
+ end else begin
1596
+ `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);)
1597
+ if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin
1598
+ next_irq_pending[irq_ebreak] = 1;
1599
+ cpu_state <= cpu_state_fetch;
1600
+ end else
1601
+ cpu_state <= cpu_state_trap;
1602
+ end
1603
+ end
1604
+ ENABLE_COUNTERS && is_rdcycle_rdcycleh_rdinstr_rdinstrh: begin
1605
+ (* parallel_case, full_case *)
1606
+ case (1'b1)
1607
+ instr_rdcycle:
1608
+ reg_out <= count_cycle[31:0];
1609
+ instr_rdcycleh && ENABLE_COUNTERS64:
1610
+ reg_out <= count_cycle[63:32];
1611
+ instr_rdinstr:
1612
+ reg_out <= count_instr[31:0];
1613
+ instr_rdinstrh && ENABLE_COUNTERS64:
1614
+ reg_out <= count_instr[63:32];
1615
+ endcase
1616
+ latched_store <= 1;
1617
+ cpu_state <= cpu_state_fetch;
1618
+ end
1619
+ is_lui_auipc_jal: begin
1620
+ reg_op1 <= instr_lui ? 0 : reg_pc;
1621
+ reg_op2 <= decoded_imm;
1622
+ if (TWO_CYCLE_ALU)
1623
+ alu_wait <= 1;
1624
+ else
1625
+ mem_do_rinst <= mem_do_prefetch;
1626
+ cpu_state <= cpu_state_exec;
1627
+ end
1628
+ ENABLE_IRQ && ENABLE_IRQ_QREGS && instr_getq: begin
1629
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1630
+ reg_out <= cpuregs_rs1;
1631
+ dbg_rs1val <= cpuregs_rs1;
1632
+ dbg_rs1val_valid <= 1;
1633
+ latched_store <= 1;
1634
+ cpu_state <= cpu_state_fetch;
1635
+ end
1636
+ ENABLE_IRQ && ENABLE_IRQ_QREGS && instr_setq: begin
1637
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1638
+ reg_out <= cpuregs_rs1;
1639
+ dbg_rs1val <= cpuregs_rs1;
1640
+ dbg_rs1val_valid <= 1;
1641
+ latched_rd <= latched_rd | irqregs_offset;
1642
+ latched_store <= 1;
1643
+ cpu_state <= cpu_state_fetch;
1644
+ end
1645
+ ENABLE_IRQ && instr_retirq: begin
1646
+ eoi <= 0;
1647
+ irq_active <= 0;
1648
+ latched_branch <= 1;
1649
+ latched_store <= 1;
1650
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1651
+ reg_out <= CATCH_MISALIGN ? (cpuregs_rs1 & 32'h fffffffe) : cpuregs_rs1;
1652
+ dbg_rs1val <= cpuregs_rs1;
1653
+ dbg_rs1val_valid <= 1;
1654
+ cpu_state <= cpu_state_fetch;
1655
+ end
1656
+ ENABLE_IRQ && instr_maskirq: begin
1657
+ latched_store <= 1;
1658
+ reg_out <= irq_mask;
1659
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1660
+ irq_mask <= cpuregs_rs1 | MASKED_IRQ;
1661
+ dbg_rs1val <= cpuregs_rs1;
1662
+ dbg_rs1val_valid <= 1;
1663
+ cpu_state <= cpu_state_fetch;
1664
+ end
1665
+ ENABLE_IRQ && ENABLE_IRQ_TIMER && instr_timer: begin
1666
+ latched_store <= 1;
1667
+ reg_out <= timer;
1668
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1669
+ timer <= cpuregs_rs1;
1670
+ dbg_rs1val <= cpuregs_rs1;
1671
+ dbg_rs1val_valid <= 1;
1672
+ cpu_state <= cpu_state_fetch;
1673
+ end
1674
+ is_lb_lh_lw_lbu_lhu && !instr_trap: begin
1675
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1676
+ reg_op1 <= cpuregs_rs1;
1677
+ dbg_rs1val <= cpuregs_rs1;
1678
+ dbg_rs1val_valid <= 1;
1679
+ cpu_state <= cpu_state_ldmem;
1680
+ mem_do_rinst <= 1;
1681
+ end
1682
+ is_slli_srli_srai && !BARREL_SHIFTER: begin
1683
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1684
+ reg_op1 <= cpuregs_rs1;
1685
+ dbg_rs1val <= cpuregs_rs1;
1686
+ dbg_rs1val_valid <= 1;
1687
+ reg_sh <= decoded_rs2;
1688
+ cpu_state <= cpu_state_shift;
1689
+ end
1690
+ is_jalr_addi_slti_sltiu_xori_ori_andi, is_slli_srli_srai && BARREL_SHIFTER: begin
1691
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1692
+ reg_op1 <= cpuregs_rs1;
1693
+ dbg_rs1val <= cpuregs_rs1;
1694
+ dbg_rs1val_valid <= 1;
1695
+ reg_op2 <= is_slli_srli_srai && BARREL_SHIFTER ? decoded_rs2 : decoded_imm;
1696
+ if (TWO_CYCLE_ALU)
1697
+ alu_wait <= 1;
1698
+ else
1699
+ mem_do_rinst <= mem_do_prefetch;
1700
+ cpu_state <= cpu_state_exec;
1701
+ end
1702
+ default: begin
1703
+ `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);)
1704
+ reg_op1 <= cpuregs_rs1;
1705
+ dbg_rs1val <= cpuregs_rs1;
1706
+ dbg_rs1val_valid <= 1;
1707
+ if (ENABLE_REGS_DUALPORT) begin
1708
+ `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);)
1709
+ reg_sh <= cpuregs_rs2;
1710
+ reg_op2 <= cpuregs_rs2;
1711
+ dbg_rs2val <= cpuregs_rs2;
1712
+ dbg_rs2val_valid <= 1;
1713
+ (* parallel_case *)
1714
+ case (1'b1)
1715
+ is_sb_sh_sw: begin
1716
+ cpu_state <= cpu_state_stmem;
1717
+ mem_do_rinst <= 1;
1718
+ end
1719
+ is_sll_srl_sra && !BARREL_SHIFTER: begin
1720
+ cpu_state <= cpu_state_shift;
1721
+ end
1722
+ default: begin
1723
+ if (TWO_CYCLE_ALU || (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu)) begin
1724
+ alu_wait_2 <= TWO_CYCLE_ALU && (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu);
1725
+ alu_wait <= 1;
1726
+ end else
1727
+ mem_do_rinst <= mem_do_prefetch;
1728
+ cpu_state <= cpu_state_exec;
1729
+ end
1730
+ endcase
1731
+ end else
1732
+ cpu_state <= cpu_state_ld_rs2;
1733
+ end
1734
+ endcase
1735
+ end
1736
+
1737
+ cpu_state_ld_rs2: begin
1738
+ `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);)
1739
+ reg_sh <= cpuregs_rs2;
1740
+ reg_op2 <= cpuregs_rs2;
1741
+ dbg_rs2val <= cpuregs_rs2;
1742
+ dbg_rs2val_valid <= 1;
1743
+
1744
+ (* parallel_case *)
1745
+ case (1'b1)
1746
+ WITH_PCPI && instr_trap: begin
1747
+ pcpi_valid <= 1;
1748
+ if (pcpi_int_ready) begin
1749
+ mem_do_rinst <= 1;
1750
+ pcpi_valid <= 0;
1751
+ reg_out <= pcpi_int_rd;
1752
+ latched_store <= pcpi_int_wr;
1753
+ cpu_state <= cpu_state_fetch;
1754
+ end else
1755
+ if (CATCH_ILLINSN && (pcpi_timeout || instr_ecall_ebreak)) begin
1756
+ pcpi_valid <= 0;
1757
+ `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);)
1758
+ if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin
1759
+ next_irq_pending[irq_ebreak] = 1;
1760
+ cpu_state <= cpu_state_fetch;
1761
+ end else
1762
+ cpu_state <= cpu_state_trap;
1763
+ end
1764
+ end
1765
+ is_sb_sh_sw: begin
1766
+ cpu_state <= cpu_state_stmem;
1767
+ mem_do_rinst <= 1;
1768
+ end
1769
+ is_sll_srl_sra && !BARREL_SHIFTER: begin
1770
+ cpu_state <= cpu_state_shift;
1771
+ end
1772
+ default: begin
1773
+ if (TWO_CYCLE_ALU || (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu)) begin
1774
+ alu_wait_2 <= TWO_CYCLE_ALU && (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu);
1775
+ alu_wait <= 1;
1776
+ end else
1777
+ mem_do_rinst <= mem_do_prefetch;
1778
+ cpu_state <= cpu_state_exec;
1779
+ end
1780
+ endcase
1781
+ end
1782
+
1783
+ cpu_state_exec: begin
1784
+ reg_out <= reg_pc + decoded_imm;
1785
+ if ((TWO_CYCLE_ALU || TWO_CYCLE_COMPARE) && (alu_wait || alu_wait_2)) begin
1786
+ mem_do_rinst <= mem_do_prefetch && !alu_wait_2;
1787
+ alu_wait <= alu_wait_2;
1788
+ end else
1789
+ if (is_beq_bne_blt_bge_bltu_bgeu) begin
1790
+ latched_rd <= 0;
1791
+ latched_store <= TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0;
1792
+ latched_branch <= TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0;
1793
+ if (mem_done)
1794
+ cpu_state <= cpu_state_fetch;
1795
+ if (TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0) begin
1796
+ decoder_trigger <= 0;
1797
+ set_mem_do_rinst = 1;
1798
+ end
1799
+ end else begin
1800
+ latched_branch <= instr_jalr;
1801
+ latched_store <= 1;
1802
+ latched_stalu <= 1;
1803
+ cpu_state <= cpu_state_fetch;
1804
+ end
1805
+ end
1806
+
1807
+ cpu_state_shift: begin
1808
+ latched_store <= 1;
1809
+ if (reg_sh == 0) begin
1810
+ reg_out <= reg_op1;
1811
+ mem_do_rinst <= mem_do_prefetch;
1812
+ cpu_state <= cpu_state_fetch;
1813
+ end else if (TWO_STAGE_SHIFT && reg_sh >= 4) begin
1814
+ (* parallel_case, full_case *)
1815
+ case (1'b1)
1816
+ instr_slli || instr_sll: reg_op1 <= reg_op1 << 4;
1817
+ instr_srli || instr_srl: reg_op1 <= reg_op1 >> 4;
1818
+ instr_srai || instr_sra: reg_op1 <= $signed(reg_op1) >>> 4;
1819
+ endcase
1820
+ reg_sh <= reg_sh - 4;
1821
+ end else begin
1822
+ (* parallel_case, full_case *)
1823
+ case (1'b1)
1824
+ instr_slli || instr_sll: reg_op1 <= reg_op1 << 1;
1825
+ instr_srli || instr_srl: reg_op1 <= reg_op1 >> 1;
1826
+ instr_srai || instr_sra: reg_op1 <= $signed(reg_op1) >>> 1;
1827
+ endcase
1828
+ reg_sh <= reg_sh - 1;
1829
+ end
1830
+ end
1831
+
1832
+ cpu_state_stmem: begin
1833
+ if (ENABLE_TRACE)
1834
+ reg_out <= reg_op2;
1835
+ if (!mem_do_prefetch || mem_done) begin
1836
+ if (!mem_do_wdata) begin
1837
+ (* parallel_case, full_case *)
1838
+ case (1'b1)
1839
+ instr_sb: mem_wordsize <= 2;
1840
+ instr_sh: mem_wordsize <= 1;
1841
+ instr_sw: mem_wordsize <= 0;
1842
+ endcase
1843
+ if (ENABLE_TRACE) begin
1844
+ trace_valid <= 1;
1845
+ trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_ADDR | ((reg_op1 + decoded_imm) & 32'hffffffff);
1846
+ end
1847
+ reg_op1 <= reg_op1 + decoded_imm;
1848
+ set_mem_do_wdata = 1;
1849
+ end
1850
+ if (!mem_do_prefetch && mem_done) begin
1851
+ cpu_state <= cpu_state_fetch;
1852
+ decoder_trigger <= 1;
1853
+ decoder_pseudo_trigger <= 1;
1854
+ end
1855
+ end
1856
+ end
1857
+
1858
+ cpu_state_ldmem: begin
1859
+ latched_store <= 1;
1860
+ if (!mem_do_prefetch || mem_done) begin
1861
+ if (!mem_do_rdata) begin
1862
+ (* parallel_case, full_case *)
1863
+ case (1'b1)
1864
+ instr_lb || instr_lbu: mem_wordsize <= 2;
1865
+ instr_lh || instr_lhu: mem_wordsize <= 1;
1866
+ instr_lw: mem_wordsize <= 0;
1867
+ endcase
1868
+ latched_is_lu <= is_lbu_lhu_lw;
1869
+ latched_is_lh <= instr_lh;
1870
+ latched_is_lb <= instr_lb;
1871
+ if (ENABLE_TRACE) begin
1872
+ trace_valid <= 1;
1873
+ trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_ADDR | ((reg_op1 + decoded_imm) & 32'hffffffff);
1874
+ end
1875
+ reg_op1 <= reg_op1 + decoded_imm;
1876
+ set_mem_do_rdata = 1;
1877
+ end
1878
+ if (!mem_do_prefetch && mem_done) begin
1879
+ (* parallel_case, full_case *)
1880
+ case (1'b1)
1881
+ latched_is_lu: reg_out <= mem_rdata_word;
1882
+ latched_is_lh: reg_out <= $signed(mem_rdata_word[15:0]);
1883
+ latched_is_lb: reg_out <= $signed(mem_rdata_word[7:0]);
1884
+ endcase
1885
+ decoder_trigger <= 1;
1886
+ decoder_pseudo_trigger <= 1;
1887
+ cpu_state <= cpu_state_fetch;
1888
+ end
1889
+ end
1890
+ end
1891
+ endcase
1892
+
1893
+ if (CATCH_MISALIGN && resetn && (mem_do_rdata || mem_do_wdata)) begin
1894
+ if (mem_wordsize == 0 && reg_op1[1:0] != 0) begin
1895
+ `debug($display("MISALIGNED WORD: 0x%08x", reg_op1);)
1896
+ if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin
1897
+ next_irq_pending[irq_buserror] = 1;
1898
+ end else
1899
+ cpu_state <= cpu_state_trap;
1900
+ end
1901
+ if (mem_wordsize == 1 && reg_op1[0] != 0) begin
1902
+ `debug($display("MISALIGNED HALFWORD: 0x%08x", reg_op1);)
1903
+ if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin
1904
+ next_irq_pending[irq_buserror] = 1;
1905
+ end else
1906
+ cpu_state <= cpu_state_trap;
1907
+ end
1908
+ end
1909
+ if (CATCH_MISALIGN && resetn && mem_do_rinst && (COMPRESSED_ISA ? reg_pc[0] : |reg_pc[1:0])) begin
1910
+ `debug($display("MISALIGNED INSTRUCTION: 0x%08x", reg_pc);)
1911
+ if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin
1912
+ next_irq_pending[irq_buserror] = 1;
1913
+ end else
1914
+ cpu_state <= cpu_state_trap;
1915
+ end
1916
+ if (!CATCH_ILLINSN && decoder_trigger_q && !decoder_pseudo_trigger_q && instr_ecall_ebreak) begin
1917
+ cpu_state <= cpu_state_trap;
1918
+ end
1919
+
1920
+ if (!resetn || mem_done) begin
1921
+ mem_do_prefetch <= 0;
1922
+ mem_do_rinst <= 0;
1923
+ mem_do_rdata <= 0;
1924
+ mem_do_wdata <= 0;
1925
+ end
1926
+
1927
+ if (set_mem_do_rinst)
1928
+ mem_do_rinst <= 1;
1929
+ if (set_mem_do_rdata)
1930
+ mem_do_rdata <= 1;
1931
+ if (set_mem_do_wdata)
1932
+ mem_do_wdata <= 1;
1933
+
1934
+ irq_pending <= next_irq_pending & ~MASKED_IRQ;
1935
+
1936
+ if (!CATCH_MISALIGN) begin
1937
+ if (COMPRESSED_ISA) begin
1938
+ reg_pc[0] <= 0;
1939
+ reg_next_pc[0] <= 0;
1940
+ end else begin
1941
+ reg_pc[1:0] <= 0;
1942
+ reg_next_pc[1:0] <= 0;
1943
+ end
1944
+ end
1945
+ current_pc = 'bx;
1946
+ end
1947
+
1948
+ `ifdef RISCV_FORMAL
1949
+ reg dbg_irq_call;
1950
+ reg dbg_irq_enter;
1951
+ reg [31:0] dbg_irq_ret;
1952
+ always @(posedge clk) begin
1953
+ rvfi_valid <= resetn && (launch_next_insn || trap) && dbg_valid_insn;
1954
+ rvfi_order <= resetn ? rvfi_order + rvfi_valid : 0;
1955
+
1956
+ rvfi_insn <= dbg_insn_opcode;
1957
+ rvfi_rs1_addr <= dbg_rs1val_valid ? dbg_insn_rs1 : 0;
1958
+ rvfi_rs2_addr <= dbg_rs2val_valid ? dbg_insn_rs2 : 0;
1959
+ rvfi_pc_rdata <= dbg_insn_addr;
1960
+ rvfi_rs1_rdata <= dbg_rs1val_valid ? dbg_rs1val : 0;
1961
+ rvfi_rs2_rdata <= dbg_rs2val_valid ? dbg_rs2val : 0;
1962
+ rvfi_trap <= trap;
1963
+ rvfi_halt <= trap;
1964
+ rvfi_intr <= dbg_irq_enter;
1965
+
1966
+ if (!resetn) begin
1967
+ dbg_irq_call <= 0;
1968
+ dbg_irq_enter <= 0;
1969
+ end else
1970
+ if (rvfi_valid) begin
1971
+ dbg_irq_call <= 0;
1972
+ dbg_irq_enter <= dbg_irq_call;
1973
+ end else
1974
+ if (irq_state == 1) begin
1975
+ dbg_irq_call <= 1;
1976
+ dbg_irq_ret <= next_pc;
1977
+ end
1978
+
1979
+ if (!resetn) begin
1980
+ rvfi_rd_addr <= 0;
1981
+ rvfi_rd_wdata <= 0;
1982
+ end else
1983
+ if (cpuregs_write && !irq_state) begin
1984
+ rvfi_rd_addr <= latched_rd;
1985
+ rvfi_rd_wdata <= latched_rd ? cpuregs_wrdata : 0;
1986
+ end else
1987
+ if (rvfi_valid) begin
1988
+ rvfi_rd_addr <= 0;
1989
+ rvfi_rd_wdata <= 0;
1990
+ end
1991
+
1992
+ casez (dbg_insn_opcode)
1993
+ 32'b 0000000_?????_000??_???_?????_0001011: begin // getq
1994
+ rvfi_rs1_addr <= 0;
1995
+ rvfi_rs1_rdata <= 0;
1996
+ end
1997
+ 32'b 0000001_?????_?????_???_000??_0001011: begin // setq
1998
+ rvfi_rd_addr <= 0;
1999
+ rvfi_rd_wdata <= 0;
2000
+ end
2001
+ 32'b 0000010_?????_00000_???_00000_0001011: begin // retirq
2002
+ rvfi_rs1_addr <= 0;
2003
+ rvfi_rs1_rdata <= 0;
2004
+ end
2005
+ endcase
2006
+
2007
+ if (!dbg_irq_call) begin
2008
+ if (dbg_mem_instr) begin
2009
+ rvfi_mem_addr <= 0;
2010
+ rvfi_mem_rmask <= 0;
2011
+ rvfi_mem_wmask <= 0;
2012
+ rvfi_mem_rdata <= 0;
2013
+ rvfi_mem_wdata <= 0;
2014
+ end else
2015
+ if (dbg_mem_valid && dbg_mem_ready) begin
2016
+ rvfi_mem_addr <= dbg_mem_addr;
2017
+ rvfi_mem_rmask <= dbg_mem_wstrb ? 0 : ~0;
2018
+ rvfi_mem_wmask <= dbg_mem_wstrb;
2019
+ rvfi_mem_rdata <= dbg_mem_rdata;
2020
+ rvfi_mem_wdata <= dbg_mem_wdata;
2021
+ end
2022
+ end
2023
+ end
2024
+
2025
+ always @* begin
2026
+ rvfi_pc_wdata = dbg_irq_call ? dbg_irq_ret : dbg_insn_addr;
2027
+ end
2028
+ `endif
2029
+
2030
+ // Formal Verification
2031
+ `ifdef FORMAL
2032
+ reg [3:0] last_mem_nowait;
2033
+ always @(posedge clk)
2034
+ last_mem_nowait <= {last_mem_nowait, mem_ready || !mem_valid};
2035
+
2036
+ // stall the memory interface for max 4 cycles
2037
+ restrict property (|last_mem_nowait || mem_ready || !mem_valid);
2038
+
2039
+ // resetn low in first cycle, after that resetn high
2040
+ restrict property (resetn != $initstate);
2041
+
2042
+ // this just makes it much easier to read traces. uncomment as needed.
2043
+ // assume property (mem_valid || !mem_ready);
2044
+
2045
+ reg ok;
2046
+ always @* begin
2047
+ if (resetn) begin
2048
+ // instruction fetches are read-only
2049
+ if (mem_valid && mem_instr)
2050
+ assert (mem_wstrb == 0);
2051
+
2052
+ // cpu_state must be valid
2053
+ ok = 0;
2054
+ if (cpu_state == cpu_state_trap) ok = 1;
2055
+ if (cpu_state == cpu_state_fetch) ok = 1;
2056
+ if (cpu_state == cpu_state_ld_rs1) ok = 1;
2057
+ if (cpu_state == cpu_state_ld_rs2) ok = !ENABLE_REGS_DUALPORT;
2058
+ if (cpu_state == cpu_state_exec) ok = 1;
2059
+ if (cpu_state == cpu_state_shift) ok = 1;
2060
+ if (cpu_state == cpu_state_stmem) ok = 1;
2061
+ if (cpu_state == cpu_state_ldmem) ok = 1;
2062
+ assert (ok);
2063
+ end
2064
+ end
2065
+
2066
+ reg last_mem_la_read = 0;
2067
+ reg last_mem_la_write = 0;
2068
+ reg [31:0] last_mem_la_addr;
2069
+ reg [31:0] last_mem_la_wdata;
2070
+ reg [3:0] last_mem_la_wstrb = 0;
2071
+
2072
+ always @(posedge clk) begin
2073
+ last_mem_la_read <= mem_la_read;
2074
+ last_mem_la_write <= mem_la_write;
2075
+ last_mem_la_addr <= mem_la_addr;
2076
+ last_mem_la_wdata <= mem_la_wdata;
2077
+ last_mem_la_wstrb <= mem_la_wstrb;
2078
+
2079
+ if (last_mem_la_read) begin
2080
+ assert(mem_valid);
2081
+ assert(mem_addr == last_mem_la_addr);
2082
+ assert(mem_wstrb == 0);
2083
+ end
2084
+ if (last_mem_la_write) begin
2085
+ assert(mem_valid);
2086
+ assert(mem_addr == last_mem_la_addr);
2087
+ assert(mem_wdata == last_mem_la_wdata);
2088
+ assert(mem_wstrb == last_mem_la_wstrb);
2089
+ end
2090
+ if (mem_la_read || mem_la_write) begin
2091
+ assert(!mem_valid || mem_ready);
2092
+ end
2093
+ end
2094
+ `endif
2095
+ endmodule
2096
+
2097
+ // This is a simple example implementation of PICORV32_REGS.
2098
+ // Use the PICORV32_REGS mechanism if you want to use custom
2099
+ // memory resources to implement the processor register file.
2100
+ // Note that your implementation must match the requirements of
2101
+ // the PicoRV32 configuration. (e.g. QREGS, etc)
2102
+ module picorv32_regs (
2103
+ input clk, wen,
2104
+ input [5:0] waddr,
2105
+ input [5:0] raddr1,
2106
+ input [5:0] raddr2,
2107
+ input [31:0] wdata,
2108
+ output [31:0] rdata1,
2109
+ output [31:0] rdata2
2110
+ );
2111
+ reg [31:0] regs [0:30];
2112
+
2113
+ always @(posedge clk)
2114
+ if (wen) regs[~waddr[4:0]] <= wdata;
2115
+
2116
+ assign rdata1 = regs[~raddr1[4:0]];
2117
+ assign rdata2 = regs[~raddr2[4:0]];
2118
+ endmodule
2119
+
2120
+
2121
+ /***************************************************************
2122
+ * picorv32_pcpi_mul
2123
+ ***************************************************************/
2124
+
2125
+ module picorv32_pcpi_mul #(
2126
+ parameter STEPS_AT_ONCE = 1,
2127
+ parameter CARRY_CHAIN = 4
2128
+ ) (
2129
+ input clk, resetn,
2130
+
2131
+ input pcpi_valid,
2132
+ input [31:0] pcpi_insn,
2133
+ input [31:0] pcpi_rs1,
2134
+ input [31:0] pcpi_rs2,
2135
+ output reg pcpi_wr,
2136
+ output reg [31:0] pcpi_rd,
2137
+ output reg pcpi_wait,
2138
+ output reg pcpi_ready
2139
+ );
2140
+ reg instr_mul, instr_mulh, instr_mulhsu, instr_mulhu;
2141
+ wire instr_any_mul = |{instr_mul, instr_mulh, instr_mulhsu, instr_mulhu};
2142
+ wire instr_any_mulh = |{instr_mulh, instr_mulhsu, instr_mulhu};
2143
+ wire instr_rs1_signed = |{instr_mulh, instr_mulhsu};
2144
+ wire instr_rs2_signed = |{instr_mulh};
2145
+
2146
+ reg pcpi_wait_q;
2147
+ wire mul_start = pcpi_wait && !pcpi_wait_q;
2148
+
2149
+ always @(posedge clk) begin
2150
+ instr_mul <= 0;
2151
+ instr_mulh <= 0;
2152
+ instr_mulhsu <= 0;
2153
+ instr_mulhu <= 0;
2154
+
2155
+ if (resetn && pcpi_valid && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001) begin
2156
+ case (pcpi_insn[14:12])
2157
+ 3'b000: instr_mul <= 1;
2158
+ 3'b001: instr_mulh <= 1;
2159
+ 3'b010: instr_mulhsu <= 1;
2160
+ 3'b011: instr_mulhu <= 1;
2161
+ endcase
2162
+ end
2163
+
2164
+ pcpi_wait <= instr_any_mul;
2165
+ pcpi_wait_q <= pcpi_wait;
2166
+ end
2167
+
2168
+ reg [63:0] rs1, rs2, rd, rdx;
2169
+ reg [63:0] next_rs1, next_rs2, this_rs2;
2170
+ reg [63:0] next_rd, next_rdx, next_rdt;
2171
+ reg [6:0] mul_counter;
2172
+ reg mul_waiting;
2173
+ reg mul_finish;
2174
+ integer i, j;
2175
+
2176
+ // carry save accumulator
2177
+ always @* begin
2178
+ next_rd = rd;
2179
+ next_rdx = rdx;
2180
+ next_rs1 = rs1;
2181
+ next_rs2 = rs2;
2182
+
2183
+ for (i = 0; i < STEPS_AT_ONCE; i=i+1) begin
2184
+ this_rs2 = next_rs1[0] ? next_rs2 : 0;
2185
+ if (CARRY_CHAIN == 0) begin
2186
+ next_rdt = next_rd ^ next_rdx ^ this_rs2;
2187
+ next_rdx = ((next_rd & next_rdx) | (next_rd & this_rs2) | (next_rdx & this_rs2)) << 1;
2188
+ next_rd = next_rdt;
2189
+ end else begin
2190
+ next_rdt = 0;
2191
+ for (j = 0; j < 64; j = j + CARRY_CHAIN)
2192
+ {next_rdt[j+CARRY_CHAIN-1], next_rd[j +: CARRY_CHAIN]} =
2193
+ next_rd[j +: CARRY_CHAIN] + next_rdx[j +: CARRY_CHAIN] + this_rs2[j +: CARRY_CHAIN];
2194
+ next_rdx = next_rdt << 1;
2195
+ end
2196
+ next_rs1 = next_rs1 >> 1;
2197
+ next_rs2 = next_rs2 << 1;
2198
+ end
2199
+ end
2200
+
2201
+ always @(posedge clk) begin
2202
+ mul_finish <= 0;
2203
+ if (!resetn) begin
2204
+ mul_waiting <= 1;
2205
+ end else
2206
+ if (mul_waiting) begin
2207
+ if (instr_rs1_signed)
2208
+ rs1 <= $signed(pcpi_rs1);
2209
+ else
2210
+ rs1 <= $unsigned(pcpi_rs1);
2211
+
2212
+ if (instr_rs2_signed)
2213
+ rs2 <= $signed(pcpi_rs2);
2214
+ else
2215
+ rs2 <= $unsigned(pcpi_rs2);
2216
+
2217
+ rd <= 0;
2218
+ rdx <= 0;
2219
+ mul_counter <= (instr_any_mulh ? 63 - STEPS_AT_ONCE : 31 - STEPS_AT_ONCE);
2220
+ mul_waiting <= !mul_start;
2221
+ end else begin
2222
+ rd <= next_rd;
2223
+ rdx <= next_rdx;
2224
+ rs1 <= next_rs1;
2225
+ rs2 <= next_rs2;
2226
+
2227
+ mul_counter <= mul_counter - STEPS_AT_ONCE;
2228
+ if (mul_counter[6]) begin
2229
+ mul_finish <= 1;
2230
+ mul_waiting <= 1;
2231
+ end
2232
+ end
2233
+ end
2234
+
2235
+ always @(posedge clk) begin
2236
+ pcpi_wr <= 0;
2237
+ pcpi_ready <= 0;
2238
+ if (mul_finish && resetn) begin
2239
+ pcpi_wr <= 1;
2240
+ pcpi_ready <= 1;
2241
+ pcpi_rd <= instr_any_mulh ? rd >> 32 : rd;
2242
+ end
2243
+ end
2244
+ endmodule
2245
+
2246
+ module picorv32_pcpi_fast_mul #(
2247
+ parameter EXTRA_MUL_FFS = 0,
2248
+ parameter EXTRA_INSN_FFS = 0,
2249
+ parameter MUL_CLKGATE = 0
2250
+ ) (
2251
+ input clk, resetn,
2252
+
2253
+ input pcpi_valid,
2254
+ input [31:0] pcpi_insn,
2255
+ input [31:0] pcpi_rs1,
2256
+ input [31:0] pcpi_rs2,
2257
+ output pcpi_wr,
2258
+ output [31:0] pcpi_rd,
2259
+ output pcpi_wait,
2260
+ output pcpi_ready
2261
+ );
2262
+ reg instr_mul, instr_mulh, instr_mulhsu, instr_mulhu;
2263
+ wire instr_any_mul = |{instr_mul, instr_mulh, instr_mulhsu, instr_mulhu};
2264
+ wire instr_any_mulh = |{instr_mulh, instr_mulhsu, instr_mulhu};
2265
+ wire instr_rs1_signed = |{instr_mulh, instr_mulhsu};
2266
+ wire instr_rs2_signed = |{instr_mulh};
2267
+
2268
+ reg shift_out;
2269
+ reg [3:0] active;
2270
+ reg [32:0] rs1, rs2, rs1_q, rs2_q;
2271
+ reg [63:0] rd, rd_q;
2272
+
2273
+ wire pcpi_insn_valid = pcpi_valid && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001;
2274
+ reg pcpi_insn_valid_q;
2275
+
2276
+ always @* begin
2277
+ instr_mul = 0;
2278
+ instr_mulh = 0;
2279
+ instr_mulhsu = 0;
2280
+ instr_mulhu = 0;
2281
+
2282
+ if (resetn && (EXTRA_INSN_FFS ? pcpi_insn_valid_q : pcpi_insn_valid)) begin
2283
+ case (pcpi_insn[14:12])
2284
+ 3'b000: instr_mul = 1;
2285
+ 3'b001: instr_mulh = 1;
2286
+ 3'b010: instr_mulhsu = 1;
2287
+ 3'b011: instr_mulhu = 1;
2288
+ endcase
2289
+ end
2290
+ end
2291
+
2292
+ always @(posedge clk) begin
2293
+ pcpi_insn_valid_q <= pcpi_insn_valid;
2294
+ if (!MUL_CLKGATE || active[0]) begin
2295
+ rs1_q <= rs1;
2296
+ rs2_q <= rs2;
2297
+ end
2298
+ if (!MUL_CLKGATE || active[1]) begin
2299
+ rd <= $signed(EXTRA_MUL_FFS ? rs1_q : rs1) * $signed(EXTRA_MUL_FFS ? rs2_q : rs2);
2300
+ end
2301
+ if (!MUL_CLKGATE || active[2]) begin
2302
+ rd_q <= rd;
2303
+ end
2304
+ end
2305
+
2306
+ always @(posedge clk) begin
2307
+ if (instr_any_mul && !(EXTRA_MUL_FFS ? active[3:0] : active[1:0])) begin
2308
+ if (instr_rs1_signed)
2309
+ rs1 <= $signed(pcpi_rs1);
2310
+ else
2311
+ rs1 <= $unsigned(pcpi_rs1);
2312
+
2313
+ if (instr_rs2_signed)
2314
+ rs2 <= $signed(pcpi_rs2);
2315
+ else
2316
+ rs2 <= $unsigned(pcpi_rs2);
2317
+ active[0] <= 1;
2318
+ end else begin
2319
+ active[0] <= 0;
2320
+ end
2321
+
2322
+ active[3:1] <= active;
2323
+ shift_out <= instr_any_mulh;
2324
+
2325
+ if (!resetn)
2326
+ active <= 0;
2327
+ end
2328
+
2329
+ assign pcpi_wr = active[EXTRA_MUL_FFS ? 3 : 1];
2330
+ assign pcpi_wait = 0;
2331
+ assign pcpi_ready = active[EXTRA_MUL_FFS ? 3 : 1];
2332
+ `ifdef RISCV_FORMAL_ALTOPS
2333
+ assign pcpi_rd =
2334
+ instr_mul ? (pcpi_rs1 + pcpi_rs2) ^ 32'h5876063e :
2335
+ instr_mulh ? (pcpi_rs1 + pcpi_rs2) ^ 32'hf6583fb7 :
2336
+ instr_mulhsu ? (pcpi_rs1 - pcpi_rs2) ^ 32'hecfbe137 :
2337
+ instr_mulhu ? (pcpi_rs1 + pcpi_rs2) ^ 32'h949ce5e8 : 1'bx;
2338
+ `else
2339
+ assign pcpi_rd = shift_out ? (EXTRA_MUL_FFS ? rd_q : rd) >> 32 : (EXTRA_MUL_FFS ? rd_q : rd);
2340
+ `endif
2341
+ endmodule
2342
+
2343
+
2344
+ /***************************************************************
2345
+ * picorv32_pcpi_div
2346
+ ***************************************************************/
2347
+
2348
+ module picorv32_pcpi_div (
2349
+ input clk, resetn,
2350
+
2351
+ input pcpi_valid,
2352
+ input [31:0] pcpi_insn,
2353
+ input [31:0] pcpi_rs1,
2354
+ input [31:0] pcpi_rs2,
2355
+ output reg pcpi_wr,
2356
+ output reg [31:0] pcpi_rd,
2357
+ output reg pcpi_wait,
2358
+ output reg pcpi_ready
2359
+ );
2360
+ reg instr_div, instr_divu, instr_rem, instr_remu;
2361
+ wire instr_any_div_rem = |{instr_div, instr_divu, instr_rem, instr_remu};
2362
+
2363
+ reg pcpi_wait_q;
2364
+ wire start = pcpi_wait && !pcpi_wait_q;
2365
+
2366
+ always @(posedge clk) begin
2367
+ instr_div <= 0;
2368
+ instr_divu <= 0;
2369
+ instr_rem <= 0;
2370
+ instr_remu <= 0;
2371
+
2372
+ if (resetn && pcpi_valid && !pcpi_ready && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001) begin
2373
+ case (pcpi_insn[14:12])
2374
+ 3'b100: instr_div <= 1;
2375
+ 3'b101: instr_divu <= 1;
2376
+ 3'b110: instr_rem <= 1;
2377
+ 3'b111: instr_remu <= 1;
2378
+ endcase
2379
+ end
2380
+
2381
+ pcpi_wait <= instr_any_div_rem && resetn;
2382
+ pcpi_wait_q <= pcpi_wait && resetn;
2383
+ end
2384
+
2385
+ reg [31:0] dividend;
2386
+ reg [62:0] divisor;
2387
+ reg [31:0] quotient;
2388
+ reg [31:0] quotient_msk;
2389
+ reg running;
2390
+ reg outsign;
2391
+
2392
+ always @(posedge clk) begin
2393
+ pcpi_ready <= 0;
2394
+ pcpi_wr <= 0;
2395
+ pcpi_rd <= 'bx;
2396
+
2397
+ if (!resetn) begin
2398
+ running <= 0;
2399
+ end else
2400
+ if (start) begin
2401
+ running <= 1;
2402
+ dividend <= (instr_div || instr_rem) && pcpi_rs1[31] ? -pcpi_rs1 : pcpi_rs1;
2403
+ divisor <= ((instr_div || instr_rem) && pcpi_rs2[31] ? -pcpi_rs2 : pcpi_rs2) << 31;
2404
+ outsign <= (instr_div && (pcpi_rs1[31] != pcpi_rs2[31]) && |pcpi_rs2) || (instr_rem && pcpi_rs1[31]);
2405
+ quotient <= 0;
2406
+ quotient_msk <= 1 << 31;
2407
+ end else
2408
+ if (!quotient_msk && running) begin
2409
+ running <= 0;
2410
+ pcpi_ready <= 1;
2411
+ pcpi_wr <= 1;
2412
+ `ifdef RISCV_FORMAL_ALTOPS
2413
+ case (1)
2414
+ instr_div: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h7f8529ec;
2415
+ instr_divu: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h10e8fd70;
2416
+ instr_rem: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h8da68fa5;
2417
+ instr_remu: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h3138d0e1;
2418
+ endcase
2419
+ `else
2420
+ if (instr_div || instr_divu)
2421
+ pcpi_rd <= outsign ? -quotient : quotient;
2422
+ else
2423
+ pcpi_rd <= outsign ? -dividend : dividend;
2424
+ `endif
2425
+ end else begin
2426
+ if (divisor <= dividend) begin
2427
+ dividend <= dividend - divisor;
2428
+ quotient <= quotient | quotient_msk;
2429
+ end
2430
+ divisor <= divisor >> 1;
2431
+ `ifdef RISCV_FORMAL_ALTOPS
2432
+ quotient_msk <= quotient_msk >> 5;
2433
+ `else
2434
+ quotient_msk <= quotient_msk >> 1;
2435
+ `endif
2436
+ end
2437
+ end
2438
+ endmodule
2439
+
2440
+
2441
+ /***************************************************************
2442
+ * picorv32_axi
2443
+ ***************************************************************/
2444
+
2445
+ module picorv32_axi #(
2446
+ parameter [ 0:0] ENABLE_COUNTERS = 1,
2447
+ parameter [ 0:0] ENABLE_COUNTERS64 = 1,
2448
+ parameter [ 0:0] ENABLE_REGS_16_31 = 1,
2449
+ parameter [ 0:0] ENABLE_REGS_DUALPORT = 1,
2450
+ parameter [ 0:0] TWO_STAGE_SHIFT = 1,
2451
+ parameter [ 0:0] BARREL_SHIFTER = 0,
2452
+ parameter [ 0:0] TWO_CYCLE_COMPARE = 0,
2453
+ parameter [ 0:0] TWO_CYCLE_ALU = 0,
2454
+ parameter [ 0:0] COMPRESSED_ISA = 0,
2455
+ parameter [ 0:0] CATCH_MISALIGN = 1,
2456
+ parameter [ 0:0] CATCH_ILLINSN = 1,
2457
+ parameter [ 0:0] ENABLE_PCPI = 0,
2458
+ parameter [ 0:0] ENABLE_MUL = 0,
2459
+ parameter [ 0:0] ENABLE_FAST_MUL = 0,
2460
+ parameter [ 0:0] ENABLE_DIV = 0,
2461
+ parameter [ 0:0] ENABLE_IRQ = 0,
2462
+ parameter [ 0:0] ENABLE_IRQ_QREGS = 1,
2463
+ parameter [ 0:0] ENABLE_IRQ_TIMER = 1,
2464
+ parameter [ 0:0] ENABLE_TRACE = 0,
2465
+ parameter [ 0:0] REGS_INIT_ZERO = 0,
2466
+ parameter [31:0] MASKED_IRQ = 32'h 0000_0000,
2467
+ parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff,
2468
+ parameter [31:0] PROGADDR_RESET = 32'h 0000_0000,
2469
+ parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010,
2470
+ parameter [31:0] STACKADDR = 32'h ffff_ffff
2471
+ ) (
2472
+ input clk, resetn,
2473
+ output trap,
2474
+
2475
+ // AXI4-lite master memory interface
2476
+
2477
+ output mem_axi_awvalid,
2478
+ input mem_axi_awready,
2479
+ output [31:0] mem_axi_awaddr,
2480
+ output [ 2:0] mem_axi_awprot,
2481
+
2482
+ output mem_axi_wvalid,
2483
+ input mem_axi_wready,
2484
+ output [31:0] mem_axi_wdata,
2485
+ output [ 3:0] mem_axi_wstrb,
2486
+
2487
+ input mem_axi_bvalid,
2488
+ output mem_axi_bready,
2489
+
2490
+ output mem_axi_arvalid,
2491
+ input mem_axi_arready,
2492
+ output [31:0] mem_axi_araddr,
2493
+ output [ 2:0] mem_axi_arprot,
2494
+
2495
+ input mem_axi_rvalid,
2496
+ output mem_axi_rready,
2497
+ input [31:0] mem_axi_rdata,
2498
+
2499
+ // Pico Co-Processor Interface (PCPI)
2500
+ output pcpi_valid,
2501
+ output [31:0] pcpi_insn,
2502
+ output [31:0] pcpi_rs1,
2503
+ output [31:0] pcpi_rs2,
2504
+ input pcpi_wr,
2505
+ input [31:0] pcpi_rd,
2506
+ input pcpi_wait,
2507
+ input pcpi_ready,
2508
+
2509
+ // IRQ interface
2510
+ input [31:0] irq,
2511
+ output [31:0] eoi,
2512
+
2513
+ `ifdef RISCV_FORMAL
2514
+ output rvfi_valid,
2515
+ output [63:0] rvfi_order,
2516
+ output [31:0] rvfi_insn,
2517
+ output rvfi_trap,
2518
+ output rvfi_halt,
2519
+ output rvfi_intr,
2520
+ output [ 4:0] rvfi_rs1_addr,
2521
+ output [ 4:0] rvfi_rs2_addr,
2522
+ output [31:0] rvfi_rs1_rdata,
2523
+ output [31:0] rvfi_rs2_rdata,
2524
+ output [ 4:0] rvfi_rd_addr,
2525
+ output [31:0] rvfi_rd_wdata,
2526
+ output [31:0] rvfi_pc_rdata,
2527
+ output [31:0] rvfi_pc_wdata,
2528
+ output [31:0] rvfi_mem_addr,
2529
+ output [ 3:0] rvfi_mem_rmask,
2530
+ output [ 3:0] rvfi_mem_wmask,
2531
+ output [31:0] rvfi_mem_rdata,
2532
+ output [31:0] rvfi_mem_wdata,
2533
+ `endif
2534
+
2535
+ // Trace Interface
2536
+ output trace_valid,
2537
+ output [35:0] trace_data
2538
+ );
2539
+ wire mem_valid;
2540
+ wire [31:0] mem_addr;
2541
+ wire [31:0] mem_wdata;
2542
+ wire [ 3:0] mem_wstrb;
2543
+ wire mem_instr;
2544
+ wire mem_ready;
2545
+ wire [31:0] mem_rdata;
2546
+
2547
+ picorv32_axi_adapter axi_adapter (
2548
+ .clk (clk ),
2549
+ .resetn (resetn ),
2550
+ .mem_axi_awvalid(mem_axi_awvalid),
2551
+ .mem_axi_awready(mem_axi_awready),
2552
+ .mem_axi_awaddr (mem_axi_awaddr ),
2553
+ .mem_axi_awprot (mem_axi_awprot ),
2554
+ .mem_axi_wvalid (mem_axi_wvalid ),
2555
+ .mem_axi_wready (mem_axi_wready ),
2556
+ .mem_axi_wdata (mem_axi_wdata ),
2557
+ .mem_axi_wstrb (mem_axi_wstrb ),
2558
+ .mem_axi_bvalid (mem_axi_bvalid ),
2559
+ .mem_axi_bready (mem_axi_bready ),
2560
+ .mem_axi_arvalid(mem_axi_arvalid),
2561
+ .mem_axi_arready(mem_axi_arready),
2562
+ .mem_axi_araddr (mem_axi_araddr ),
2563
+ .mem_axi_arprot (mem_axi_arprot ),
2564
+ .mem_axi_rvalid (mem_axi_rvalid ),
2565
+ .mem_axi_rready (mem_axi_rready ),
2566
+ .mem_axi_rdata (mem_axi_rdata ),
2567
+ .mem_valid (mem_valid ),
2568
+ .mem_instr (mem_instr ),
2569
+ .mem_ready (mem_ready ),
2570
+ .mem_addr (mem_addr ),
2571
+ .mem_wdata (mem_wdata ),
2572
+ .mem_wstrb (mem_wstrb ),
2573
+ .mem_rdata (mem_rdata )
2574
+ );
2575
+
2576
+ picorv32 #(
2577
+ .ENABLE_COUNTERS (ENABLE_COUNTERS ),
2578
+ .ENABLE_COUNTERS64 (ENABLE_COUNTERS64 ),
2579
+ .ENABLE_REGS_16_31 (ENABLE_REGS_16_31 ),
2580
+ .ENABLE_REGS_DUALPORT(ENABLE_REGS_DUALPORT),
2581
+ .TWO_STAGE_SHIFT (TWO_STAGE_SHIFT ),
2582
+ .BARREL_SHIFTER (BARREL_SHIFTER ),
2583
+ .TWO_CYCLE_COMPARE (TWO_CYCLE_COMPARE ),
2584
+ .TWO_CYCLE_ALU (TWO_CYCLE_ALU ),
2585
+ .COMPRESSED_ISA (COMPRESSED_ISA ),
2586
+ .CATCH_MISALIGN (CATCH_MISALIGN ),
2587
+ .CATCH_ILLINSN (CATCH_ILLINSN ),
2588
+ .ENABLE_PCPI (ENABLE_PCPI ),
2589
+ .ENABLE_MUL (ENABLE_MUL ),
2590
+ .ENABLE_FAST_MUL (ENABLE_FAST_MUL ),
2591
+ .ENABLE_DIV (ENABLE_DIV ),
2592
+ .ENABLE_IRQ (ENABLE_IRQ ),
2593
+ .ENABLE_IRQ_QREGS (ENABLE_IRQ_QREGS ),
2594
+ .ENABLE_IRQ_TIMER (ENABLE_IRQ_TIMER ),
2595
+ .ENABLE_TRACE (ENABLE_TRACE ),
2596
+ .REGS_INIT_ZERO (REGS_INIT_ZERO ),
2597
+ .MASKED_IRQ (MASKED_IRQ ),
2598
+ .LATCHED_IRQ (LATCHED_IRQ ),
2599
+ .PROGADDR_RESET (PROGADDR_RESET ),
2600
+ .PROGADDR_IRQ (PROGADDR_IRQ ),
2601
+ .STACKADDR (STACKADDR )
2602
+ ) picorv32_core (
2603
+ .clk (clk ),
2604
+ .resetn (resetn),
2605
+ .trap (trap ),
2606
+
2607
+ .mem_valid(mem_valid),
2608
+ .mem_addr (mem_addr ),
2609
+ .mem_wdata(mem_wdata),
2610
+ .mem_wstrb(mem_wstrb),
2611
+ .mem_instr(mem_instr),
2612
+ .mem_ready(mem_ready),
2613
+ .mem_rdata(mem_rdata),
2614
+
2615
+ .pcpi_valid(pcpi_valid),
2616
+ .pcpi_insn (pcpi_insn ),
2617
+ .pcpi_rs1 (pcpi_rs1 ),
2618
+ .pcpi_rs2 (pcpi_rs2 ),
2619
+ .pcpi_wr (pcpi_wr ),
2620
+ .pcpi_rd (pcpi_rd ),
2621
+ .pcpi_wait (pcpi_wait ),
2622
+ .pcpi_ready(pcpi_ready),
2623
+
2624
+ .irq(irq),
2625
+ .eoi(eoi),
2626
+
2627
+ `ifdef RISCV_FORMAL
2628
+ .rvfi_valid (rvfi_valid ),
2629
+ .rvfi_order (rvfi_order ),
2630
+ .rvfi_insn (rvfi_insn ),
2631
+ .rvfi_trap (rvfi_trap ),
2632
+ .rvfi_halt (rvfi_halt ),
2633
+ .rvfi_intr (rvfi_intr ),
2634
+ .rvfi_rs1_addr (rvfi_rs1_addr ),
2635
+ .rvfi_rs2_addr (rvfi_rs2_addr ),
2636
+ .rvfi_rs1_rdata(rvfi_rs1_rdata),
2637
+ .rvfi_rs2_rdata(rvfi_rs2_rdata),
2638
+ .rvfi_rd_addr (rvfi_rd_addr ),
2639
+ .rvfi_rd_wdata (rvfi_rd_wdata ),
2640
+ .rvfi_pc_rdata (rvfi_pc_rdata ),
2641
+ .rvfi_pc_wdata (rvfi_pc_wdata ),
2642
+ .rvfi_mem_addr (rvfi_mem_addr ),
2643
+ .rvfi_mem_rmask(rvfi_mem_rmask),
2644
+ .rvfi_mem_wmask(rvfi_mem_wmask),
2645
+ .rvfi_mem_rdata(rvfi_mem_rdata),
2646
+ .rvfi_mem_wdata(rvfi_mem_wdata),
2647
+ `endif
2648
+
2649
+ .trace_valid(trace_valid),
2650
+ .trace_data (trace_data)
2651
+ );
2652
+ endmodule
2653
+
2654
+
2655
+ /***************************************************************
2656
+ * picorv32_axi_adapter
2657
+ ***************************************************************/
2658
+
2659
+ module picorv32_axi_adapter (
2660
+ input clk, resetn,
2661
+
2662
+ // AXI4-lite master memory interface
2663
+
2664
+ output mem_axi_awvalid,
2665
+ input mem_axi_awready,
2666
+ output [31:0] mem_axi_awaddr,
2667
+ output [ 2:0] mem_axi_awprot,
2668
+
2669
+ output mem_axi_wvalid,
2670
+ input mem_axi_wready,
2671
+ output [31:0] mem_axi_wdata,
2672
+ output [ 3:0] mem_axi_wstrb,
2673
+
2674
+ input mem_axi_bvalid,
2675
+ output mem_axi_bready,
2676
+
2677
+ output mem_axi_arvalid,
2678
+ input mem_axi_arready,
2679
+ output [31:0] mem_axi_araddr,
2680
+ output [ 2:0] mem_axi_arprot,
2681
+
2682
+ input mem_axi_rvalid,
2683
+ output mem_axi_rready,
2684
+ input [31:0] mem_axi_rdata,
2685
+
2686
+ // Native PicoRV32 memory interface
2687
+
2688
+ input mem_valid,
2689
+ input mem_instr,
2690
+ output mem_ready,
2691
+ input [31:0] mem_addr,
2692
+ input [31:0] mem_wdata,
2693
+ input [ 3:0] mem_wstrb,
2694
+ output [31:0] mem_rdata
2695
+ );
2696
+ reg ack_awvalid;
2697
+ reg ack_arvalid;
2698
+ reg ack_wvalid;
2699
+ reg xfer_done;
2700
+
2701
+ assign mem_axi_awvalid = mem_valid && |mem_wstrb && !ack_awvalid;
2702
+ assign mem_axi_awaddr = mem_addr;
2703
+ assign mem_axi_awprot = 0;
2704
+
2705
+ assign mem_axi_arvalid = mem_valid && !mem_wstrb && !ack_arvalid;
2706
+ assign mem_axi_araddr = mem_addr;
2707
+ assign mem_axi_arprot = mem_instr ? 3'b100 : 3'b000;
2708
+
2709
+ assign mem_axi_wvalid = mem_valid && |mem_wstrb && !ack_wvalid;
2710
+ assign mem_axi_wdata = mem_wdata;
2711
+ assign mem_axi_wstrb = mem_wstrb;
2712
+
2713
+ assign mem_ready = mem_axi_bvalid || mem_axi_rvalid;
2714
+ assign mem_axi_bready = mem_valid && |mem_wstrb;
2715
+ assign mem_axi_rready = mem_valid && !mem_wstrb;
2716
+ assign mem_rdata = mem_axi_rdata;
2717
+
2718
+ always @(posedge clk) begin
2719
+ if (!resetn) begin
2720
+ ack_awvalid <= 0;
2721
+ end else begin
2722
+ xfer_done <= mem_valid && mem_ready;
2723
+ if (mem_axi_awready && mem_axi_awvalid)
2724
+ ack_awvalid <= 1;
2725
+ if (mem_axi_arready && mem_axi_arvalid)
2726
+ ack_arvalid <= 1;
2727
+ if (mem_axi_wready && mem_axi_wvalid)
2728
+ ack_wvalid <= 1;
2729
+ if (xfer_done || !mem_valid) begin
2730
+ ack_awvalid <= 0;
2731
+ ack_arvalid <= 0;
2732
+ ack_wvalid <= 0;
2733
+ end
2734
+ end
2735
+ end
2736
+ endmodule
2737
+
2738
+
2739
+ /***************************************************************
2740
+ * picorv32_wb
2741
+ ***************************************************************/
2742
+
2743
+ module picorv32_wb #(
2744
+ parameter [ 0:0] ENABLE_COUNTERS = 1,
2745
+ parameter [ 0:0] ENABLE_COUNTERS64 = 1,
2746
+ parameter [ 0:0] ENABLE_REGS_16_31 = 1,
2747
+ parameter [ 0:0] ENABLE_REGS_DUALPORT = 1,
2748
+ parameter [ 0:0] TWO_STAGE_SHIFT = 1,
2749
+ parameter [ 0:0] BARREL_SHIFTER = 0,
2750
+ parameter [ 0:0] TWO_CYCLE_COMPARE = 0,
2751
+ parameter [ 0:0] TWO_CYCLE_ALU = 0,
2752
+ parameter [ 0:0] COMPRESSED_ISA = 0,
2753
+ parameter [ 0:0] CATCH_MISALIGN = 1,
2754
+ parameter [ 0:0] CATCH_ILLINSN = 1,
2755
+ parameter [ 0:0] ENABLE_PCPI = 0,
2756
+ parameter [ 0:0] ENABLE_MUL = 0,
2757
+ parameter [ 0:0] ENABLE_FAST_MUL = 0,
2758
+ parameter [ 0:0] ENABLE_DIV = 0,
2759
+ parameter [ 0:0] ENABLE_IRQ = 0,
2760
+ parameter [ 0:0] ENABLE_IRQ_QREGS = 1,
2761
+ parameter [ 0:0] ENABLE_IRQ_TIMER = 1,
2762
+ parameter [ 0:0] ENABLE_TRACE = 0,
2763
+ parameter [ 0:0] REGS_INIT_ZERO = 0,
2764
+ parameter [31:0] MASKED_IRQ = 32'h 0000_0000,
2765
+ parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff,
2766
+ parameter [31:0] PROGADDR_RESET = 32'h 0000_0000,
2767
+ parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010,
2768
+ parameter [31:0] STACKADDR = 32'h ffff_ffff
2769
+ ) (
2770
+ output trap,
2771
+
2772
+ // Wishbone interfaces
2773
+ input wb_rst_i,
2774
+ input wb_clk_i,
2775
+
2776
+ output reg [31:0] wbm_adr_o,
2777
+ output reg [31:0] wbm_dat_o,
2778
+ input [31:0] wbm_dat_i,
2779
+ output reg wbm_we_o,
2780
+ output reg [3:0] wbm_sel_o,
2781
+ output reg wbm_stb_o,
2782
+ input wbm_ack_i,
2783
+ output reg wbm_cyc_o,
2784
+
2785
+ // Pico Co-Processor Interface (PCPI)
2786
+ output pcpi_valid,
2787
+ output [31:0] pcpi_insn,
2788
+ output [31:0] pcpi_rs1,
2789
+ output [31:0] pcpi_rs2,
2790
+ input pcpi_wr,
2791
+ input [31:0] pcpi_rd,
2792
+ input pcpi_wait,
2793
+ input pcpi_ready,
2794
+
2795
+ // IRQ interface
2796
+ input [31:0] irq,
2797
+ output [31:0] eoi,
2798
+
2799
+ `ifdef RISCV_FORMAL
2800
+ output rvfi_valid,
2801
+ output [63:0] rvfi_order,
2802
+ output [31:0] rvfi_insn,
2803
+ output rvfi_trap,
2804
+ output rvfi_halt,
2805
+ output rvfi_intr,
2806
+ output [ 4:0] rvfi_rs1_addr,
2807
+ output [ 4:0] rvfi_rs2_addr,
2808
+ output [31:0] rvfi_rs1_rdata,
2809
+ output [31:0] rvfi_rs2_rdata,
2810
+ output [ 4:0] rvfi_rd_addr,
2811
+ output [31:0] rvfi_rd_wdata,
2812
+ output [31:0] rvfi_pc_rdata,
2813
+ output [31:0] rvfi_pc_wdata,
2814
+ output [31:0] rvfi_mem_addr,
2815
+ output [ 3:0] rvfi_mem_rmask,
2816
+ output [ 3:0] rvfi_mem_wmask,
2817
+ output [31:0] rvfi_mem_rdata,
2818
+ output [31:0] rvfi_mem_wdata,
2819
+ `endif
2820
+
2821
+ // Trace Interface
2822
+ output trace_valid,
2823
+ output [35:0] trace_data,
2824
+
2825
+ output mem_instr
2826
+ );
2827
+ wire mem_valid;
2828
+ wire [31:0] mem_addr;
2829
+ wire [31:0] mem_wdata;
2830
+ wire [ 3:0] mem_wstrb;
2831
+ reg mem_ready;
2832
+ reg [31:0] mem_rdata;
2833
+
2834
+ wire clk;
2835
+ wire resetn;
2836
+
2837
+ assign clk = wb_clk_i;
2838
+ assign resetn = ~wb_rst_i;
2839
+
2840
+ picorv32 #(
2841
+ .ENABLE_COUNTERS (ENABLE_COUNTERS ),
2842
+ .ENABLE_COUNTERS64 (ENABLE_COUNTERS64 ),
2843
+ .ENABLE_REGS_16_31 (ENABLE_REGS_16_31 ),
2844
+ .ENABLE_REGS_DUALPORT(ENABLE_REGS_DUALPORT),
2845
+ .TWO_STAGE_SHIFT (TWO_STAGE_SHIFT ),
2846
+ .BARREL_SHIFTER (BARREL_SHIFTER ),
2847
+ .TWO_CYCLE_COMPARE (TWO_CYCLE_COMPARE ),
2848
+ .TWO_CYCLE_ALU (TWO_CYCLE_ALU ),
2849
+ .COMPRESSED_ISA (COMPRESSED_ISA ),
2850
+ .CATCH_MISALIGN (CATCH_MISALIGN ),
2851
+ .CATCH_ILLINSN (CATCH_ILLINSN ),
2852
+ .ENABLE_PCPI (ENABLE_PCPI ),
2853
+ .ENABLE_MUL (ENABLE_MUL ),
2854
+ .ENABLE_FAST_MUL (ENABLE_FAST_MUL ),
2855
+ .ENABLE_DIV (ENABLE_DIV ),
2856
+ .ENABLE_IRQ (ENABLE_IRQ ),
2857
+ .ENABLE_IRQ_QREGS (ENABLE_IRQ_QREGS ),
2858
+ .ENABLE_IRQ_TIMER (ENABLE_IRQ_TIMER ),
2859
+ .ENABLE_TRACE (ENABLE_TRACE ),
2860
+ .REGS_INIT_ZERO (REGS_INIT_ZERO ),
2861
+ .MASKED_IRQ (MASKED_IRQ ),
2862
+ .LATCHED_IRQ (LATCHED_IRQ ),
2863
+ .PROGADDR_RESET (PROGADDR_RESET ),
2864
+ .PROGADDR_IRQ (PROGADDR_IRQ ),
2865
+ .STACKADDR (STACKADDR )
2866
+ ) picorv32_core (
2867
+ .clk (clk ),
2868
+ .resetn (resetn),
2869
+ .trap (trap ),
2870
+
2871
+ .mem_valid(mem_valid),
2872
+ .mem_addr (mem_addr ),
2873
+ .mem_wdata(mem_wdata),
2874
+ .mem_wstrb(mem_wstrb),
2875
+ .mem_instr(mem_instr),
2876
+ .mem_ready(mem_ready),
2877
+ .mem_rdata(mem_rdata),
2878
+
2879
+ .pcpi_valid(pcpi_valid),
2880
+ .pcpi_insn (pcpi_insn ),
2881
+ .pcpi_rs1 (pcpi_rs1 ),
2882
+ .pcpi_rs2 (pcpi_rs2 ),
2883
+ .pcpi_wr (pcpi_wr ),
2884
+ .pcpi_rd (pcpi_rd ),
2885
+ .pcpi_wait (pcpi_wait ),
2886
+ .pcpi_ready(pcpi_ready),
2887
+
2888
+ .irq(irq),
2889
+ .eoi(eoi),
2890
+
2891
+ `ifdef RISCV_FORMAL
2892
+ .rvfi_valid (rvfi_valid ),
2893
+ .rvfi_order (rvfi_order ),
2894
+ .rvfi_insn (rvfi_insn ),
2895
+ .rvfi_trap (rvfi_trap ),
2896
+ .rvfi_halt (rvfi_halt ),
2897
+ .rvfi_intr (rvfi_intr ),
2898
+ .rvfi_rs1_addr (rvfi_rs1_addr ),
2899
+ .rvfi_rs2_addr (rvfi_rs2_addr ),
2900
+ .rvfi_rs1_rdata(rvfi_rs1_rdata),
2901
+ .rvfi_rs2_rdata(rvfi_rs2_rdata),
2902
+ .rvfi_rd_addr (rvfi_rd_addr ),
2903
+ .rvfi_rd_wdata (rvfi_rd_wdata ),
2904
+ .rvfi_pc_rdata (rvfi_pc_rdata ),
2905
+ .rvfi_pc_wdata (rvfi_pc_wdata ),
2906
+ .rvfi_mem_addr (rvfi_mem_addr ),
2907
+ .rvfi_mem_rmask(rvfi_mem_rmask),
2908
+ .rvfi_mem_wmask(rvfi_mem_wmask),
2909
+ .rvfi_mem_rdata(rvfi_mem_rdata),
2910
+ .rvfi_mem_wdata(rvfi_mem_wdata),
2911
+ `endif
2912
+
2913
+ .trace_valid(trace_valid),
2914
+ .trace_data (trace_data)
2915
+ );
2916
+
2917
+ localparam IDLE = 2'b00;
2918
+ localparam WBSTART = 2'b01;
2919
+ localparam WBEND = 2'b10;
2920
+
2921
+ reg [1:0] state;
2922
+
2923
+ wire we;
2924
+ assign we = (mem_wstrb[0] | mem_wstrb[1] | mem_wstrb[2] | mem_wstrb[3]);
2925
+
2926
+ always @(posedge wb_clk_i) begin
2927
+ if (wb_rst_i) begin
2928
+ wbm_adr_o <= 0;
2929
+ wbm_dat_o <= 0;
2930
+ wbm_we_o <= 0;
2931
+ wbm_sel_o <= 0;
2932
+ wbm_stb_o <= 0;
2933
+ wbm_cyc_o <= 0;
2934
+ state <= IDLE;
2935
+ end else begin
2936
+ case (state)
2937
+ IDLE: begin
2938
+ if (mem_valid) begin
2939
+ wbm_adr_o <= mem_addr;
2940
+ wbm_dat_o <= mem_wdata;
2941
+ wbm_we_o <= we;
2942
+ wbm_sel_o <= mem_wstrb;
2943
+
2944
+ wbm_stb_o <= 1'b1;
2945
+ wbm_cyc_o <= 1'b1;
2946
+ state <= WBSTART;
2947
+ end else begin
2948
+ mem_ready <= 1'b0;
2949
+
2950
+ wbm_stb_o <= 1'b0;
2951
+ wbm_cyc_o <= 1'b0;
2952
+ wbm_we_o <= 1'b0;
2953
+ end
2954
+ end
2955
+ WBSTART:begin
2956
+ if (wbm_ack_i) begin
2957
+ mem_rdata <= wbm_dat_i;
2958
+ mem_ready <= 1'b1;
2959
+
2960
+ state <= WBEND;
2961
+
2962
+ wbm_stb_o <= 1'b0;
2963
+ wbm_cyc_o <= 1'b0;
2964
+ wbm_we_o <= 1'b0;
2965
+ end
2966
+ end
2967
+ WBEND: begin
2968
+ mem_ready <= 1'b0;
2969
+
2970
+ state <= IDLE;
2971
+ end
2972
+ default:
2973
+ state <= IDLE;
2974
+ endcase
2975
+ end
2976
+ end
2977
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/picosoc.sdc ADDED
@@ -0,0 +1 @@
 
 
1
+ create_clock -period 10 clk_bufg
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/picosoc_noflash.v ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * PicoSoC - A simple example SoC using PicoRV32
3
+ *
4
+ * This is a modified PicoSoC example which has removed the requirement
5
+ * for an external SPI flash. The PicoRV32 program is stored in ROM implemented
6
+ * as a number of case statements. The ROM file is generated using an external
7
+ * script.
8
+ *
9
+ *
10
+ * Copyright (C) 2017 Clifford Wolf <clifford@clifford.at>
11
+ *
12
+ * Permission to use, copy, modify, and/or distribute this software for any
13
+ * purpose with or without fee is hereby granted, provided that the above
14
+ * copyright notice and this permission notice appear in all copies.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
17
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
18
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
19
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
20
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
21
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
22
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23
+ *
24
+ */
25
+
26
+ `ifndef PICORV32_REGS
27
+ `ifdef PICORV32_V
28
+ //`error "picosoc.v must be read before picorv32.v!"
29
+ `endif
30
+
31
+ `define PICORV32_REGS picosoc_regs
32
+ `endif
33
+
34
+ module picosoc_noflash (
35
+ input clk,
36
+ input resetn,
37
+
38
+ output iomem_valid,
39
+ input iomem_ready,
40
+ output [ 3:0] iomem_wstrb,
41
+ output [31:0] iomem_addr,
42
+ output [31:0] iomem_wdata,
43
+ input [31:0] iomem_rdata,
44
+
45
+ // Rewrite firmware
46
+ input progmem_wen,
47
+ input [31:0] progmem_waddr,
48
+ input [31:0] progmem_wdata,
49
+
50
+ input irq_5,
51
+ input irq_6,
52
+ input irq_7,
53
+
54
+ output ser_tx,
55
+ input ser_rx
56
+ );
57
+ parameter integer MEM_WORDS = 8192;
58
+ parameter [31:0] STACKADDR = (4*MEM_WORDS); // end of memory
59
+ parameter [31:0] PROGADDR_RESET = 32'h 0010_0000; // 1 MB into flash
60
+
61
+ reg [31:0] irq;
62
+ wire irq_stall = 0;
63
+ wire irq_uart = 0;
64
+
65
+ always @* begin
66
+ irq = 0;
67
+ irq[3] = irq_stall;
68
+ irq[4] = irq_uart;
69
+ irq[5] = irq_5;
70
+ irq[6] = irq_6;
71
+ irq[7] = irq_7;
72
+ end
73
+
74
+ wire mem_valid;
75
+ wire mem_instr;
76
+ wire mem_ready;
77
+ wire [31:0] mem_addr;
78
+ wire [31:0] mem_wdata;
79
+ wire [3:0] mem_wstrb;
80
+ wire [31:0] mem_rdata;
81
+
82
+ wire progmem_ready;
83
+ wire [31:0] progmem_rdata;
84
+
85
+ reg ram_ready;
86
+ wire [31:0] ram_rdata;
87
+
88
+ assign iomem_valid = mem_valid && (mem_addr[31:24] > 8'h 01);
89
+ assign iomem_wstrb = mem_wstrb;
90
+ assign iomem_addr = mem_addr;
91
+ assign iomem_wdata = mem_wdata;
92
+
93
+ wire spimemio_cfgreg_sel = mem_valid && (mem_addr == 32'h 0200_0000);
94
+
95
+ wire simpleuart_reg_div_sel = mem_valid && (mem_addr == 32'h 0200_0004);
96
+ wire [31:0] simpleuart_reg_div_do;
97
+
98
+ wire simpleuart_reg_dat_sel = mem_valid && (mem_addr == 32'h 0200_0008);
99
+ wire [31:0] simpleuart_reg_dat_do;
100
+ wire simpleuart_reg_dat_wait;
101
+
102
+ assign mem_ready =
103
+ (iomem_valid && iomem_ready) || progmem_ready || ram_ready || spimemio_cfgreg_sel ||
104
+ simpleuart_reg_div_sel || (simpleuart_reg_dat_sel && !simpleuart_reg_dat_wait);
105
+
106
+ assign mem_rdata =
107
+ (iomem_valid && iomem_ready) ? iomem_rdata :
108
+ progmem_ready ? progmem_rdata :
109
+ ram_ready ? ram_rdata :
110
+ spimemio_cfgreg_sel ? 32'h0000_0000 : // Mockup, will always read 0
111
+ simpleuart_reg_div_sel ? simpleuart_reg_div_do :
112
+ simpleuart_reg_dat_sel ? simpleuart_reg_dat_do : 32'h 0000_0000;
113
+
114
+ `ifdef SIMULATION
115
+ wire trace_valid;
116
+ wire [35:0] trace_data;
117
+ integer trace_file;
118
+ `endif
119
+
120
+ picorv32 #(
121
+ .STACKADDR(STACKADDR),
122
+ .PROGADDR_RESET(PROGADDR_RESET),
123
+ .PROGADDR_IRQ(32'h 0000_0000),
124
+ .BARREL_SHIFTER(1),
125
+ .COMPRESSED_ISA(1),
126
+ .ENABLE_MUL(1),
127
+ .ENABLE_DIV(1),
128
+ .ENABLE_IRQ(1),
129
+ `ifdef SIMULATION
130
+ .ENABLE_IRQ_QREGS(0),
131
+ .ENABLE_TRACE(1)
132
+ `else
133
+ .ENABLE_IRQ_QREGS(0)
134
+ `endif
135
+ ) cpu (
136
+ .clk (clk ),
137
+ .resetn (resetn ),
138
+ .mem_valid (mem_valid ),
139
+ .mem_instr (mem_instr ),
140
+ .mem_ready (mem_ready ),
141
+ .mem_addr (mem_addr ),
142
+ .mem_wdata (mem_wdata ),
143
+ .mem_wstrb (mem_wstrb ),
144
+ .mem_rdata (mem_rdata ),
145
+ `ifdef SIMULATION
146
+ .irq (irq ),
147
+ .trace_valid (trace_valid),
148
+ .trace_data (trace_data )
149
+ `else
150
+ .irq (irq )
151
+ `endif
152
+ );
153
+
154
+ // This it the program ROM memory for the PicoRV32
155
+ progmem progmem (
156
+ .clk (clk),
157
+ .rstn (resetn),
158
+
159
+ .valid (mem_valid && mem_addr >= 4*MEM_WORDS && mem_addr < 32'h 0200_0000),
160
+ .ready (progmem_ready),
161
+ .addr (mem_addr),
162
+ .rdata (progmem_rdata),
163
+ .wen (progmem_wen),
164
+ .waddr (progmem_waddr),
165
+ .wdata (progmem_wdata)
166
+ );
167
+
168
+ simpleuart simpleuart (
169
+ .clk (clk ),
170
+ .resetn (resetn ),
171
+
172
+ .ser_tx (ser_tx ),
173
+ .ser_rx (ser_rx ),
174
+
175
+ .reg_div_we (simpleuart_reg_div_sel ? mem_wstrb : 4'b 0000),
176
+ .reg_div_di (mem_wdata),
177
+ .reg_div_do (simpleuart_reg_div_do),
178
+
179
+ .reg_dat_we (simpleuart_reg_dat_sel ? mem_wstrb[0] : 1'b 0),
180
+ .reg_dat_re (simpleuart_reg_dat_sel && !mem_wstrb),
181
+ .reg_dat_di (mem_wdata),
182
+ .reg_dat_do (simpleuart_reg_dat_do),
183
+ .reg_dat_wait(simpleuart_reg_dat_wait)
184
+ );
185
+
186
+ always @(posedge clk)
187
+ ram_ready <= mem_valid && !mem_ready && mem_addr < 4*MEM_WORDS;
188
+
189
+ picosoc_mem #(.WORDS(MEM_WORDS)) memory (
190
+ .clk(clk),
191
+ .wen((mem_valid && !mem_ready && mem_addr < 4*MEM_WORDS) ? mem_wstrb : 4'b0),
192
+ .addr(mem_addr[23:2]),
193
+ .wdata(mem_wdata),
194
+ .rdata(ram_rdata)
195
+ );
196
+
197
+ // Simulation debug
198
+ `ifdef SIMULATION
199
+ always @(posedge clk)
200
+ if (resetn) begin
201
+ if ( mem_instr && mem_valid && mem_ready)
202
+ $display("Inst rd: [0x%08X] = 0x%08X", mem_addr, mem_rdata);
203
+ if (!mem_instr && mem_valid && mem_ready)
204
+ $display("Data rd: [0x%08X] = 0x%08X", mem_addr, mem_rdata);
205
+ end
206
+
207
+ // Trace
208
+ initial begin
209
+
210
+ trace_file = $fopen("testbench.trace", "w");
211
+ repeat (10) @(posedge clk);
212
+
213
+ while(1) begin
214
+ @(posedge clk)
215
+ if (resetn && trace_valid)
216
+ $fwrite(trace_file, "%x\n", trace_data);
217
+ $fflush(trace_file);
218
+ //$display("Trace : %09X", trace_data);
219
+ end
220
+ end
221
+
222
+ `endif // SIMULATION
223
+
224
+ endmodule
225
+
226
+ // Implementation note:
227
+ // Replace the following two modules with wrappers for your SRAM cells.
228
+
229
+ module picosoc_regs (
230
+ input clk, wen,
231
+ input [5:0] waddr,
232
+ input [5:0] raddr1,
233
+ input [5:0] raddr2,
234
+ input [31:0] wdata,
235
+ output [31:0] rdata1,
236
+ output [31:0] rdata2
237
+ );
238
+ (* ram_style = "block" *) reg [31:0] regs [0:31]; // distribuirani bio
239
+
240
+ always @(posedge clk)
241
+ if (wen) regs[waddr[4:0]] <= wdata;
242
+
243
+ assign rdata1 = regs[raddr1[4:0]];
244
+ assign rdata2 = regs[raddr2[4:0]];
245
+ endmodule
246
+
247
+ module picosoc_mem #(
248
+ parameter integer WORDS = 32
249
+ ) (
250
+ input clk,
251
+ input [3:0] wen,
252
+ input [21:0] addr,
253
+ input [31:0] wdata,
254
+ output reg [31:0] rdata
255
+ );
256
+ (* ram_style = "block" *) reg [31:0] mem [0:WORDS-1];
257
+
258
+ //initial $readmemh("firmware.hex", mem);
259
+ always @(posedge clk) begin
260
+ rdata <= mem[addr];
261
+ if (wen[0]) mem[addr][ 7: 0] <= wdata[ 7: 0];
262
+ if (wen[1]) mem[addr][15: 8] <= wdata[15: 8];
263
+ if (wen[2]) mem[addr][23:16] <= wdata[23:16];
264
+ if (wen[3]) mem[addr][31:24] <= wdata[31:24];
265
+ end
266
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/progmem.v ADDED
The diff for this file is too large to render. See raw diff
 
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/simpleuart.v ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * PicoSoC - A simple example SoC using PicoRV32
3
+ *
4
+ * Copyright (C) 2017 Clifford Wolf <clifford@clifford.at>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ module simpleuart (
21
+ input clk,
22
+ input resetn,
23
+
24
+ output ser_tx,
25
+ input ser_rx,
26
+
27
+ input [ 3:0] reg_div_we,
28
+ input [31:0] reg_div_di,
29
+ output [31:0] reg_div_do,
30
+
31
+ input reg_dat_we,
32
+ input reg_dat_re,
33
+ input [31:0] reg_dat_di,
34
+ output [31:0] reg_dat_do,
35
+ output reg_dat_wait
36
+ );
37
+ reg [31:0] cfg_divider;
38
+
39
+ reg [3:0] recv_state;
40
+ reg [31:0] recv_divcnt;
41
+ reg [7:0] recv_pattern;
42
+ reg [7:0] recv_buf_data;
43
+ reg recv_buf_valid;
44
+
45
+ reg [9:0] send_pattern;
46
+ reg [3:0] send_bitcnt;
47
+ reg [31:0] send_divcnt;
48
+ reg send_dummy;
49
+
50
+ assign reg_div_do = cfg_divider;
51
+
52
+ assign reg_dat_wait = reg_dat_we && (send_bitcnt || send_dummy);
53
+ assign reg_dat_do = recv_buf_valid ? recv_buf_data : ~0;
54
+
55
+ always @(posedge clk) begin
56
+ if (!resetn) begin
57
+ cfg_divider <= 1;
58
+ end else begin
59
+ if (reg_div_we[0]) cfg_divider[7:0] <= reg_div_di[7:0];
60
+ if (reg_div_we[1]) cfg_divider[15:8] <= reg_div_di[15:8];
61
+ if (reg_div_we[2]) cfg_divider[23:16] <= reg_div_di[23:16];
62
+ if (reg_div_we[3]) cfg_divider[31:24] <= reg_div_di[31:24];
63
+ end
64
+ end
65
+
66
+ always @(posedge clk) begin
67
+ if (!resetn) begin
68
+ recv_state <= 0;
69
+ recv_divcnt <= 0;
70
+ recv_pattern <= 0;
71
+ recv_buf_data <= 0;
72
+ recv_buf_valid <= 0;
73
+ end else begin
74
+ recv_divcnt <= recv_divcnt + 1;
75
+ if (reg_dat_re) recv_buf_valid <= 0;
76
+ case (recv_state)
77
+ 0: begin
78
+ if (!ser_rx) recv_state <= 1;
79
+ recv_divcnt <= 0;
80
+ end
81
+ 1: begin
82
+ if (2 * recv_divcnt > cfg_divider) begin
83
+ recv_state <= 2;
84
+ recv_divcnt <= 0;
85
+ end
86
+ end
87
+ 10: begin
88
+ if (recv_divcnt > cfg_divider) begin
89
+ recv_buf_data <= recv_pattern;
90
+ recv_buf_valid <= 1;
91
+ recv_state <= 0;
92
+ end
93
+ end
94
+ default: begin
95
+ if (recv_divcnt > cfg_divider) begin
96
+ recv_pattern <= {ser_rx, recv_pattern[7:1]};
97
+ recv_state <= recv_state + 1;
98
+ recv_divcnt <= 0;
99
+ end
100
+ end
101
+ endcase
102
+ end
103
+ end
104
+
105
+ assign ser_tx = send_pattern[0];
106
+
107
+ always @(posedge clk) begin
108
+ if (reg_div_we) send_dummy <= 1;
109
+ send_divcnt <= send_divcnt + 1;
110
+ if (!resetn) begin
111
+ send_pattern <= ~0;
112
+ send_bitcnt <= 0;
113
+ send_divcnt <= 0;
114
+ send_dummy <= 1;
115
+ end else begin
116
+ if (send_dummy && !send_bitcnt) begin
117
+ send_pattern <= ~0;
118
+ send_bitcnt <= 15;
119
+ send_divcnt <= 0;
120
+ send_dummy <= 0;
121
+ end else if (reg_dat_we && !send_bitcnt) begin
122
+ send_pattern <= {1'b1, reg_dat_di[7:0], 1'b0};
123
+ send_bitcnt <= 10;
124
+ send_divcnt <= 0;
125
+ end else if (send_divcnt > cfg_divider && send_bitcnt) begin
126
+ send_pattern <= {1'b1, send_pattern[9:1]};
127
+ send_bitcnt <= send_bitcnt - 1;
128
+ send_divcnt <= 0;
129
+ end
130
+ end
131
+ end
132
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/top.v ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * PicoSoC - A simple example SoC using PicoRV32
3
+ *
4
+ * Copyright (C) 2017 Clifford Wolf <clifford@clifford.at>
5
+ *
6
+ * Permission to use, copy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * copyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ `timescale 1ns / 1ps
21
+
22
+ module top (
23
+ input wire clk_10mhz, // 10MHz clock
24
+
25
+ //output wire led_olimex, // LED output
26
+
27
+ output tx,
28
+ input rx,
29
+
30
+ input btnC,
31
+ input btnU,
32
+ input btnD,
33
+ input btnL,
34
+ input btnR,
35
+
36
+ input [15:0] sw,
37
+ output [15:0] led,
38
+ output [7:0] cathodes,
39
+ output [3:0] anodes,
40
+
41
+ output hsync, // to VGA connector
42
+ output vsync, // to VGA connector
43
+ output [11:0] rgb, // to DAC, to VGA connector
44
+
45
+ output [7:0] jb
46
+ );
47
+
48
+ // command protocol constants:
49
+ parameter [7:0] C_SOP = 8'h23;
50
+ parameter [7:0] C_EOP = 8'h0d;
51
+
52
+ // commands:
53
+ parameter [7:0] C_REGISTER_RD = 8'h08;
54
+ parameter [7:0] C_REGISTER_WR = 8'h07;
55
+
56
+ wire rx_busy, tx_busy, converted, data_valid;
57
+ reg [15:0] data_length, data_cnt;
58
+ reg [7:0] command;
59
+
60
+ // Local control logic variables
61
+ // FSM state
62
+ reg [3:0] state;
63
+
64
+ // This variable is super critical in preventing wrong FSM state changes
65
+ reg allow_next; // Local signal to prevent race conditions
66
+
67
+ // IO related variables
68
+ reg flush_ctrl; // Flush the RX data after reading
69
+ reg tx_enable_ctrl; // Allow tranmission of output, after data is settled
70
+
71
+ wire [7:0] uart_data; // The actual RX UART data
72
+ reg [7:0] out_data; // The data that will be sent over TX
73
+
74
+ reg ram_wen;
75
+ reg [31:0] ram_data, ram_addr;
76
+ reg [15:0] display_data;
77
+ reg [7:0] checksum;
78
+ reg [8:0] leds;
79
+
80
+ // UART clock related variables
81
+ reg [4:0] counter;
82
+
83
+ // VGA signals
84
+ wire [9:0] w_x, w_y;
85
+ wire w_video_on, w_p_tick;
86
+ reg [11:0] rgb_reg;
87
+ wire [11:0] rgb_next;
88
+
89
+ ///////////////////////////////////
90
+ // Power-on Reset
91
+ ///////////////////////////////////
92
+ reg [7:0] reset_cnt = 0;
93
+ wire resetn = &reset_cnt;
94
+
95
+ wire clk, lock;
96
+
97
+ pll pll_inst (
98
+ .clock_in(clk_10mhz), // 10 MHz
99
+ .rst_in(),
100
+ .clock_out(clk),// 25 MHz, 0 deg
101
+ .locked(lock)
102
+ );
103
+
104
+ reg sw_dl1, sw_dl2;
105
+ always @(posedge clk)
106
+ begin
107
+ sw_dl1 <= sw[15];
108
+ sw_dl2 <= sw_dl1;
109
+ if(sw_dl2 && !sw[15]) begin
110
+ reset_cnt <= 0;
111
+ end else begin
112
+ reset_cnt <= reset_cnt + !resetn;
113
+ end
114
+ end
115
+
116
+ wire btnC_out;
117
+ debounce debBtnC (
118
+ .clk (clk),
119
+ .in (btnC),
120
+ .out (btnC_out)
121
+ );
122
+ wire btnL_out;
123
+ debounce debBtnL (
124
+ .clk (clk),
125
+ .in (btnL),
126
+ .out (btnL_out)
127
+ );
128
+ wire btnR_out;
129
+ debounce debBtnR (
130
+ .clk (clk),
131
+ .in (btnR),
132
+ .out (btnR_out)
133
+ );
134
+ wire btnD_out;
135
+ debounce debBtnD (
136
+ .clk (clk),
137
+ .in (btnD),
138
+ .out (btnD_out)
139
+ );
140
+ wire btnU_out;
141
+ debounce debBtnU (
142
+ .clk (clk),
143
+ .in (btnU),
144
+ .out (btnU_out)
145
+ );
146
+ ///////////////////////////////////
147
+ // Peripheral Bus
148
+ ///////////////////////////////////
149
+ wire iomem_valid;
150
+ wire iomem_ready;
151
+ wire [ 3:0] iomem_wstrb;
152
+ wire [31:0] iomem_addr;
153
+ wire [31:0] iomem_wdata;
154
+ wire [31:0] iomem_rdata;
155
+
156
+ reg [31:0] gpio;
157
+ wire [4:0] debug_pins_char_gen;
158
+ reg [31:0] gpio_iomem_rdata;
159
+ reg gpio_iomem_ready;
160
+ wire vga_iomem_ready;
161
+
162
+
163
+ wire[4:0] buttons;
164
+ assign buttons = { btnC_out, btnD_out, btnL_out, btnR_out, btnU_out};
165
+
166
+
167
+ // enable signals for each of the peripherals
168
+ wire gpio_en = (iomem_addr[31:24] == 8'h03); /* GPIO mapped to 0x03xx_xxxx */
169
+ wire video_en = (iomem_addr[31:24] == 8'h05); /* Video device mapped to 0x05xx_xxxx */
170
+
171
+ assign led[5:0] = leds[5:0];
172
+ //assign led[10:6] = buttons;
173
+ assign led[11] = w_video_on;
174
+ assign led[12] = allow_next;
175
+ assign led[13] = ram_wen;
176
+ assign led[14] = r_CLK_1HZ;
177
+ assign led[15] = sw[15];
178
+
179
+ assign iomem_ready = gpio_en ? gpio_iomem_ready : ( video_en ? vga_iomem_ready : 1'b0);
180
+ assign iomem_rdata = gpio_en ? gpio_iomem_rdata : 32'h00000000;
181
+
182
+
183
+ always @(posedge clk)
184
+ begin
185
+ if (!resetn) begin
186
+ gpio <= 0;
187
+ end else begin
188
+ gpio_iomem_ready <= 0;
189
+ if (iomem_valid && !iomem_ready && gpio_en) begin
190
+ gpio_iomem_ready <= 1;
191
+ gpio_iomem_rdata <= {8'h00, 1'b0, 1'b0, 1'b0, buttons[4:0], gpio[15:0]};
192
+ if (iomem_wstrb[0]) gpio[7:0] <= iomem_wdata[7:0];
193
+ if (iomem_wstrb[1]) gpio[15:8] <= iomem_wdata[15:8];
194
+ if (iomem_wstrb[2]) gpio[23:16] <= iomem_wdata[23:16];
195
+ if (iomem_wstrb[3]) gpio[31:24] <= iomem_wdata[31:24];
196
+ end
197
+ end
198
+ end
199
+
200
+ wire tx_uc, rx_uc, tx_prog, rx_prog;
201
+
202
+ assign tx = sw[15] ? tx_prog : tx_uc;
203
+ assign rx_uc = sw[15] ? 1'bz : rx;
204
+ assign rx_prog = sw[15] ? rx : 1'bz;
205
+
206
+ // uC Circuit
207
+ picosoc_noflash soc (
208
+ .clk (clk),
209
+ .resetn (resetn),
210
+
211
+ .ser_tx (tx_uc),
212
+ .ser_rx (rx_uc),
213
+
214
+ .irq_5 (1'b0),
215
+ .irq_6 (1'b0),
216
+ .irq_7 (1'b0),
217
+
218
+ .iomem_valid(iomem_valid),
219
+ .iomem_ready(iomem_ready),
220
+ .iomem_wstrb(iomem_wstrb),
221
+ .iomem_addr (iomem_addr),
222
+ .iomem_wdata(iomem_wdata),
223
+ .iomem_rdata(iomem_rdata),
224
+
225
+ .progmem_wen (progmem_wen),
226
+ .progmem_waddr (ram_addr),
227
+ .progmem_wdata (ram_data)
228
+ );
229
+
230
+ // VGA Controller
231
+ vga_controller vga(
232
+ .clk(clk),
233
+ .reset(!resetn),
234
+ .hsync(hsync),
235
+ .vsync(vsync),
236
+ .video_on(w_video_on),
237
+ .p_tick(w_p_tick),
238
+ .x(w_x),
239
+ .y(w_y)
240
+ );
241
+
242
+ // VGA Wrapper
243
+ vga_wrapper at(
244
+ .clk(clk),
245
+ .reset(!resetn),
246
+ .vga_iomem_ready(vga_iomem_ready),
247
+
248
+ .iomem_valid(iomem_valid && video_en),
249
+ .iomem_ready(iomem_ready),
250
+ .iomem_wstrb(iomem_wstrb),
251
+ .iomem_addr(iomem_addr),
252
+ .iomem_wdata(iomem_wdata),
253
+
254
+ .video_on(w_video_on),
255
+ .x(w_x),
256
+ .y(w_y),
257
+ .rgb(rgb_next),
258
+
259
+ .o_debug_pins(debug_pins_char_gen)
260
+ );
261
+
262
+ // RGB buffer
263
+ always @(posedge clk)
264
+ begin
265
+ //if(w_p_tick)
266
+ rgb_reg <= rgb_next;
267
+ end
268
+
269
+ // output
270
+ assign rgb = rgb_reg;
271
+
272
+
273
+ wire I_write = (command==C_REGISTER_WR);
274
+ wire I_read = (command==C_REGISTER_RD);
275
+
276
+ initial begin
277
+ counter = 0;
278
+
279
+ flush_ctrl = 0;
280
+ tx_enable_ctrl = 0;
281
+ allow_next = 0;
282
+ out_data = 0;
283
+ checksum = 0;
284
+ display_data = 0;
285
+ command = 0;
286
+ data_length = 0;
287
+ data_cnt = 0;
288
+ progmem_wen = 0;
289
+ ram_wen = 0;
290
+ ram_addr = 32'hFFFFFFFF;
291
+ ram_data = 32'd0;
292
+ end
293
+
294
+ reg progmem_wen;
295
+
296
+ // Constants (parameters) to create the frequencies needed:
297
+ // Input clock is 100.0 MHz, system clock.
298
+ // Formula is: (100000 KHz / 1 Hz) * 50% duty cycle
299
+ // So for 1/2 Hz: (100000000 / 1) * 0.5 = 50000000, Input clock is generated 100MHz
300
+ parameter c_CNT_CLK_HZ = 50000000;
301
+ // These signals will be the counters:
302
+ reg [31:0] r_CNT_CLK_HZ = 0;
303
+ // These signals will toggle at the frequencies needed:
304
+ reg r_CLK_1HZ = 1'b0;
305
+ always @(posedge clk)
306
+ begin
307
+ if (r_CNT_CLK_HZ == c_CNT_CLK_HZ-1) begin// -1, since counter starts at 0
308
+ r_CLK_1HZ <= !r_CLK_1HZ;
309
+ r_CNT_CLK_HZ <= 0;
310
+ end else
311
+ r_CNT_CLK_HZ <= r_CNT_CLK_HZ + 1;
312
+ end
313
+ //------------------------------------------------------------------------------
314
+
315
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/uart_rx.v ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `timescale 10ns/1ns
2
+
3
+ /*
4
+ * Custom UART RX design, with all requisite customization options
5
+ * Written by Shubhayu Das, November 2021
6
+ * Version: 1.2.0
7
+ * Last updated: 27th November, 2021
8
+ *
9
+ * The clock frequency and the baud rate have to be calculated and set manually.
10
+ * As it stands now, this module will automatically calculate the prescalar needed.
11
+ * This division will be done in software, which is inefficient, and wastes power
12
+ *
13
+ ***************************
14
+ *
15
+ * THEORY OF WORKING of this module:
16
+ *
17
+ * CLOCKS:
18
+ * - An input clock of 25MHz is expected.
19
+ * - Internally, a "slow_clk_en" pulse is generated, depending on baud rate.
20
+ *
21
+ * UART:
22
+ * An active low signal starts receiving.
23
+ * I am implementing oversampling. Each RX bit is sampled 15 times,
24
+ * then the "obtained_bit" function is used to calculate the detected bit
25
+ *
26
+ * An FSM is used to handle the operation of the module.
27
+ * FSM states:
28
+ * - IDLE : Waiting for start bit(0)
29
+ * - DETECT_START : Possible start bit detected. Oversample and decide
30
+ * - STARTED : Receiving started, oversample and decide individual bits
31
+ * - CONVERSION : RX complete, run parity check, retain data until flushed
32
+ *
33
+ * Oversampling:
34
+ * The incoming RX signal is oversampled, and the oversampled bits are stored in
35
+ * the "oversampled_bit" buffer. Once the buffer is full, the "obtained_bit"
36
+ * function is used to find the accurate bit. This bit is stored in "sampled_rx_data",
37
+ * at the correct location
38
+ *
39
+ * RX:
40
+ * Oversampling is continued until all bits are received. The "sampled_rx_data"
41
+ * contains the final data. This data must be read only AFTER the converted flag goes high.
42
+ *
43
+ ***************************
44
+ * Parameters in the module:
45
+ *
46
+ * FRAME_BITS - The number of bits in the data frame. Allowed values: 5-9 bits/frame
47
+ * PARITY_BIT - Set to "2" to disable parity check. Set to "0/1" for odd/even parity resp.
48
+ * STOP_BITS - The number of stop bits, Allowed values: 1-2 bits
49
+ *
50
+ ***************************
51
+ * Inputs to the module:
52
+ *
53
+ * rx - The input rx signal
54
+ * i_clk - The clock of the local system, used for sampling the bits and FSM sync
55
+ * flush - Clear the converted data from the register
56
+ *
57
+ ***************************
58
+ * Outputs of the module
59
+ *
60
+ * data - The final converted data, of appropriate bit-width
61
+ * converted - Active high signal indicating successfully received frame
62
+ * data_valid - Active high signal indicating if received data is valid(if parity is enabled)
63
+ * busy - Indicates if data reception has started and system is busy
64
+ *
65
+ ***************************
66
+ * In this version, the oversampling factor is 15.
67
+ *
68
+ * Note that due to small mismatches, between the input clock frequency and the target baud rate,
69
+ * there will a drift over time. This needs to be taken care of in the parent module.
70
+ *
71
+ ***************************
72
+ *
73
+ * Sample input clock setup for Basys 3:
74
+ * Set the clock to 100MHz in the constraints file.
75
+ * Then divide the clock to get a time period of 540ns
76
+ *
77
+ ***************************
78
+ * TODO: handling lost bits, using timeout
79
+ * Actually looking at the stop bit(s)
80
+ */
81
+
82
+ //`define DEBUG
83
+
84
+ module uart_rx #(
85
+ parameter FRAME_BITS = 8, // Number of data bits, can be 7/8
86
+ PARITY_BIT = 2, // Parity disabled by default
87
+ STOP_BITS = 1 // Using only 1 stop bit
88
+ ) (
89
+ input rx,
90
+ input i_clk,
91
+ input flush,
92
+ output reg [FRAME_BITS-1:0] data,
93
+ output reg converted,
94
+ output reg data_valid,
95
+ output reg busy
96
+ );
97
+
98
+ // FSM states
99
+ localparam IDLE = 0;
100
+ localparam DETECT_START = 1;
101
+ localparam STARTED = 2;
102
+ localparam CONVERSION = 3;
103
+
104
+ // Calculating the total number of bits that need to be stored
105
+ localparam TOTAL_RX_BITS = (PARITY_BIT < 2 ) ? FRAME_BITS + STOP_BITS + 1 : FRAME_BITS + STOP_BITS;
106
+
107
+ // Hardcoding the number of samples per bit.
108
+ // Change this according to the input clock frequency
109
+ localparam OVERSAMPLE_FACTOR = 15;
110
+
111
+ // Three parameters used by the "obtained_bit" function
112
+ localparam integer SAMPLE_LOC_1 = (OVERSAMPLE_FACTOR / 2) - 1;
113
+ localparam integer SAMPLE_LOC_2 = (OVERSAMPLE_FACTOR / 2);
114
+ localparam integer SAMPLE_LOC_3 = (OVERSAMPLE_FACTOR / 2) + 1;
115
+
116
+ reg [1:0] state; // FSM state
117
+
118
+ reg [3:0] bit_location; // Indexing variable for the received data
119
+ reg [3:0] insert_location; // current index of data in oversampling buffer
120
+
121
+ reg [OVERSAMPLE_FACTOR-1:0] oversampled_bit; // oversampling buffer
122
+ reg [TOTAL_RX_BITS-1:0] sampled_rx_data; // RX buffer
123
+
124
+ initial begin
125
+
126
+ `ifdef DEBUG
127
+ $display("Oversampling factor: %2d", OVERSAMPLE_FACTOR);
128
+ `endif
129
+
130
+ state = IDLE;
131
+
132
+ busy = 0;
133
+ bit_location = 0;
134
+ insert_location = 0;
135
+ sampled_rx_data = {(TOTAL_RX_BITS-1){1'b0}};
136
+ end
137
+
138
+ // Managing the states of the conversion FSM
139
+ always @(posedge i_clk) begin
140
+ case (state)
141
+
142
+ // Unless "0" is detected on RX line, wait
143
+ IDLE :
144
+ state <= rx ? IDLE : DETECT_START;
145
+
146
+ // Once "0" is seen on RX line, sample certain times, decide if RX started
147
+ // If RX started, go to next state
148
+ DETECT_START: begin
149
+ if(insert_location == (OVERSAMPLE_FACTOR-4))
150
+ if(busy)
151
+ state <= STARTED;
152
+ else begin
153
+ state <= IDLE;
154
+ end
155
+ end
156
+
157
+ // Receive all bits of the RX data, with oversampling
158
+ STARTED:
159
+ state <= (bit_location == TOTAL_RX_BITS) ? CONVERSION : STARTED;
160
+
161
+ // Check parity, then retain data until data is flushed
162
+ CONVERSION:
163
+ state <= (flush) ? IDLE : CONVERSION;
164
+ endcase
165
+ end
166
+
167
+ // Actual logic in each state
168
+ always @(posedge i_clk) begin
169
+ case (state)
170
+
171
+ // Simply reset all the vectors
172
+ IDLE: begin
173
+ converted <= 0;
174
+ data_valid <= 0;
175
+ busy <= 0;
176
+ bit_location <= 0;
177
+ insert_location <= 0; // Not really needed
178
+ oversampled_bit <= 15'b0;
179
+ sampled_rx_data = {(TOTAL_RX_BITS-1){1'b0}};
180
+ data <= {FRAME_BITS{1'b0}};
181
+ end
182
+
183
+ // Try to detect if a zero bit is detected, marking start of transmission
184
+ DETECT_START: begin
185
+ if (insert_location == (OVERSAMPLE_FACTOR - 5)) begin
186
+ busy <= ~obtained_bit(oversampled_bit); // Decide what bit was received
187
+ oversampled_bit <= 15'b0; // Reset the oversampling buffer
188
+ end
189
+ else
190
+ oversampled_bit[insert_location] <= rx; // Fill the oversample buffer
191
+
192
+ if(busy)
193
+ insert_location <= 0; // Increment insertion location
194
+ else
195
+ insert_location <= insert_location + 1;
196
+ end
197
+
198
+ // Once transmission start is confirmed, start receiving the data, with oversampling
199
+ STARTED: begin
200
+ oversampled_bit[insert_location] <= rx;
201
+ insert_location <= insert_location + 1;
202
+
203
+ // Once oversampling buffer is full, decide what bit was received
204
+ if (insert_location == OVERSAMPLE_FACTOR - 1) begin
205
+ sampled_rx_data[bit_location] <= obtained_bit(oversampled_bit);
206
+ oversampled_bit <= 15'b0; // Reset the oversampling buffer
207
+
208
+ bit_location <= bit_location + 1;
209
+ end
210
+ end
211
+
212
+ // Transmission complete, check parity, put out data and other flag bits
213
+ CONVERSION: begin
214
+ if(~converted) begin
215
+ converted <= 1;
216
+ data <= sampled_rx_data[FRAME_BITS-1:0];
217
+
218
+ if(PARITY_BIT < 2) begin
219
+ if (^data == PARITY_BIT)
220
+ data_valid <= 1;
221
+ else
222
+ data_valid <= 0;
223
+ end
224
+ else
225
+ data_valid <= 1;
226
+ end
227
+ end
228
+ endcase
229
+ end
230
+
231
+ // Function to decide the received bit, depending on the oversampled data bits
232
+ function obtained_bit (input [OVERSAMPLE_FACTOR-1:0] oversampled_vector);
233
+ obtained_bit = (oversampled_vector[SAMPLE_LOC_1] & oversampled_vector[SAMPLE_LOC_2]) |
234
+ (oversampled_vector[SAMPLE_LOC_2] & oversampled_vector[SAMPLE_LOC_3]) |
235
+ (oversampled_vector[SAMPLE_LOC_1] & oversampled_vector[SAMPLE_LOC_3]);
236
+ endfunction
237
+
238
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/uart_tx.v ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `timescale 10ns / 1ns
2
+
3
+ /*
4
+ * Custom TX design, to match the RX module
5
+ * Author: Shubhayu Das
6
+ * Date: 27th November, 2021
7
+ * Version: 1.2
8
+ * Last update: 28th Nov, 2021: Changed order of bytes to big-endian
9
+ *
10
+ ********************
11
+ * Inputs:
12
+ * clk: UART clk, which MUST match the clock on the RX module
13
+ * tx_enable: start transmitting data ASAP
14
+ * data: the actual data to be transmitted
15
+ ********************
16
+ * Parameters:
17
+ * FRAME_BITS: Number of data bits per transaction
18
+ * PARITY_BITS: 0/1 indicate odd or even parity, 2 disables parity
19
+ * STOP_BITS: Number of stop bits to send
20
+ * RETENTION_DURATION: Compensate for oversampling UART clock
21
+ *
22
+ ********************
23
+ * Outputs:
24
+ * tx: The TX data line
25
+ * tx_busy: signal to indicate TX line is busy, don't start anything else
26
+ *
27
+ ********************
28
+ * Features of this module:
29
+ *
30
+ * This module automatically compensates for the faster UART clock being used
31
+ * for oversampling in the RX module. This is controlled by the
32
+ * RETENTION_DURATION" parameter.
33
+ *
34
+ * The input data is sampled as soon as "tx_enable" is set(on the next clock posedge)
35
+ * The input data is stored locally, the source register's value can change
36
+ * freely, without corrupting the TX activity.
37
+ *
38
+ * The data being sent is automatically flipped. So data[7:0] is sent as data[0:7]
39
+ */
40
+
41
+
42
+ module uart_tx #(
43
+ parameter FRAME_BITS = 8, // Number of data bits, can be 7/8
44
+ PARITY_BIT = 2, // Parity disabled by default
45
+ STOP_BITS = 1, // Using only 1 stop bit
46
+ RETENTION_DURATION = 15 // Compensate for oversampling in RX
47
+ )(
48
+ input clk,
49
+ input tx_enable,
50
+ input [FRAME_BITS-1:0] data,
51
+ output reg tx,
52
+ output reg tx_busy
53
+ );
54
+
55
+ function integer clog2;
56
+ input integer value;
57
+ integer temp;
58
+ begin
59
+ temp = value - 1;
60
+ for (clog2 = 0; temp > 0; clog2 = clog2 + 1) begin
61
+ temp = temp >> 1;
62
+ end
63
+ end
64
+ endfunction
65
+
66
+ // Knowing how bits need to be sent
67
+ localparam N_TX_BITS = (PARITY_BIT < 2) ?
68
+ (1+FRAME_BITS+1+STOP_BITS) : (1+FRAME_BITS+STOP_BITS);
69
+ localparam INDEX_SIZE = clog2(N_TX_BITS);
70
+
71
+ // FSM states
72
+ localparam IDLE = 0; // Wait for tx_enable to be set
73
+ localparam CAPTURE = 1; // Copy data into local_data, with parity, stop bits
74
+ localparam TRANSMITTING = 2;// Data being put on TX line
75
+
76
+ reg [2:0] state;
77
+ reg data_framed; // Indicates data has been copied to local_data
78
+
79
+ reg [INDEX_SIZE:0] bit_index;
80
+
81
+ reg [0:N_TX_BITS-1] local_data; // local data register
82
+
83
+ // Keeps TX high for requisite number of cycles
84
+ reg [clog2(RETENTION_DURATION):0] retention_counter;
85
+
86
+
87
+ initial begin
88
+ tx = 1;
89
+ tx_busy = 0;
90
+
91
+ state = IDLE;
92
+ bit_index = 0;
93
+ data_framed = 0;
94
+ local_data = 0;
95
+
96
+ // This is NOT a mistake
97
+ // This compensates for the immediate addition that happens
98
+ // in "TRANSMITTING" state
99
+ retention_counter = RETENTION_DURATION;
100
+ end
101
+
102
+ // Handle the state changes
103
+ always @(posedge clk) begin
104
+ case(state)
105
+ IDLE:
106
+ state <= (tx_enable) ? CAPTURE : IDLE;
107
+
108
+ CAPTURE:
109
+ state <= (data_framed) ? TRANSMITTING : CAPTURE;
110
+
111
+ TRANSMITTING:
112
+ state <= (bit_index == N_TX_BITS) ? IDLE : TRANSMITTING;
113
+ endcase
114
+ end
115
+
116
+ always @(posedge clk) begin
117
+ case(state)
118
+ IDLE: begin
119
+ tx <= 1;
120
+ tx_busy <= 0;
121
+ bit_index <= 0;
122
+ local_data <= 0;
123
+ data_framed <= 0;
124
+ retention_counter <= RETENTION_DURATION;
125
+ end
126
+
127
+ CAPTURE: begin
128
+ tx_busy <= 1;
129
+
130
+ // The data needs to be reversed
131
+ if(PARITY_BIT < 2) begin
132
+ local_data <= {
133
+ 1'b0, // Start bit
134
+ data[0], // Reversed data
135
+ data[1],
136
+ data[2],
137
+ data[3],
138
+ data[4],
139
+ data[5],
140
+ data[6],
141
+ data[7],
142
+ ^data, // Parity
143
+ {(STOP_BITS){1'b1}} // Stop bit(s)
144
+ };
145
+ data_framed <= 1;
146
+ end
147
+ else begin
148
+ // Same as above, but without parity
149
+ local_data <= {
150
+ 1'b0,
151
+ data[0],
152
+ data[1],
153
+ data[2],
154
+ data[3],
155
+ data[4],
156
+ data[5],
157
+ data[6],
158
+ data[7],
159
+ {(STOP_BITS){1'b1}}
160
+ };
161
+ data_framed <= 1;
162
+ end
163
+ end
164
+
165
+ TRANSMITTING: begin
166
+ if(retention_counter == 0) begin
167
+ tx <= local_data[bit_index];
168
+ bit_index <= bit_index + 1;
169
+
170
+ if(bit_index == N_TX_BITS)
171
+ tx_busy <= 0;
172
+
173
+ end
174
+
175
+ if(retention_counter < RETENTION_DURATION)
176
+ retention_counter <= retention_counter + 1;
177
+ else
178
+ retention_counter <= 0;
179
+ end
180
+ endcase
181
+ end
182
+
183
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/vga_controller.v ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `timescale 1ns / 1ps
2
+ //////////////////////////////////////////////////////////////////////////////////
3
+ // Reference Book:
4
+ // Chu, Pong P.
5
+ // Wiley, 2008
6
+ // "FPGA Prototyping by Verilog Examples: Xilinx Spartan-3 Version"
7
+ //
8
+ // Adapted for the Basys 3 by David J. Marion
9
+ // Comments by David J. Marion
10
+ //
11
+ // FOR USE WITH AN FPGA THAT HAS A 100MHz CLOCK SIGNAL ONLY.
12
+ // VGA Mode
13
+ // 640x480 pixels VGA screen with 25MHz pixel rate based on 60 Hz refresh rate
14
+ // 800 pixels/line * 525 lines/screen * 60 screens/second = ~25.2M pixels/second
15
+ //
16
+ // A 25MHz signal will suffice. The Basys 3 has a 100MHz signal available, so a
17
+ // 25MHz tick is created for syncing the pixel counts, pixel tick, horiz sync,
18
+ // vert sync, and video on signals.
19
+ //////////////////////////////////////////////////////////////////////////////////
20
+
21
+ module vga_controller(
22
+ input wire clk, // from Basys 3
23
+ input reset, // system reset
24
+ output video_on, // ON while pixel counts for x and y and within display area
25
+ output hsync, // horizontal sync
26
+ output vsync, // vertical sync
27
+ output p_tick, // the 25MHz pixel/second rate signal, pixel tick
28
+ output [9:0] x, // pixel count/position of pixel x, max 0-799
29
+ output [9:0] y // pixel count/position of pixel y, max 0-524
30
+ );
31
+
32
+ // Based on VGA standards found at vesa.org for 640x480 resolution
33
+ // Total horizontal width of screen = 800 pixels, partitioned into sections
34
+ parameter HD = 640; // horizontal display area width in pixels
35
+ parameter HF = 48; // horizontal front porch width in pixels
36
+ parameter HB = 16; // horizontal back porch width in pixels
37
+ parameter HR = 96; // horizontal retrace width in pixels
38
+ parameter HMAX = HD+HF+HB+HR-1; // max value of horizontal counter = 799
39
+ // Total vertical length of screen = 525 pixels, partitioned into sections
40
+ parameter VD = 480; // vertical display area length in pixels
41
+ parameter VF = 10; // vertical front porch length in pixels
42
+ parameter VB = 33; // vertical back porch length in pixels
43
+ parameter VR = 2; // vertical retrace length in pixels
44
+ parameter VMAX = VD+VF+VB+VR-1; // max value of vertical counter = 524
45
+
46
+ // Counter Registers, two each for buffering to avoid glitches
47
+ reg [9:0] h_count_reg, h_count_next;
48
+ reg [9:0] v_count_reg, v_count_next;
49
+
50
+ // Output Buffers
51
+ reg v_sync_reg, h_sync_reg;
52
+ wire v_sync_next, h_sync_next;
53
+
54
+ always @(posedge clk or posedge reset)
55
+ if (reset) begin
56
+ v_count_reg <= 0;
57
+ h_count_reg <= 0;
58
+ v_sync_reg <= 1'b0;
59
+ h_sync_reg <= 1'b0;
60
+ end else begin
61
+ // Logika za horizontalni brojač
62
+ if (h_count_reg == HMAX) begin
63
+ h_count_reg <= 0;
64
+ // Logika za vertikalni brojač
65
+ if (v_count_reg == VMAX)
66
+ v_count_reg <= 0;
67
+ else
68
+ v_count_reg <= v_count_reg + 1;
69
+ end else begin
70
+ h_count_reg <= h_count_reg + 1;
71
+ end
72
+
73
+ // Ažuriranje sinhronizacije
74
+ v_sync_reg <= v_sync_next;
75
+ h_sync_reg <= h_sync_next;
76
+ end
77
+
78
+ // reg r_25MHz;
79
+ // wire w_25MHz;
80
+
81
+ // always @(posedge clk or posedge reset)
82
+ // if(reset)
83
+ // r_25MHz <= 0;
84
+ // else
85
+ // r_25MHz <= r_25MHz + 1;
86
+
87
+ // assign w_25MHz = (r_25MHz == 0) ? 1 : 0; // assert tick 1/2 of the time
88
+
89
+ // // Register Control
90
+ // always @(posedge clk or posedge reset)
91
+ // if(reset) begin
92
+ // v_count_reg <= 0;
93
+ // h_count_reg <= 0;
94
+ // v_sync_reg <= 1'b0;
95
+ // h_sync_reg <= 1'b0;
96
+ // end
97
+ // else begin
98
+ // v_count_reg <= v_count_next;
99
+ // h_count_reg <= h_count_next;
100
+ // v_sync_reg <= v_sync_next;
101
+ // h_sync_reg <= h_sync_next;
102
+ // end
103
+
104
+ // //Logic for horizontal counter
105
+ // always @(posedge w_25MHz or posedge reset) // pixel tick
106
+ // if(reset)
107
+ // h_count_next = 0;
108
+ // else
109
+ // if(h_count_reg == HMAX) // end of horizontal scan
110
+ // h_count_next = 0;
111
+ // else
112
+ // h_count_next = h_count_reg + 1;
113
+
114
+ // // Logic for vertical counter
115
+ // always @(posedge w_25MHz or posedge reset)
116
+ // if(reset)
117
+ // v_count_next = 0;
118
+ // else
119
+ // if(h_count_reg == HMAX) // end of horizontal scan
120
+ // if((v_count_reg == VMAX)) // end of vertical scan
121
+ // v_count_next = 0;
122
+ // else
123
+ // v_count_next = v_count_reg + 1;
124
+
125
+ // h_sync_next asserted within the horizontal retrace area
126
+ assign h_sync_next = (h_count_reg >= (HD+HB) && h_count_reg <= (HD+HB+HR-1));
127
+
128
+ // v_sync_next asserted within the vertical retrace area
129
+ assign v_sync_next = (v_count_reg >= (VD+VB) && v_count_reg <= (VD+VB+VR-1));
130
+
131
+ // Video ON/OFF - only ON while pixel counts are within the display area
132
+ assign video_on = (h_count_reg < HD) && (v_count_reg < VD); // 0-639 and 0-479 respectively
133
+
134
+ // Outputs
135
+ assign hsync = h_sync_reg;
136
+ assign vsync = v_sync_reg;
137
+ assign x = h_count_reg;
138
+ assign y = v_count_reg;
139
+ assign p_tick = clk;
140
+
141
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/vga_map_ram.v ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ module vga_map_ram (
3
+ input clk,
4
+ input wen,
5
+ input [11:0] waddr,
6
+ input [3:0] wdata,
7
+ input ren,
8
+ input [11:0] raddr,
9
+ output reg [3:0] rdata
10
+ );
11
+ //parameter MEM_INIT_FILE = "vid_ram.mem";
12
+ (* ram_style = "block" *) reg [3:0] map_ram [0:1199]; // memory for 40 x 30 position mega character with value between 0-15 for character id
13
+
14
+ //initial
15
+ //if (MEM_INIT_FILE != "")
16
+ // $readmemh(MEM_INIT_FILE, map_ram);
17
+
18
+ always @(posedge clk)
19
+ begin
20
+ if (ren)
21
+ rdata <= map_ram[raddr];
22
+ end
23
+
24
+ always @(posedge clk)
25
+ begin
26
+ if (wen)
27
+ map_ram[waddr] <= wdata;
28
+ end
29
+
30
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/vga_ram.v ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ module vga_ram (
3
+ input clk,
4
+ input wen,
5
+ input [11:0] waddr,
6
+ input [11:0] wdata,
7
+ input ren,
8
+ input [11:0] raddr,
9
+ output reg [11:0] rdata
10
+ );
11
+ //parameter MEM_INIT_FILE = "vid_ram.mem";
12
+ (* ram_style = "block" *) reg [11:0] ram [0:4095]; // memory for 16 character with dimension 16x16 pixels @ 12bpp // bio distribuirani
13
+
14
+ //initial
15
+ //if (MEM_INIT_FILE != "")
16
+ // $readmemh(MEM_INIT_FILE, ram);
17
+
18
+ always @(posedge clk)
19
+ begin
20
+ if (ren)
21
+ rdata <= ram[raddr];
22
+ end
23
+
24
+ always @(posedge clk)
25
+ begin
26
+ if (wen)
27
+ ram[waddr] <= wdata;
28
+ end
29
+
30
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/1.hw/vga_wrapper.v ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `timescale 1ns / 1ps
2
+
3
+ module vga_wrapper (
4
+ input clk,
5
+ input reset, // system reset
6
+
7
+ output reg vga_iomem_ready,
8
+ input iomem_valid,
9
+ input iomem_ready,
10
+ input [3:0] iomem_wstrb,
11
+ input [31:0] iomem_addr,
12
+ input [31:0] iomem_wdata,
13
+
14
+ input video_on,
15
+ input [9:0] x, y,
16
+ output reg [11:0] rgb,
17
+
18
+ output[4:0] o_debug_pins
19
+ );
20
+
21
+ // signal declarations
22
+ wire charset_on, charset_on1, charset_on2;
23
+ reg char_mem_write, map_mem_write;
24
+ wire [11:0] write_address;
25
+ wire [11:0] read_address, map_read_address;
26
+ wire [11:0] rgb_rdata;
27
+ wire [3:0] map_rdata;
28
+
29
+ always @(posedge clk)
30
+ begin
31
+ if (reset) begin
32
+ char_mem_write <= 0;
33
+ map_mem_write <= 0;
34
+ end else begin
35
+ vga_iomem_ready <= 0;
36
+ char_mem_write <= 0;
37
+ map_mem_write <= 0;
38
+ if (iomem_valid && !iomem_ready) begin
39
+ vga_iomem_ready <= 1;
40
+ if(iomem_addr[23:20]==4'h1) begin
41
+ if(iomem_wstrb[0]) begin
42
+ char_mem_write <= 1;
43
+ end
44
+ end else if(iomem_addr[23:20]==4'h2) begin
45
+ if(iomem_wstrb[0]) begin
46
+ map_mem_write <= 1;
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
52
+
53
+ assign write_address = (iomem_addr[15:0]/4);
54
+ assign read_address = {map_rdata, y[3:0], x[3:0]};
55
+ assign map_read_address = ( y >> 4 ) * 6'd40 + ( x >> 4 );
56
+
57
+ vga_map_ram map(
58
+ .clk(clk),
59
+ .wen(map_mem_write),
60
+ .waddr(write_address),
61
+ .wdata(iomem_wdata[3:0]),
62
+ .ren(video_on),
63
+ .raddr(map_read_address),
64
+ .rdata(map_rdata)
65
+ );
66
+
67
+ vga_ram ram(
68
+ .clk(clk),
69
+ .wen(char_mem_write),
70
+ .waddr(write_address),
71
+ .wdata(iomem_wdata[11:0]),
72
+ .ren(video_on),
73
+ .raddr(read_address),
74
+ .rdata(rgb_rdata)
75
+ );
76
+
77
+
78
+ // rgb multiplexing circuit
79
+ always @(*)
80
+ begin
81
+ if(~video_on)
82
+ rgb = 12'h000; // blank
83
+ else
84
+ rgb = rgb_rdata;
85
+ end
86
+
87
+ assign o_debug_pins = {1'b0, 1'b0, 1'b0, 1'b0, 1'b0};
88
+
89
+ endmodule
chili-chips-ba_openCologne/5.TetriSaraj/2.sim/README.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HW/SW co-sim with VProc VIP
2
+ by Simon Southwell
3
+ <p align="center">
4
+ <img src="0.doc/wyvernSemi.png">
5
+ </p>
6
+
7
+
8
+ ## First things first
9
+ - [Vproc Intro](https://drive.google.com/file/d/1V81Q9Ue9HjQIpum2KXUp8eKwzed-kwfm)
10
+ - [VProc Manual](https://github.com/wyvernSemi/vproc/blob/master/doc/VProc.pdf)
11
+
12
+
13
+ ## Native Mode
14
+ <img src="0.doc/vproc_tb_native.png">
15
+
16
+
17
+ ## ISS Mode
18
+ <img src="0.doc/vproc_tb_iss.png">
19
+
20
+
21
+ ## Testbench structure
22
+ <img src="0.doc/vid_ctlr_tb_vproc.png">
23
+
24
+ ## How to build and run it
25
+
26
+ ## Misc Tidbits: VProc Node
27
+ Node is simply memory mapped in _display.v_ for cross referencing. When using the C API or when creating a new C++ API object, the node number must be used to connect to a given VProc instantiation which might, accidently, be the wrong one. This simply gives a means, if desired, to check that the API object is connected to the expected node for safety and avoiding unexpected behaviour. It does not have to be there for VProc to work.
28
+
29
+ ## Misc Tidbits: VProc Delta-Cycle Processing
30
+ The "delta-cycle" process can't be a clock in order to access more than 32 bits to read and/or update in a single cycle. Conceivably if one needed to access, say, ten 32-bit ports, then VProc could be run 10 times faster to update by the end of the external clock, but this is an arbitrary number and might not work for all possible cases.
31
+
32
+ It would likely run slower than using the delta-cycle updates. It's only needed, in any case, if using VProc to memory map ports---and the jury is out for _display.v_ and I need to measure its impact on performance.
33
+
34
+ The whole delta cycle logic can be disabled by setting VProc's **DISABLE_DELTA** generic to non-zero, and the **Update** and **UpdateResponse** signals are then unconnected. In a test bench that only has VProcs used as a 32-bit memory mapped virtual CPUs, then this feature can be ignored and configured out.
35
+
36
+ Delta cycle accesses are used for pcievhost, but it might conceivably be configured out for a single lane 8b10b bit in and out port (20 bits) and a electrical idle in and out, but two lanes or more is not possible as this will require multiple accesses per cycle.
37
+
38
+ ## References
39
+ - [LI-2024-01](https://www.linkedin.com/pulse/vproc-virtual-processor-vip-simon-southwell-pjmpe)
40
+ - [LI-2024-10](https://www.linkedin.com/posts/simon-southwell-7684482_riscv-iss-embeddedsoftware-activity-7256311551178027008-1nlZ?utm_source=share&utm_medium=member_desktop)
41
+ - [VGASIM](https://github.com/wyvernSemi/vgasim)
42
+
43
+
44
+ #### End of Document
chili-chips-ba_openCologne/5.TetriSaraj/2.sw/main.c ADDED
@@ -0,0 +1,1212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * PicoSoC - A simple example SoC using PicoRV32
3
+ *
4
+ * Coyright (C) 2017 Clifford Wolf <clifford@clifford.at>
5
+ *
6
+ * Permission to use, coy, modify, and/or distribute this software for any
7
+ * purpose with or without fee is hereby granted, provided that the above
8
+ * coyright notice and this permission notice appear in all copies.
9
+ *
10
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ *
18
+ */
19
+
20
+ // INCLUDES AND DEFINES--------------------------------------------------
21
+
22
+ #include <stdint.h>
23
+ #include <stdbool.h>
24
+ #include "uart.h"
25
+
26
+ #define RAM_TOTAL 0x2000 // 8 KB
27
+
28
+ #define reg_uart_clkdiv (*(volatile uint32_t*)0x02000004)
29
+ #define reg_uart_data (*(volatile uint32_t*)0x02000008)
30
+
31
+ #define reg_gpio (*(volatile uint32_t*) 0x03000000)
32
+ #define reg_video_char ((volatile uint32_t*)0x05100000)
33
+ #define reg_video_map ((volatile uint32_t*)0x05200000)
34
+
35
+ #define BUTTON_UP 0x01 // 0000 0001
36
+ #define BUTTON_RIGHT 0x02 // 0000 0010
37
+ #define BUTTON_LEFT 0x04 // 0000 0100
38
+ #define BUTTON_DOWN 0x08 // 0000 1000
39
+ #define BUTTON_CENTER 0x10 // 0001 0000
40
+
41
+ #define DELAY 2500
42
+
43
+ #define fieldWidth 40
44
+ #define fieldHeight 30
45
+
46
+ // GLOBAL VARIABLES--------------------------------------------------------
47
+
48
+ uint8_t buttons;
49
+ static uint32_t delay = DELAY;
50
+ static uint8_t field[1200];
51
+
52
+ static uint8_t tetrominoes[7][16]={{1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0},
53
+ {0,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0},
54
+ {0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0},
55
+ {0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0},
56
+ {0,1,0,0,0,1,1,0,0,0,1,0,0,0,0,0},
57
+ {0,1,0,0,0,1,0,0,0,1,1,0,0,0,0,0},
58
+ {0,0,1,0,0,0,1,0,0,1,1,0,0,0,0,0}};
59
+
60
+ // PRIVATE FUNCTIONS DECLARATIONS--------------------------------------------
61
+
62
+ static void CharactersInit(void);
63
+ static void DisplayProjectName(void);
64
+ static void DisplayCompanyName(void);
65
+ static void DisplayGameName(void);
66
+ static void DisplayHeart(int x_start, int y_start, int color);
67
+ static void setScreenColor(int color);
68
+ static void DisplayGameOverScreen(int numLives );
69
+ static void DisplayTheEndScreen(void);
70
+ static void GetButtonStates(void);
71
+ static int Rotate(int x, int y, int r);
72
+ static bool DoesPieceFit(int ntetrominoes, int nRotation, int nPosX, int nPosY);
73
+ static void DisplayDigit(uint8_t number, uint8_t startX, uint8_t startY);
74
+ static void WriteScore(int score);
75
+
76
+ // PRIVATE FUNCTIONS IMPLEMENTATION-------------------------------------------
77
+
78
+ /*
79
+ * brief reads the gpio register and changes the state of buttons variable
80
+ * return void
81
+ */
82
+ void GetButtonStates() {
83
+ buttons = (uint8_t)(reg_gpio >> 16)&0xFF;
84
+ }
85
+
86
+ /*
87
+ * brief displays GATEMATE Demo on the screen
88
+ * return void
89
+ */
90
+ void DisplayProjectName()
91
+ {
92
+ uint8_t nameY = 3;
93
+ for (uint8_t y = 0; y < 30; y++)
94
+ {
95
+ for (uint8_t x = 0; x < 40; x++) // Board Boundary
96
+ {
97
+ reg_video_map[y * 40 + x] = 12; // Background color
98
+ //G
99
+ if ((y == nameY && (x >= 3 && x <= 5)) || (y == nameY + 4 && (x >= 3 && x <= 5)) || (x == 3 && (y >= nameY && y <= nameY + 4)) || (x == 5 && (y >= nameY + 2 && y <= nameY + 4)))
100
+ reg_video_map[y * 40 + x] = 0;
101
+ //a
102
+ if((x == 7 || x == 9) && (y >= nameY + 1 && y <= nameY + 4) || (x == 8 && y == nameY + 2) || (x == 8 && y == nameY))
103
+ reg_video_map[y * 40 + x] = 0;
104
+ //t
105
+ if ((y == nameY && (x >= 11 && x <= 13)) || (x == 12 && (y >= nameY && y <= nameY + 4)))
106
+ reg_video_map[y * 40 + x] = 0;
107
+ //e
108
+ if (((y == nameY || y == nameY + 4) && (x >= 15 && x <= 17)) || (y == nameY + 2 && x == 16) || (x == 15 && (y >= nameY && y <= nameY + 4)))
109
+ reg_video_map[y * 40 + x] = 0;
110
+ //M
111
+ if ((y == nameY && (x == 20 || x == 21 || x == 23 || x == 24)) || (x == 20 && (y >= nameY && y <= nameY + 4)) || (x == 24 && (y >= nameY && y <= nameY + 4)) || (x == 22 && y == nameY + 1))
112
+ reg_video_map[y * 40 + x] = 11;
113
+ //a
114
+ if((x == 26 || x == 28) && (y >= nameY + 1 && y <= nameY + 4) || (x == 27 && y == nameY + 2) || (x == 27 && y == nameY))
115
+ reg_video_map[y * 40 + x] = 11;
116
+ //t
117
+ if ((y == nameY && (x >= 30 && x <= 32)) || (x == 31 && (y >= nameY && y <= nameY + 4)))
118
+ reg_video_map[y * 40 + x] = 11;
119
+ //e
120
+ if (((y == nameY || y == nameY + 4) && (x >= 34 && x <= 36)) || (y == nameY + 2 && x == 35) || (x == 34 && (y >= nameY && y <= nameY + 4)))
121
+ reg_video_map[y * 40 + x] = 11;
122
+ }
123
+ }
124
+ }
125
+
126
+
127
+ /*
128
+ * brief displays CHILI CHIPS on the screen
129
+ * return void
130
+ */
131
+ void DisplayCompanyName()
132
+ {
133
+ uint8_t lineY = 11;
134
+ uint8_t lineXStart = 3, lineXEnd = 36;
135
+ uint8_t nameY = 14;
136
+ for (uint8_t y = 0; y < 30; y++)
137
+ {
138
+ for (uint8_t x = 0; x < 40; x++) // Board Boundary
139
+ {
140
+ // blue line
141
+ if (y == lineY && (x >= lineXStart && x <= lineXEnd))
142
+ reg_video_map[y * 40 + x] = 10;
143
+
144
+ //C
145
+ if (x == 4 && (y >= nameY && y <= nameY + 4))
146
+ reg_video_map[y * 40 + x] = 7;
147
+ if (y == nameY && (x == 5 || x == 6))
148
+ reg_video_map[y * 40 + x] = 7;
149
+ if (y == nameY + 4 && (x == 5 || x == 6))
150
+ reg_video_map[y * 40 + x] = 7;
151
+ //h
152
+ if (x == 8 && (y >= nameY && y <= nameY + 4) )
153
+ reg_video_map[y*40+x]=7;
154
+ if (y == nameY + 2 && (x == 9 || x == 10))
155
+ reg_video_map[y * 40 + x] = 7;
156
+ if (x == 10 && (y >= nameY + 2 && y <= nameY + 4))
157
+ reg_video_map[y * 40 + x] = 7;
158
+ // i
159
+ if (x == 12 && (y >= nameY + 2 && y <= nameY + 4))
160
+ reg_video_map[y * 40 + x] = 7;
161
+ if (x == 12 && y == nameY)
162
+ reg_video_map[y * 40 + x] = 7;
163
+ // l
164
+ if (x == 14 && (y >= nameY && y <= nameY + 4))
165
+ reg_video_map[y * 40 + x]=7;
166
+ // i
167
+ if (x == 16 && (y >= nameY + 2 && y <= nameY + 4))
168
+ reg_video_map[y * 40 + x] = 7;
169
+ if (x == 16 && y == nameY)
170
+ reg_video_map[y * 40 + x] = 7;
171
+ // C
172
+ if (x == 19 && (y >= nameY && y <= nameY + 4) )
173
+ reg_video_map[y * 40 + x] = 2;
174
+ if (y == nameY && (x == 20 || x == 21))
175
+ reg_video_map[y * 40 + x] = 2;
176
+ if (y == nameY + 4 && (x == 20 || x == 21))
177
+ reg_video_map[y * 40 + x] = 2;
178
+ //H
179
+ if (x == 23 && (y >= nameY && y <= nameY + 4))
180
+ reg_video_map[y * 40 + x] = 2;
181
+ if (y == nameY + 2 && (x == 24 || x == 25))
182
+ reg_video_map[y * 40 + x] = 2;
183
+ if (x == 25 && (y >= nameY && y <= nameY + 4))
184
+ reg_video_map[y * 40 + x] = 2;
185
+ // I
186
+ if (x == 27 && (y >= nameY && y <= nameY + 4))
187
+ reg_video_map[y * 40 + x] = 2;
188
+ // P
189
+ if (x == 29 && (y >= nameY && y <= nameY + 4))
190
+ reg_video_map[y * 40 + x] = 2;
191
+ if (y == nameY && (x == 30 || x == 31))
192
+ reg_video_map[y * 40 + x] = 2;
193
+ if (y == nameY + 2 && (x == 30 || x == 31))
194
+ reg_video_map[y * 40 + x] = 2;
195
+ if (x == 31 && (y >= nameY && y <= nameY + 2))
196
+ reg_video_map[y * 40 + x] = 2;
197
+ // S
198
+ if (y == nameY && (x >= 33 && x <= 35 ))
199
+ reg_video_map[y * 40 + x] = 2;
200
+ if (y == nameY + 2 && (x >= 33 && x <= 35))
201
+ reg_video_map[y * 40 + x] = 2;
202
+ if (y == nameY + 4 && (x >= 33 && x <= 35))
203
+ reg_video_map[y * 40 + x] = 2;
204
+ if (x == 33 && y == nameY + 1)
205
+ reg_video_map[y * 40 + x] = 2;
206
+ if (x == 35 && y == nameY + 3)
207
+ reg_video_map[y * 40 + x] = 2;
208
+ }
209
+ }
210
+ }
211
+
212
+ /*
213
+ * brief displays TETRISARAJ on the screen
214
+ * return void
215
+ */
216
+ void DisplayGameName()
217
+ {
218
+ uint8_t nameY = 22;
219
+ for (uint8_t y = 0; y < 30; y++)
220
+ {
221
+ for (uint8_t x = 0; x < 40; x++) // Board Boundary
222
+ {
223
+ //T
224
+ if(y == nameY && (x>=2 && x<=4) || (x == 3 && (y >= nameY && y <= nameY + 4)))
225
+ reg_video_map[y * 40 + x] = 2;
226
+ //E
227
+ if (((y == nameY || y == nameY + 4) && (x >= 6 && x <= 8)) || (y == nameY + 2 && x == 7) || (x == 6 && (y >= nameY && y <= nameY + 4)))
228
+ reg_video_map[y * 40 + x] = 2;
229
+ //T
230
+ if(y == nameY && (x >= 10 && x <= 12))
231
+ reg_video_map[y * 40 + x] = 2;
232
+ if(x == 11 && (y >= nameY && y <= nameY + 4))
233
+ reg_video_map[y * 40 + x] = 2;
234
+ //R
235
+ if(x == 14 && (y >= nameY && y <= nameY + 4))
236
+ reg_video_map[y * 40 + x] = 2;
237
+ if(x == 15 && y== nameY)
238
+ reg_video_map[y * 40 + x] = 2;
239
+ if(x == 16 && y == nameY + 1)
240
+ reg_video_map[y * 40 + x] = 2;
241
+ if(x == 15 && y == nameY + 2)
242
+ reg_video_map[y * 40 + x] = 2;
243
+ if(x == 16 && (y == nameY + 3 || y == nameY + 4))
244
+ reg_video_map[y * 40 + x] = 2;
245
+ //I
246
+ if(x == 18 && (y >= nameY && y <= nameY + 4))
247
+ reg_video_map[y * 40 + x] = 2;
248
+ //S
249
+ if(y == nameY && (x == 20 || x == 21))
250
+ reg_video_map[y * 40 + x] = 7;
251
+ if(x == 20 && (y == nameY + 1 || y == nameY + 2 || y == nameY + 4))
252
+ reg_video_map[y * 40 + x] = 7;
253
+ if(x == 21 && (y >= nameY + 2 && y <= nameY + 4))
254
+ reg_video_map[y * 40 + x] = 7;
255
+ //A
256
+ if((x == 23 || x == 25) && (y >= nameY + 1 && y <= nameY + 4))
257
+ reg_video_map[y * 40 + x] = 7;
258
+ if(x == 24 && y == nameY + 2)
259
+ reg_video_map[y * 40 + x] = 7;
260
+ if(x == 24 && y == nameY)
261
+ reg_video_map[y * 40 + x] = 7;
262
+ //R
263
+ if(x == 27 && (y >= nameY && y <= nameY + 4))
264
+ reg_video_map[y * 40 + x] = 7;
265
+ if(x == 28 && y == nameY)
266
+ reg_video_map[y * 40 + x] = 7;
267
+ if(x == 29 && y == nameY + 1)
268
+ reg_video_map[y * 40 + x] = 7;
269
+ if(x == 28 && y == nameY + 2)
270
+ reg_video_map[y * 40 + x] = 7;
271
+ if(x == 29 && (y == nameY + 3 || y == nameY + 4))
272
+ reg_video_map[y * 40 + x] = 7;
273
+ //A
274
+ if((x == 31 || x == 33) && (y >= nameY + 1 && y <= nameY + 4))
275
+ reg_video_map[y * 40 + x] = 7;
276
+ if(x == 32 && y == nameY + 2)
277
+ reg_video_map[y * 40 + x] = 7;
278
+ if(x == 32 && y == nameY)
279
+ reg_video_map[y * 40 + x] = 7;
280
+ //J
281
+ if(x == 37 && (y >= nameY && y <= nameY + 4))
282
+ reg_video_map[y * 40 + x] = 7;
283
+ if((x == 35 || x == 36) && y == nameY + 4)
284
+ reg_video_map[y * 40 + x] = 7;
285
+ if(x == 35 && y == nameY + 3)
286
+ reg_video_map[y * 40 + x] = 7;
287
+ }
288
+ }
289
+ }
290
+ /*
291
+ * brief displays heart on screen
292
+ * return void
293
+ */
294
+ void DisplayHeart(int x_start, int y_start, int color){
295
+ for (int y = 0; y < 30; y++)
296
+ {
297
+ for (int x = 0; x < 40; x++) // Board Boundary
298
+ {
299
+ if((x==2+x_start || x==3+x_start || x==7+x_start || x==8+x_start) && y==y_start)
300
+ reg_video_map[y * 40 + x] = 0;
301
+ if((x==1+x_start || x==4+x_start || x==6+x_start || x==9+x_start) && y==y_start+1)
302
+ reg_video_map[y * 40 + x] = 0;
303
+ if((x==x_start || x==5+x_start || x==10+x_start) && y==y_start+2)
304
+ reg_video_map[y * 40 + x] = 0;
305
+ if((x==x_start || x==10+x_start) && y==y_start+3)
306
+ reg_video_map[y * 40 + x] = 0;
307
+ if((x==1+x_start || x==9+x_start) && y==y_start+4)
308
+ reg_video_map[y * 40 + x] = 0;
309
+ if((x==2+x_start || x==8+x_start) && y==y_start+5)
310
+ reg_video_map[y * 40 + x] = 0;
311
+ if((x==3+x_start || x==7+x_start) && y==y_start+6)
312
+ reg_video_map[y * 40 + x] = 0;
313
+ if((x==4+x_start || x==6+x_start) && y==y_start+7)
314
+ reg_video_map[y * 40 + x] = 0;
315
+ if((x==5+x_start) && y==y_start+8)
316
+ reg_video_map[y * 40 + x] = 0;
317
+
318
+ if((x==2+x_start || x==3+x_start || x==7+x_start || x==8+x_start) && y==y_start+1)
319
+ reg_video_map[y * 40 + x] = color;
320
+ if(((x>=1+x_start && x<=4+x_start) || (x>=6+x_start && x<=9+x_start)) && y==y_start+2)
321
+ reg_video_map[y * 40 + x] = color;
322
+ if((x>=1+x_start && x<=9+x_start) && y==y_start+3)
323
+ reg_video_map[y * 40 + x] = color;
324
+ if((x>=2+x_start && x<=8+x_start) && y==y_start+4)
325
+ reg_video_map[y * 40 + x] = color;
326
+ if((x>=3+x_start && x<=7+x_start) && y==y_start+5)
327
+ reg_video_map[y * 40 + x] = color;
328
+ if((x>=4+x_start && x<=6+x_start) && y==y_start+6)
329
+ reg_video_map[y * 40 + x] = color;
330
+ if(x==5+x_start && y==y_start+7)
331
+ reg_video_map[y * 40 + x] = color;
332
+
333
+ }
334
+ }
335
+
336
+ }
337
+ /*
338
+ * brief set screen color
339
+ * return void
340
+ */
341
+ void setScreenColor(int color){
342
+ for (uint8_t y = 0; y < 30; y++)
343
+ {
344
+ for (uint8_t x = 0; x < 40; x++) // Board Boundary
345
+ {
346
+ reg_video_map[y * 40 + x] = color;
347
+ }
348
+ }
349
+ }
350
+ /*
351
+ * brief displays game over screen
352
+ * return void
353
+ */
354
+ void DisplayGameOverScreen(int numLives )
355
+ {
356
+ uint8_t nameY = 1;
357
+ for (uint8_t y = 0; y < 30; y++)
358
+ {
359
+ for (uint8_t x = 0; x < 40; x++) // Board Boundary
360
+ {
361
+ reg_video_map[y * 40 + x] = 9;
362
+
363
+ //G
364
+ if((x == 5 && (y >= nameY+2 && y <= nameY+5)) || (x == 6 && (y == nameY+1 || y == nameY+6)) || ((x >= 7 && x<= 11) && (y == nameY || y==nameY+7)) || (x==11 && (y>=nameY+4 && y<=nameY+7)) || (x >= 8 && x<= 11) && (y == nameY+4) )
365
+ reg_video_map[y * 40 + x] = 3;
366
+
367
+ //A
368
+ if((x==16 && y==nameY) || ((x==15 || x==17) && y==nameY+1) || ((x==14 || x==18) && (y>=nameY+2 && y<=nameY+3)) || ((x>=13 && x<=19) && y==nameY+4) || ((x==13 || x==19) && (y>=nameY+5 && y<=nameY+7)))
369
+ reg_video_map[y * 40 + x] = 1;
370
+
371
+ //M
372
+ if(((x==21 || x==28) && (y>=nameY && y<=nameY+7)) || ((x==22 || x==27) && y==nameY) || ((x==23 || x==26) && (y>=nameY+1 && y<=nameY+2)) || ((x==24 || x==25) && y==nameY+3))
373
+ reg_video_map[y * 40 + x] = 2;
374
+
375
+ //E
376
+ if(((x>=30 && x<=34) && (y==nameY || y==nameY+7)) || (x==30 && (y>=nameY+1 && y<=nameY+6)) || ((x>=31 && x<=33) && y==nameY+4))
377
+ reg_video_map[y * 40 + x] = 4;
378
+
379
+
380
+ //O
381
+ if(((x==7 || x==12) && (y>=nameY+11 && y<=nameY+16)) || ((y==nameY+10 || y==nameY+17) && (x>=8 && x<=11)))
382
+ reg_video_map[y * 40 + x] = 3;
383
+
384
+ //V
385
+ if(((x==14 || x==20) && (y>=nameY+10 && y<=nameY+12)) || ((x==15 || x==19) && (y>=nameY+13 && y<=nameY+14)) || ((x==16 || x==18) && (y==nameY+15)) || ((x==17) && (y>=nameY+16 && y<=nameY+17)))
386
+ reg_video_map[y * 40 + x] = 1;
387
+
388
+ //E
389
+ if(((x>=22 && x<=26) && (y==nameY+10 || y==nameY+17)) || (x==22 && (y>=nameY+11 && y<=nameY+16)) || ((x>=23 && x<=25) && y==nameY+14))
390
+ reg_video_map[y * 40 + x] = 2;
391
+
392
+ //R
393
+ if((x==28 && (y>=nameY+10 && y<=nameY+17)) || ((x>=29 && x<=31) && (y==nameY+14 || y==nameY+10)) || ((x==32) && (y>=nameY+11 && y<=nameY+13)) || (x==30 && y==nameY+15) || (x==31 && y==nameY+16) || (x==32 && y==nameY+17))
394
+ reg_video_map[y * 40 + x] = 4;
395
+ }
396
+ }
397
+ // Lives
398
+ if(numLives==3){
399
+ DisplayHeart(5,21,3);
400
+ DisplayHeart(15,21,3);
401
+ DisplayHeart(25,21,3);
402
+ }
403
+
404
+ if(numLives==2){
405
+ DisplayHeart(5,21,3);
406
+ DisplayHeart(15,21,3);
407
+ DisplayHeart(25,21,9);
408
+ }
409
+
410
+ if(numLives==1){
411
+ DisplayHeart(5,21,3);
412
+ DisplayHeart(15,21,9);
413
+ DisplayHeart(25,21,9);
414
+ }
415
+ }
416
+ /*
417
+ * brief displays THE END screen
418
+ * return void
419
+ */
420
+ void DisplayTheEndScreen(void)
421
+ {
422
+ uint8_t nameY = 8;
423
+ for (uint8_t y = 0; y < 23; y++)
424
+ {
425
+ for (uint8_t x = 0; x < 40; x++) // Board Boundary
426
+ {
427
+ reg_video_map[y * 40 + x] = 0;
428
+
429
+ // T
430
+ if ((y == nameY && (x >= 5 && x <= 7)) || (x == 6 && (y >= nameY && y <= nameY + 4)))
431
+ reg_video_map[y * 40 + x] = 3;
432
+
433
+ // H
434
+ if ((y == nameY + 2 && (x >= 9 && x <= 11)) || ((x == 9 || x == 11) && (y >= nameY && y <= nameY + 4)))
435
+ reg_video_map[y * 40 + x] = 3;
436
+
437
+ // E
438
+ if (((y == nameY || y == nameY + 4) && (x >= 13 && x <= 15)) || (x == 13 && (y >= nameY && y <= nameY + 4)) || (y == nameY + 2 && (x >= 13 && x <= 14)))
439
+ reg_video_map[y * 40 + x] = 3;
440
+
441
+ // E
442
+ if (((y == nameY || y == nameY + 4) && (x >= 20 && x <= 22)) || (x == 20 && (y >= nameY && y <= nameY + 4)) || (y == nameY + 2 && (x >= 20 && x <= 21)))
443
+ reg_video_map[y * 40 + x] = 3;
444
+
445
+ // N
446
+ if ((y == nameY + 2 && x == 25) || (y == nameY + 3 && x == 26) || ((x == 24 || x == 27) && (y >= nameY && y <= nameY + 4)))
447
+ reg_video_map[y * 40 + x] = 3;
448
+
449
+ // D
450
+ if ((x == 31 && (y >= nameY + 1 && y <= nameY + 3)) || ((y == nameY || y == nameY + 4) && (x >= 29 && x <= 30)) || (x == 29 && (y >= nameY && y <= nameY + 4)))
451
+ reg_video_map[y * 40 + x] = 3;
452
+
453
+ // !
454
+ if ((x == 33 && (y >= nameY && y <= nameY + 2)) || (x == 33 && y == nameY + 4))
455
+ reg_video_map[y * 40 + x] = 3;
456
+ }
457
+ }
458
+ }
459
+
460
+ /*
461
+ * brief defines all characters that can be used
462
+ * return void
463
+ */
464
+ void CharactersInit() {
465
+ uint32_t pixel = 0x00000FFF;
466
+ for(uint8_t z = 0; z < 16; z++)
467
+ {
468
+ for(uint8_t y = 0; y < 16; y++)
469
+ {
470
+ for(uint8_t x = 0; x < 16; x++)
471
+ {
472
+ if(z == 0) // color black
473
+ {
474
+ if(y == 0 || y == 1) pixel = 0x00000222;
475
+ else if (x == 14 || x == 15) pixel = 0x00000111;
476
+ else pixel = 0x00000000;
477
+ }
478
+ else if(z == 1) // color green
479
+ {
480
+ if(y == 0 || y == 1) pixel = 0x00000080;
481
+ else if (x == 14 || x == 15) pixel = 0x00000080;
482
+ else pixel = 0x000008B4;
483
+ }
484
+ else if(z == 2) // color blue
485
+ {
486
+ if(y == 0 || y == 1) pixel = 0x0000000B;
487
+ else if (x == 14 || x == 15) pixel = 0x0000000B;
488
+ else pixel = 0x0000009F;
489
+ }
490
+ else if(z == 3) // color red
491
+ {
492
+ if(y == 0 || y == 1) pixel = 0x00000A00;
493
+ else if (x == 14 || x == 15) pixel = 0x00000B00;
494
+ else pixel = 0x00000F00;
495
+ }
496
+ else if(z == 4) // color yellow
497
+ {
498
+ if(y == 0 || y == 1) pixel = 0x00000FD8;
499
+ else if (x == 14 || x == 15) pixel = 0x00000FD4;
500
+ else pixel = 0x00000FD2;
501
+ }
502
+ else if(z == 5) // color purple
503
+ {
504
+ if(y == 0 || y == 1) pixel = 0x00000075D;
505
+ else if (x == 14 || x == 15) pixel = 0x00000074D;
506
+ else pixel = 0x00000070D;
507
+ }
508
+ else if(z == 6) // color pink
509
+ {
510
+ if(y == 0 || y == 1) pixel = 0x00000FAF;
511
+ else if (x == 14 || x == 15) pixel = 0x00000F6F;
512
+ else pixel = 0x00000F0F;
513
+ }
514
+ else if(z == 7) // color orange
515
+ {
516
+ if(y == 0 || y == 1) pixel = 0x00000FB0;
517
+ else if (x == 14 || x == 15) pixel = 0x00000F90;
518
+ else pixel = 0x00000F63;
519
+ }
520
+ else if(z == 8) // not used
521
+ {
522
+ pixel = 0x000000A0;
523
+ }
524
+ else if(z == 9) // color gray
525
+ {
526
+ if (x == 14 || x == 15) pixel = 0x00000CCC;
527
+ else if(y == 0 || y == 1) pixel = 0x00000111;
528
+ else pixel = 0x00000AAA;
529
+ }
530
+ else if(z == 10) // color light blue
531
+ {
532
+ if(y == 0 || y == 1) pixel = 0x0000000B;
533
+ else if (x == 14 || x == 15) pixel = 0x0000000B;
534
+ else pixel = 0x00000007;
535
+ }
536
+ else if(z == 11) // GateMate blue
537
+ {
538
+ if(y == 0 || y == 1) pixel = 0x0000000B;
539
+ else if (x == 14 || x == 15) pixel = 0x0000000B;
540
+ else pixel = 0x0000006C;
541
+ }
542
+ else if(z == 12) // not used
543
+ {
544
+ // Yellow pixels (color FD2)
545
+ if ((x == 2 && y == 0) || (x == 7 && y == 0) || (x == 8 && y == 0) ||
546
+ (x == 13 && y == 0) || (x == 1 && y == 1) || (x == 6 && y == 1) ||
547
+ (x == 9 && y == 1) || (x == 14 && y == 1) || (x == 0 && y == 2) ||
548
+ (x == 5 && y == 2) || (x == 10 && y == 2) || (x == 15 && y == 2) ||
549
+ (x == 2 && y == 3) || (x == 3 && y == 3) || (x == 4 && y == 3) ||
550
+ (x == 11 && y == 3) || (x == 12 && y == 3) || (x == 13 && y == 3) ||
551
+ (x == 2 && y == 4) || (x == 13 && y == 4) || (x == 2 && y == 5) ||
552
+ (x == 13 && y == 5) || (x == 1 && y == 6) || (x == 14 && y == 6) ||
553
+ (x == 0 && y == 7) || (x == 15 && y == 7) || (x == 1 && y == 8) ||
554
+ (x == 14 && y == 8) || (x == 2 && y == 9) || (x == 13 && y == 9) ||
555
+ (x == 2 && y == 10) || (x == 13 && y == 10) || (x == 2 && y == 11) ||
556
+ (x == 3 && y == 11) || (x == 4 && y == 11) || (x == 11 && y == 11) ||
557
+ (x == 12 && y == 11) || (x == 13 && y == 11) || (x == 5 && y == 12) ||
558
+ (x == 10 && y == 12) || (x == 0 && y == 13) || (x == 6 && y == 13) ||
559
+ (x == 9 && y == 13) || (x == 15 && y == 13) || (x == 1 && y == 14) ||
560
+ (x == 7 && y == 14) || (x == 8 && y == 14) || (x == 14 && y == 14) ||
561
+ (x == 2 && y == 15) || (x == 3 && y == 15) || (x == 4 && y == 15) ||
562
+ (x == 5 && y == 15) || (x == 6 && y == 15) || (x == 7 && y == 15) ||
563
+ (x == 8 && y == 15) || (x == 9 && y == 15) || (x == 10 && y == 15) ||
564
+ (x == 11 && y == 15) || (x == 12 && y == 15) || (x == 13 && y == 15))
565
+ {
566
+ pixel = 0x00000FD2; // Yellow color (FD2)
567
+ }
568
+ // White pixels
569
+ else
570
+ {
571
+ pixel = 0xFFFFFFFF; // White color
572
+ }
573
+ }
574
+ else if(z == 13) // not used
575
+ {
576
+ pixel = 0x00000A0A;
577
+ }
578
+ else if(z == 14) // not used
579
+ {
580
+ pixel = 0x00000FFF;
581
+ }
582
+ else
583
+ {
584
+ pixel = 0x00000000;
585
+ }
586
+ reg_video_char[z * 256 + y * 16 + x] = pixel;
587
+ }
588
+ }
589
+ }
590
+ }
591
+
592
+ /*
593
+ * brief handles the rotation of the piece
594
+ * return index of the rotated piece
595
+ */
596
+ int Rotate(int x, int y, int r)
597
+ {
598
+ int pi = 0;
599
+ switch (r % 4)
600
+ {
601
+ case 0: // 0 degrees // 0 1 2 3
602
+ pi = y * 4 + x; // 4 5 6 7
603
+ break; // 8 9 10 11
604
+ //12 13 14 15
605
+
606
+ case 1: // 90 degrees //12 8 4 0
607
+ pi = 12 + y - (x * 4); //13 9 5 1
608
+ break; //14 10 6 2
609
+ //15 11 7 3
610
+
611
+ case 2: // 180 degrees //15 14 13 12
612
+ pi = 15 - (y * 4) - x; //11 10 9 8
613
+ break; // 7 6 5 4
614
+ // 3 2 1 0
615
+
616
+ case 3: // 270 degrees // 3 7 11 15
617
+ pi = 3 - y + (x * 4); // 2 6 10 14
618
+ break; // 1 5 9 13
619
+ } // 0 4 8 12
620
+
621
+ return pi;
622
+ }
623
+
624
+ /*
625
+ * brief checks if the piece can be moved to a specified position
626
+ * return true if the piece can fit and false otherwise
627
+ */
628
+ bool DoesPieceFit(int tetrominosIndex, int nRotation, int nPosX, int nPosY)
629
+ {
630
+ // All Field cells >0 are occupied
631
+ for (int x = 0; x < 4; x++)
632
+ for (int y = 0; y < 4; y++)
633
+ {
634
+ // Get index into piece
635
+ int pi = Rotate(x, y, nRotation);
636
+
637
+ // Get index into field
638
+ int fi = (nPosY + y) * fieldWidth + (nPosX + x);
639
+
640
+ // Check that test is in bounds. Note out of bounds does
641
+ // not necessarily mean a fail, as the long vertical piece
642
+ // can have cells that lie outside the boundary, so we'll
643
+ // just ignore them
644
+ if (nPosX + x >= 0 && nPosX + x < fieldWidth)
645
+ {
646
+ if (nPosY + y >= 0 && nPosY + y < fieldHeight)
647
+ {
648
+ // In Bounds so do collision check
649
+ if ((tetrominoes[tetrominosIndex][pi] != 0 && field[fi] != 0) /* || (tetrominoes[ntetrominoes][pi] != 0 && (nPosY+y)==0) */) // dodali smo || ....
650
+ return false; // fail on first hit
651
+ }
652
+ }
653
+ }
654
+
655
+ return true;
656
+ }
657
+
658
+ /*
659
+ * brief displays a digit on specified location
660
+ * return void
661
+ */
662
+ void DrawDigit(int number, int startX, int startY)
663
+ {
664
+ for (uint8_t y = startY; y < startY + 5; y++)
665
+ {
666
+ for (uint8_t x = startX; x < startX + 3; x++)
667
+ {
668
+ switch (number)
669
+ {
670
+ case 0:
671
+ if (x == startX || x == startX + 2 || y == startY || y == startY + 4)
672
+ field[y * fieldWidth + x] = 0;
673
+ else
674
+ field[y * fieldWidth + x] = 9;
675
+ break;
676
+ case 1:
677
+ if (x == startX + 2 || y == startY + 1)
678
+ field[y * fieldWidth + x] = 0;
679
+ else
680
+ field[y * fieldWidth + x] = 9;
681
+ break;
682
+ case 2:
683
+ if (y == startY || y == startY + 2 || y == startY + 4 || (y == startY + 1 && x == startX + 2) || (y == startY + 3 && x == startX))
684
+ field[y * fieldWidth + x] = 0;
685
+ else
686
+ field[y * fieldWidth + x] = 9;
687
+ break;
688
+ case 3:
689
+ if (x == startX + 2 || y == startY || y == startY + 2 ||y == startY + 4)
690
+ field[y * fieldWidth + x] = 0;
691
+ else
692
+ field[y * fieldWidth + x] = 9;
693
+ break;
694
+ case 4:
695
+ if (x == startX + 2 || y == startY + 2 || (y <= startY + 2 && x == startX))
696
+ field[y * fieldWidth + x] = 0;
697
+ else
698
+ field[y * fieldWidth + x] = 9;
699
+ break;
700
+ case 5:
701
+ if (y == startY || y == startY + 2 || y == startY + 4 || (y == startY + 1 && x == startX) || (y == startY + 3 && x == startX + 2))
702
+ field[y * fieldWidth + x] = 0;
703
+ else
704
+ field[y * fieldWidth + x] = 9;
705
+ break;
706
+ case 6:
707
+ if (x == startX || y == startY || y == startY + 2 || y == startY + 4 || (y == startY + 3 && x == startX + 2))
708
+ field[y * fieldWidth + x] = 0;
709
+ else
710
+ field[y * fieldWidth + x] = 9;
711
+ break;
712
+ case 7:
713
+ if (x == startX + 2 || y == startY)
714
+ field[y * fieldWidth + x] = 0;
715
+ else
716
+ field[y * fieldWidth + x] = 9;
717
+ break;
718
+ case 8:
719
+ if (x == startX || x == startX + 2 || y == startY || y == startY + 2 || y == startY + 4)
720
+ field[y * fieldWidth + x] = 0;
721
+ else
722
+ field[y * fieldWidth + x] = 9;
723
+ break;
724
+ case 9:
725
+ if (x == startX + 2 || y == startY || y == startY + 2 || y == startY + 4 || (y == startY + 1 && x == startX))
726
+ field[y * fieldWidth + x] = 0;
727
+ else
728
+ field[y * fieldWidth + x] = 9;
729
+ break;
730
+ default:
731
+ break;
732
+ }
733
+ }
734
+ }
735
+ }
736
+
737
+ /*
738
+ * brief displays the current player score
739
+ * return void
740
+ */
741
+ void DisplayScore(int score, int startX, int startY)
742
+ {
743
+ int digits[4] = {0,0,0,0};
744
+ int i = 0;
745
+ while (score != 0)
746
+ {
747
+ digits[i++] = score % 10;
748
+ score /= 10;
749
+ }
750
+
751
+ for (i = 3; i >= 0; i--)
752
+ {
753
+ DrawDigit(digits[i], startX + (3 - i)*4, startY);
754
+ }
755
+ }
756
+
757
+ /*
758
+ * brief displays the word score on the screen
759
+ * return void
760
+ */
761
+ void WriteScore(int score)
762
+ {
763
+ for (uint8_t y = 24; y < 29; y++) {
764
+ for (uint8_t x = 3; x < 21; x++) {
765
+ if (x == 3 || x == 4) // letter S
766
+ {
767
+ if (y == 24 || y == 26 || y == 28 || (x == 3 && y == 25) || (x == 4 && y == 27))
768
+ field[y * fieldWidth + x] = 0;
769
+ else
770
+ field[y * fieldWidth + x] = 9;
771
+ }
772
+ else if (x == 6 || x == 7) // letter C
773
+ {
774
+ if (x == 6 || y == 24 || y == 28)
775
+ field[y * fieldWidth + x] = 0;
776
+ else
777
+ field[y * fieldWidth + x] = 9;
778
+ }
779
+ else if (x == 9 || x == 10 || x == 11) // letter O
780
+ {
781
+ if (x == 9 || x == 11 || y == 24 || y == 28)
782
+ field[y * fieldWidth + x] = 0;
783
+ else
784
+ field[y * fieldWidth + x] = 9;
785
+ }
786
+ else if (x == 13 || x == 14 || x == 15) // letter R
787
+ {
788
+ if (x == 13 || (x == 14 && (y == 24 || y == 26)) || (x == 15 && (y == 25 || y > 26)))
789
+ field[y * fieldWidth + x] = 0;
790
+ else
791
+ field[y * fieldWidth + x] = 9;
792
+ }
793
+ else if (x == 17 || x == 18) // letter E
794
+ {
795
+ if (x == 17 || (x == 18 && y % 2 == 0))
796
+ field[y * fieldWidth + x] = 0;
797
+ else
798
+ field[y * fieldWidth + x] = 9;
799
+ }
800
+ else if (x == 20) // colon
801
+ {
802
+ if (y == 25 || y == 27)
803
+ field[y * fieldWidth + x] = 0;
804
+ else
805
+ field[y * fieldWidth + x] = 9;
806
+ }
807
+ }
808
+ }
809
+
810
+ DisplayScore(score, 22, 24);
811
+ }
812
+ /*
813
+ * brief creating the initial field
814
+ * return void
815
+ */
816
+ void FieldInitialization(){
817
+
818
+ for (uint8_t y = 0; y < fieldHeight; y++)
819
+ {
820
+ for (uint8_t x = 0; x < fieldWidth; x++)
821
+ {
822
+ field[y * fieldWidth + x] = (y == 0 ||
823
+ y >= fieldHeight - 7 ||
824
+ x + 1 == fieldWidth / 2 ||
825
+ x == fieldWidth / 2 ) ? 9u : 0u;
826
+ }
827
+ }
828
+ }
829
+
830
+ /*
831
+ * brief delay function, u32_delay = 40000 -> approx. 5 seconds
832
+ * return void
833
+ */
834
+ static inline void _delay(uint32_t u32_delay)
835
+ {
836
+ uint16_t local = 0;
837
+ for (uint32_t i = 0u; i<u32_delay; i++)
838
+ {
839
+ print("_delay called");
840
+ if (i % 2 == 0) local++;
841
+ }
842
+ }
843
+ /*
844
+ * brief generates a 32-bit random number using XORSHIFT algorithm
845
+ * param state: Pointer to the state variable for the random number generator
846
+ * return unsigned int: The generated random number.
847
+ */
848
+ unsigned int xorshift32(unsigned int *state) {
849
+ unsigned int x = *state;
850
+ x ^= x << 13;
851
+ x ^= x >> 17;
852
+ x ^= x << 5;
853
+ *state = x;
854
+ return x;
855
+ }
856
+ /*
857
+ * brief generates a random binary number (0 or 1)
858
+ * return int: The generated random binary number (0 or 1)
859
+ */
860
+ int generateRandomBinary() {
861
+ static unsigned int state = 123456789;
862
+ return xorshift32(&state) % 2;
863
+ }
864
+ /*
865
+ * brief generates a random number within the specified range [min, max]
866
+ * param min: The minimum value of the range
867
+ * param max: The maximum value of the range
868
+ * return int: The generated random number within the range [min, max]
869
+ */
870
+ int generateRandomNumber(int min, int max) {
871
+ static unsigned int state = 123456789;
872
+ unsigned int range = max - min + 1;
873
+ unsigned int randomValue = xorshift32(&state) % range + min;
874
+ return randomValue;
875
+ }
876
+
877
+
878
+ void main()
879
+ {
880
+ reg_uart_clkdiv = 217;
881
+ print("TetriSaraj!\n");
882
+
883
+ bool rightButton = false, downButton = false, centerButton = false, upButton = false, leftButton = false;
884
+
885
+ reg_gpio = 0x0;
886
+
887
+ CharactersInit();
888
+ DisplayProjectName();
889
+ _delay(3000); // 15000
890
+
891
+ DisplayCompanyName();
892
+ _delay(3000);
893
+
894
+ DisplayGameName();
895
+ _delay(3000);
896
+
897
+ FieldInitialization();
898
+
899
+ setScreenColor(12);
900
+
901
+ DisplayHeart(5,9,3);
902
+ DisplayHeart(15,9,3);
903
+ DisplayHeart(25,9,3);
904
+ _delay(4000); // 20000
905
+
906
+ // Game Logic
907
+ uint16_t pieceIndex = 0;
908
+ uint8_t pieceRotation = 3;
909
+ uint8_t pieceXCoordinate = 0;
910
+ uint8_t pieceYCoordinate = fieldHeight / 2;
911
+
912
+ uint8_t speed = 15;
913
+ uint8_t gameTicksCount = 0;
914
+ uint8_t numLives=3;
915
+ bool movePiece = false;
916
+ bool rotationFlag = true;
917
+
918
+ uint16_t pieceCount = 0;
919
+ uint16_t score = 0;
920
+
921
+ uint8_t linesXCoordinates[4] = {0, 0, 0, 0};
922
+ uint8_t linesCount = 0;
923
+ bool isGameOver = false;
924
+ bool isTheEnd = false;
925
+ uint8_t previousSide = 0;
926
+ bool hasScoreChanged = false;
927
+
928
+ uint8_t randomSideGenerator = 0; // left - 0, right - 1
929
+
930
+ WriteScore(score);
931
+
932
+ while (1) {
933
+
934
+ if(isGameOver && numLives==1){
935
+ isTheEnd=true;
936
+ isGameOver=false;
937
+ }
938
+
939
+ if (isGameOver)
940
+ {
941
+ numLives=numLives-1;
942
+ DisplayGameOverScreen(numLives);
943
+
944
+ _delay(4000); // 18000
945
+
946
+ for (uint8_t y = 0; y < fieldHeight; y++)
947
+ {
948
+ for (uint8_t x = 0; x < fieldWidth; x++)
949
+ {
950
+ field[y * fieldWidth + x] = (y == 0 ||
951
+ y >= fieldHeight - 7 ||
952
+ x + 1 == fieldWidth / 2 ||
953
+ x == fieldWidth / 2 ) ? 9u : 0u;
954
+ }
955
+ }
956
+ isGameOver=false;
957
+ WriteScore(score);
958
+ }
959
+
960
+ if (isTheEnd)
961
+ {
962
+ DisplayTheEndScreen();
963
+
964
+ while (!(buttons & BUTTON_CENTER))
965
+ {
966
+ // Press center button to restart the game
967
+ GetButtonStates();
968
+ }
969
+
970
+ for (uint8_t y = 0; y < fieldHeight; y++)
971
+ {
972
+ for (uint8_t x = 0; x < fieldWidth; x++)
973
+ {
974
+ field[y * fieldWidth + x] = (y == 0 ||
975
+ y >= fieldHeight - 7 ||
976
+ x + 1 == fieldWidth / 2 ||
977
+ x == fieldWidth / 2 ) ? 9u : 0u;
978
+ }
979
+ }
980
+ isTheEnd=false;
981
+
982
+ score=0;
983
+ speed=15;
984
+
985
+ WriteScore(score);
986
+ }
987
+ delay--;
988
+
989
+ GetButtonStates();
990
+
991
+ if (buttons & BUTTON_UP)
992
+ {
993
+ upButton = true;
994
+ print("BUTTON_UP\n");
995
+ }
996
+ if (buttons & BUTTON_DOWN)
997
+ {
998
+ downButton = true;
999
+ print("BUTTON_DOWN\n");
1000
+ }
1001
+ if (buttons & BUTTON_RIGHT)
1002
+ {
1003
+ rightButton = true;
1004
+ print("BUTTON_RIGHT\n");
1005
+ }
1006
+ if (buttons & BUTTON_LEFT)
1007
+ {
1008
+ leftButton = true;
1009
+ print("BUTTON_LEFT\n");
1010
+ }
1011
+ if (buttons & BUTTON_CENTER)
1012
+ {
1013
+ centerButton = true;
1014
+ print("BUTTON_CENTER\n");
1015
+ }
1016
+ reg_gpio = 0x00000100 | buttons; // first 9 leds
1017
+
1018
+
1019
+ // Game Logic
1020
+ if (delay == 0)
1021
+ {
1022
+ delay = DELAY;
1023
+ gameTicksCount++;
1024
+ movePiece = (gameTicksCount == speed);
1025
+
1026
+
1027
+ // Player input handling
1028
+ if (!randomSideGenerator) // left part of the screen
1029
+ {
1030
+ pieceYCoordinate += (downButton && DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate, pieceYCoordinate + 1)) ? 1 : 0;
1031
+ pieceYCoordinate -= (upButton && DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate, pieceYCoordinate - 1)) ? 1 : 0;
1032
+ pieceXCoordinate += (rightButton && DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate + 1, pieceYCoordinate)) ? 1 : 0;
1033
+ }
1034
+ else // right part of the screen
1035
+ {
1036
+ pieceYCoordinate -= (upButton && DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate, pieceYCoordinate - 1)) ? 1 : 0;
1037
+ pieceYCoordinate += (downButton && DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate, pieceYCoordinate + 1)) ? 1 : 0;
1038
+ pieceXCoordinate -= (leftButton && DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate - 1, pieceYCoordinate)) ? 1 : 0;
1039
+ }
1040
+
1041
+ if (centerButton)
1042
+ {
1043
+ pieceRotation += (rotationFlag && DoesPieceFit(pieceIndex, pieceRotation + 1, pieceXCoordinate, pieceYCoordinate)) ? 1 : 0;
1044
+ rotationFlag = false;
1045
+ }
1046
+ else
1047
+ rotationFlag = true;
1048
+
1049
+ // Move the piece "down" the playfield if it's time
1050
+ if (movePiece)
1051
+ {
1052
+ // Update difficulty every 50 pieces
1053
+ gameTicksCount = 0;
1054
+ pieceCount++;
1055
+ if (pieceCount % 50 == 0)
1056
+ if (speed >= 10) speed--;
1057
+
1058
+ // Test if piece can be moved down
1059
+ if (DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate + 1, pieceYCoordinate) && !randomSideGenerator)
1060
+ {
1061
+ pieceXCoordinate++;
1062
+ }
1063
+ else if (DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate - 1, pieceYCoordinate) && randomSideGenerator)
1064
+ {
1065
+ pieceXCoordinate--;
1066
+ }
1067
+ else
1068
+ {
1069
+ // Lock the piece in place
1070
+ for (int x = 0; x < 4; x++)
1071
+ {
1072
+ for (int y = 0; y < 4; y++)
1073
+ {
1074
+ if (tetrominoes[pieceIndex][Rotate(x, y, pieceRotation)] != 0)
1075
+ {
1076
+ field[(pieceYCoordinate + y) * fieldWidth + (pieceXCoordinate + x)] = pieceIndex + 1;
1077
+ }
1078
+ }
1079
+ }
1080
+
1081
+ // Check if any lines formed
1082
+ for (int x = 0; x < 4; x++)
1083
+ {
1084
+ bool bLine = true;
1085
+ for (int y = 1; y < fieldHeight - 7; y++)
1086
+ {
1087
+ if (field[(pieceXCoordinate + x) + fieldWidth * y] == 0 || field[(pieceXCoordinate + x) + fieldWidth * y] == 9u)
1088
+ {
1089
+ bLine = false;
1090
+ break;
1091
+ }
1092
+ }
1093
+
1094
+ if (bLine)
1095
+ {
1096
+ // Remove the line
1097
+ for (int y = 1; y < fieldHeight - 7; y++)
1098
+ {
1099
+ field[(pieceXCoordinate + x) + fieldWidth * y] = 0;
1100
+ }
1101
+
1102
+ // Remember the coordinates of the removed line
1103
+ linesXCoordinates[linesCount] = pieceXCoordinate + x;
1104
+ linesCount++;
1105
+ }
1106
+ }
1107
+ previousSide = randomSideGenerator;
1108
+
1109
+ // Score handling
1110
+ score += 1;
1111
+ if (linesCount != 0) score += (1 << linesCount) * 20;
1112
+ hasScoreChanged = true;
1113
+
1114
+ // Generate new piece
1115
+ pieceYCoordinate = generateRandomNumber(2,19);
1116
+ // Generate new side
1117
+ randomSideGenerator= generateRandomBinary();
1118
+
1119
+ if (!randomSideGenerator)
1120
+ {
1121
+ pieceRotation = 3;
1122
+ pieceXCoordinate = 0;
1123
+ }
1124
+ else
1125
+ {
1126
+ pieceRotation = 3;
1127
+ pieceXCoordinate = fieldWidth - 4;
1128
+ }
1129
+
1130
+ pieceIndex = pieceCount % 7;
1131
+
1132
+ // Game is over if the piece doesn't fit at the beginning
1133
+ isGameOver = !DoesPieceFit(pieceIndex, pieceRotation, pieceXCoordinate, pieceYCoordinate);
1134
+ }
1135
+ }
1136
+
1137
+ // Rendering part
1138
+ if (hasScoreChanged)
1139
+ {
1140
+ hasScoreChanged = false;
1141
+ DisplayScore(score, 22, 24);
1142
+ }
1143
+
1144
+ // Display the current field state
1145
+ for (int y = 0; y < fieldHeight; y++)
1146
+ {
1147
+ for (int x = 0; x < fieldWidth; x++)
1148
+ {
1149
+ reg_video_map[y * fieldWidth + x] = field[y * fieldWidth + x];
1150
+ }
1151
+ }
1152
+
1153
+ // Display the current piece on the field
1154
+ for (int x = 0; x < 4; x++)
1155
+ {
1156
+ for (int y = 0; y < 4; y++)
1157
+ {
1158
+ if (tetrominoes[pieceIndex][Rotate(x, y, pieceRotation)] != 0)
1159
+ {
1160
+ reg_video_map[(pieceYCoordinate + y) * fieldWidth + (pieceXCoordinate + x)] = pieceIndex + 1;
1161
+ }
1162
+ }
1163
+ }
1164
+
1165
+ // Handle the lines removal
1166
+ if (linesCount != 0)
1167
+ {
1168
+ if (previousSide == 0)
1169
+ {
1170
+ for (uint8_t v = 0; v < linesCount; v++)
1171
+ {
1172
+ for (uint8_t x = linesXCoordinates[v]; x > 0; x--)
1173
+ {
1174
+ for (uint8_t y = 1; y < fieldHeight - 7; y++)
1175
+ {
1176
+ field[x + fieldWidth * y] = field[x - 1 + fieldWidth * y];
1177
+ }
1178
+ }
1179
+ }
1180
+ }
1181
+ else
1182
+ {
1183
+ for (uint8_t v = linesCount; v > 0; v--)
1184
+ {
1185
+ for (uint8_t x = linesXCoordinates[v - 1]; x < fieldWidth - 1; x++)
1186
+ {
1187
+ for (uint8_t y = 1; y < fieldHeight - 7; y++)
1188
+ {
1189
+ field[x + fieldWidth * y] = field[x + 1 + fieldWidth * y];
1190
+ }
1191
+ }
1192
+ }
1193
+
1194
+ }
1195
+
1196
+ // clear the coordinates array
1197
+ linesXCoordinates[0] = 0;
1198
+ linesXCoordinates[1] = 0;
1199
+ linesXCoordinates[2] = 0;
1200
+ linesXCoordinates[3] = 0;
1201
+ linesCount = 0;
1202
+ }
1203
+
1204
+ rightButton = false;
1205
+ downButton = false;
1206
+ centerButton = false;
1207
+ upButton = false;
1208
+ leftButton = false;
1209
+ }
1210
+ }
1211
+ }
1212
+
chili-chips-ba_openCologne/5.TetriSaraj/README.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TetriSaraj on GateMate
2
+
3
+ ## Introduction
4
+
5
+ This project is a demonstration of a complex digital hardware/software system.
6
+
7
+ The hardware consists of a custom SoC with RISC-V CPU and our special _Video Controller_ that operates with _Mega Characters (MC)_, which are a close kin to the infamous _"Sprites"_.
8
+
9
+ The software is bare-metal, w/o an OS, and implements a well-known, classic game, now rotated by 90 degrees and mirror-duplicated.
10
+
11
+ The whole thing is called _TetriSaraj_, and essentially a port:
12
+ - from Digilent _Basys3_ (Artix7-35T) with openXC7 tools
13
+ - to Olimex _GateMate1-EVB_ board with CologneChip tools.
14
+
15
+ For the complete design detail (game logic, system block diagram, memory mapping etc.), please visit the original project repo:
16
+ - https://github.com/chili-chips-ba/openXC7-TetriSaraj
17
+
18
+ ## Surprise, surprise...
19
+
20
+ Other than the expected changes related to constraints, pinouts, makefile etc., the operating clock frequency emerged as the main (and indeed unexpected) difference between these two designs.
21
+
22
+ The original TetriSaraj ran on Artix-7 at `100MHz` w/o problems, even when built with openXC7 PNR, as opposed to Xilinx-proprietary Vivado. That was however far from possible on GateMate FPGA, where the `Fmax for the original design was 16MHz`, and for a reduced/optimized version barely reached 31 MHz, even at the highest VDD_CORE setting.
23
+
24
+ With VGA sub-system needing at least 25MHz, we decided to scale down the clock of the entire (already reduced) system to the `25MHz`. This then caused multiple timing issues in the video generation section (such as within _vga_controller.v_ and _top.v_), calling for significant timing-driven adaptations, in some instances even an overhaul.
25
+
26
+ ## Hardware setup
27
+
28
+ Since Olimex comes with only 1 user button, we had to plug-in _SimpleIO Extension Board_ that brings additional buttons.
29
+
30
+ The game needs 5 buttons:
31
+ - 4 arrows for the direction of movement
32
+ - plus 1 for the rotation.
33
+
34
+ The complete setup is shown below:
35
+
36
+ <img width=400 src="https://github.com/user-attachments/assets/ae35220d-a01d-4727-a8b0-39b207c47629">
37
+
38
+ In addition to the _GateMateA1-EVB_, you will also need:
39
+ - monitor with VGA port connected to it.
40
+ - _SimpleIO Extension Board_ or, yet better, the new _**joyIO**_ card
41
+
42
+ <img width=400 src="https://github.com/chili-chips-ba/openCologne/blob/main/0.doc/Intergalaktik/joyIO.png">
43
+
44
+ ## The Gameplay
45
+
46
+ Our progam starts with a small, but full-custom Splash 😄:
47
+
48
+ <img width=400 src="https://github.com/user-attachments/assets/62c2cd11-c261-4846-bbc2-cd59c46a0b8e">
49
+
50
+ But, you start with three lives, that is three hearts:
51
+
52
+ <img width=400 src="https://github.com/user-attachments/assets/b3558a6a-6a9b-4704-ad9c-fcdc21c5b5f6">
53
+
54
+ As you're playin', you can earn more hearts, or lose them.
55
+ The more you earn, the harder we make it for you to play and win.
56
+
57
+ <img width=400 src="https://github.com/user-attachments/assets/8e191741-83f5-4792-80df-5bba1fc767ef">
58
+
59
+ Sorry, it's _"Game Over"_ when you lose your last heart.
60
+
61
+ <img width=400 src="https://github.com/user-attachments/assets/cb28b561-fd35-4a46-918c-065b71d953db">
62
+
63
+ Time to try again...
64
+
65
+ <img width=400 src="https://github.com/user-attachments/assets/8e982547-ae1c-4c15-9c74-409e79cbc810">
66
+
67
+ ## Demo stream
68
+
69
+ https://github.com/user-attachments/assets/12611cf4-5f7c-42ba-97fa-0026c773a5dd
70
+
71
+ ## How to build TetriSaraj for GateMate?!
72
+
73
+ To synthesize and run the design locally, one must install the _CologneChip toolchain_ and adapt the _Makefile_. The whole process is explained in `3.build/Makefile`.
74
+
75
+ ## Our next play shall be audible
76
+
77
+ Stay tuned for the arrival of stereo soundtrack to TetriSaraj play...
78
+
79
+ ## References
80
+ 1) Also available on [Xilinx Artix7](https://github.com/chili-chips-ba/openXC7-TetriSaraj) and [Gowin LittleBee](https://github.com/chili-chips-ba/openXC7-TetriSaraj/tree/main/99.more-boards/0.tang-nano-9k), thanks to [SymbioticEDA](https://www.symbioticeda.com) support
81
+
82
+ 2) Postings and mentions:
83
+ > - [Dec.15, 2024](https://www.linkedin.com/feed/update/urn:li:activity:7273353028055769089?commentUrn=urn%3Ali%3Acomment%3A%28activity%3A7273353028055769089%2C7274166171325607936%29&dashCommentUrn=urn%3Ali%3Afsd_comment%3A%287274166171325607936%2Curn%3Ali%3Aactivity%3A7273353028055769089%29)
84
+ > - [Oct.15, 2024](https://www.linkedin.com/posts/chili-chips_tetrisaraj-gatemate-opensource-activity-7252167674741301249-gOgI?utm_source=share&utm_medium=member_desktop)
85
+ > - [Oct.11, 2024](https://www.linkedin.com/feed/update/urn:li:activity:7250565052359921665?commentUrn=urn%3Ali%3Acomment%3A%28activity%3A7250565052359921665%2C7250724417754836992%29&replyUrn=urn%3Ali%3Acomment%3A%28activity%3A7250565052359921665%2C7251814253668544513%29&dashCommentUrn=urn%3Ali%3Afsd_comment%3A%287250724417754836992%2Curn%3Ali%3Aactivity%3A7250565052359921665%29&dashReplyUrn=urn%3Ali%3Afsd_comment%3A%287251814253668544513%2Curn%3Ali%3Aactivity%3A7250565052359921665%29)
86
+ > - [Oct.1, 2024](https://www.linkedin.com/feed/update/urn:li:ugcPost:7246625338787602434?commentUrn=urn%3Ali%3Acomment%3A%28ugcPost%3A7246625338787602434%2C7247337428045209600%29&dashCommentUrn=urn%3Ali%3Afsd_comment%3A%287247337428045209600%2Curn%3Ali%3AugcPost%3A7246625338787602434%29)
87
+ > - [SarajevoMakerFaire 2024](https://sarajevo.makerfaire.com/maker/entry/143)
88
+ > - [May 2023](https://www.linkedin.com/posts/chili-chips_fpga-education-riscv-activity-7076630631165689858-wgK_?utm_source=share&utm_medium=member_desktop)
89
+ > - [April 2023](https://www.linkedin.com/posts/chili-chips_fpga-foss-yosys-activity-7069758169639505920-LRyG?utm_source=share&utm_medium=member_desktop)
90
+ > - and more...
91
+
92
+ <img width=500 src="0.doc/TetriSaraj-joyIO.png">
93
+
94
+ #### End of Document
chili-chips-ba_openCologne/6.PCB.advanced/README.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PCB2 - Advanced (ULX5M-GS)
2
+
3
+ For more, please see:
4
+ - [Extension_Boards_for_Olimex_GateMate repo](https://github.com/intergalaktik/ulx5m-gs)
5
+ - [PCB Request Issues](https://github.com/chili-chips-ba/openCologne/issues?q=label%3A%22PCB+request%22+)
6
+
7
+ ### ---Conceptual Design---
8
+ <p align="center">
9
+ <img width=500 src="0.doc/ulx5m.concept1.jpg">
10
+ <img width=500 src="0.doc/ulx5m.concept2.png">
11
+ </p>
12
+
13
+ ### ---Version1 Design---
14
+
15
+ #### V01 layout
16
+ <p align="center">
17
+ <img width=800 src="0.doc/ulx5m-gs.v01.1.routed.png">
18
+ </p>
19
+
20
+ #### V01 manufactured PCB
21
+ <p align="center">
22
+ <img width=800 src="0.doc/ulx5m-gs.v01.2.barePCB.jpg">
23
+ </p>
24
+
25
+ #### V01 bringup/debug
26
+ <p align="center">
27
+ <img width=800 src="0.doc/ulx5m-gs.v01.3.debug.jpg">
28
+ </p>
29
+
30
+ ### ---Version2 Design---
31
+
32
+ ##### V02 draft for team review
33
+ <p align="center">
34
+ <img width=500 src="0.doc/ulx5m-gs.v02.1.top.jpg">
35
+ <img width=500 src="0.doc/ulx5m-gs.v02.2.bottom.jpg">
36
+ </p>
37
+
38
+ ##### V02 assembled prototype
39
+ <p align="center">
40
+ <img width=800 src="0.doc/ulx5m-gs.v02.3.jpg">
41
+ </p>
42
+
43
+ #### V02 bringup/debug
44
+ [![ULX5M blinks LEDs on its own](0.doc/ulx5m-gs.v02.4.debug.jpg)](https://www.youtube.com/watch?v=LA20pfW7X00 "ULX5M is counting!")
45
+
46
+
47
+ #### V02 mounted on the CM4-BB3 carrier card
48
+ <p align="center">
49
+ <img width=600 src="0.doc/ulx5m-gs.v02.5.with-CM4_BB3.jpg">
50
+ <img width=600 src="0.doc/ulx5m-gs.v02.6.with-CM4_BB3.HDMI.jpg">
51
+ </p>
52
+
53
+ #### V02 mounted on the CM4 "Piunora" carrier card
54
+ <p align="center">
55
+ <img width=600 src="0.doc/ulx5m-gs.v02.7.with-CM4_Piunora.jpg">
56
+ <img width=600 src="0.doc/ulx5m-gs.v02.8.with-CM4_Piunora.HDMI.jpg">
57
+ </p>
58
+
59
+ #### End of Document
chili-chips-ba_openCologne/7.SerDes/1.serdestool_by_gm/README.md ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SerDes App for GateMate
2
+
3
+ ## References
4
+ - Measuring Eye Diagrams on [Rigol MSO5000](https://www.youtube.com/watch?si=vo3GYcDNML9LsX7S&v=JcJbcKl5llo&feature=youtu.be)
5
+
6
+ ## Verifying board setup
7
+
8
+ Using the provided serdestool we can verify that our board setup is functioning correctrly. We can run a loopback test ( `./sedestool --tcloopback `) :
9
+
10
+ ```
11
+ INFO: Found 1 device in JTAG chain.
12
+ INFO: Starting SerDes loopback testcases
13
+
14
+ INFO: Enabling TX PMA Loopback (Mode 0)
15
+ INFO: Configuring SerDes ADPLL
16
+ INFO: SerDes ADPLL frequency / data rate is 625.0 MHz / 1250.0 Mbit/s
17
+ INFO: Disabling SerDes ADPLL
18
+ INFO: Writing SerDes ADPLL divider settings
19
+ INFO: Stopping SerDes ADPLL self-calibration
20
+ INFO: Starting SerDes ADPLL
21
+ INFO: Starting SerDes ADPLL self-calibration
22
+ INFO: SerDes ADPLL locked
23
+ INFO: PFDAC result: max reached: 0, ac_result: 98320, CP: 3
24
+ INFO: ADPLL status: LCK: 1 FTO: 0 FTU: 0 FT: 708 SY: 0 ST: 2
25
+ INFO: Resetting SerDes TX
26
+ INFO: Resetting SerDes RX
27
+ INFO: Sending data (this might take a while) ...
28
+ INFO: Checking 32-Bit comma alignment
29
+ INFO: Resetting SerDes TX
30
+ INFO: Resetting SerDes RX
31
+ INFO: Sending data (this might take a while) ...
32
+ INFO: Checking 16-Bit comma alignment
33
+ INFO: Resetting SerDes TX
34
+ INFO: Resetting SerDes RX
35
+ INFO: Sending data (this might take a while) ...
36
+ INFO: Checking 8-Bit comma alignment
37
+
38
+ INFO: Enabling TX PMA Loopback (Mode 1)
39
+ INFO: Configuring SerDes ADPLL
40
+ INFO: SerDes ADPLL frequency / data rate is 625.0 MHz / 1250.0 Mbit/s
41
+ INFO: Disabling SerDes ADPLL
42
+ INFO: Writing SerDes ADPLL divider settings
43
+ INFO: Stopping SerDes ADPLL self-calibration
44
+ INFO: Starting SerDes ADPLL
45
+ INFO: Starting SerDes ADPLL self-calibration
46
+ INFO: SerDes ADPLL locked
47
+ INFO: PFDAC result: max reached: 0, ac_result: 16, CP: 6
48
+ INFO: ADPLL status: LCK: 1 FTO: 0 FTU: 0 FT: 706 SY: 0 ST: 2
49
+ INFO: Resetting SerDes TX
50
+ INFO: Resetting SerDes RX
51
+ INFO: Sending data (this might take a while) ...
52
+ INFO: Checking 32-Bit comma alignment
53
+ INFO: Resetting SerDes TX
54
+ INFO: Resetting SerDes RX
55
+ INFO: Sending data (this might take a while) ...
56
+ INFO: Checking 16-Bit comma alignment
57
+ INFO: Resetting SerDes TX
58
+ INFO: Resetting SerDes RX
59
+ INFO: Sending data (this might take a while) ...
60
+ INFO: Checking 8-Bit comma alignment
61
+
62
+ INFO: Enabling TX PCS Loopback
63
+ INFO: Configuring SerDes ADPLL
64
+ INFO: SerDes ADPLL frequency / data rate is 625.0 MHz / 1250.0 Mbit/s
65
+ INFO: Disabling SerDes ADPLL
66
+ INFO: Writing SerDes ADPLL divider settings
67
+ INFO: Stopping SerDes ADPLL self-calibration
68
+ INFO: Starting SerDes ADPLL
69
+ INFO: Starting SerDes ADPLL self-calibration
70
+ INFO: SerDes ADPLL locked
71
+ INFO: PFDAC result: max reached: 0, ac_result: 98330, CP: 25
72
+ INFO: ADPLL status: LCK: 1 FTO: 0 FTU: 0 FT: 707 SY: 0 ST: 2
73
+ INFO: Resetting SerDes TX
74
+ INFO: Resetting SerDes RX
75
+ INFO: Sending data (this might take a while) ...
76
+ INFO: Checking 32-Bit comma alignment
77
+ INFO: Resetting SerDes TX
78
+ INFO: Resetting SerDes RX
79
+ INFO: Sending data (this might take a while) ...
80
+ INFO: Checking 16-Bit comma alignment
81
+ INFO: Resetting SerDes TX
82
+ INFO: Resetting SerDes RX
83
+ INFO: Sending data (this might take a while) ...
84
+ INFO: Checking 8-Bit comma alignment
85
+
86
+ ```
87
+ as well as a PRBS test (`./serdestool --tcprbs`):
88
+
89
+
90
+ ```
91
+ INFO: Found 1 device in JTAG chain.
92
+ INFO: Starting SerDes PRBS testcases
93
+ INFO: Configuring SerDes ADPLL
94
+ INFO: SerDes ADPLL frequency / data rate is 625.0 MHz / 1250.0 Mbit/s
95
+ INFO: Disabling SerDes ADPLL
96
+ INFO: Writing SerDes ADPLL divider settings
97
+ INFO: Stopping SerDes ADPLL self-calibration
98
+ INFO: Starting SerDes ADPLL
99
+ INFO: Starting SerDes ADPLL self-calibration
100
+ INFO: SerDes ADPLL locked
101
+ INFO: PFDAC result: max reached: 0, ac_result: 19, CP: 28
102
+ INFO: ADPLL status: LCK: 1 FTO: 0 FTU: 0 FT: 708 SY: 0 ST: 2
103
+ INFO: Resetting SerDes TX
104
+ INFO: Resetting SerDes RX
105
+ INFO: Setting up PRBS-7
106
+ INFO: Sending data (this might take a while) ...
107
+ INFO: 0/10
108
+ INFO: 1/10
109
+ INFO: 2/10
110
+ INFO: 3/10
111
+ INFO: 4/10
112
+ INFO: 5/10
113
+ INFO: 6/10
114
+ INFO: 7/10
115
+ INFO: 8/10
116
+ INFO: 9/10
117
+ INFO: RX_PRBS_LOCKED: 1, RX_PRBS_ERR_CNT: 0
118
+ INFO: Starting error injection
119
+ INFO: RX_PRBS_LOCKED: 1, RX_PRBS_ERR_CNT: 6
120
+ INFO: Setting up PRBS-15
121
+ INFO: Sending data (this might take a while) ...
122
+ INFO: 0/10
123
+ INFO: 1/10
124
+ INFO: 2/10
125
+ INFO: 3/10
126
+ INFO: 4/10
127
+ INFO: 5/10
128
+ INFO: 6/10
129
+ INFO: 7/10
130
+ INFO: 8/10
131
+ INFO: 9/10
132
+ INFO: RX_PRBS_LOCKED: 1, RX_PRBS_ERR_CNT: 0
133
+ INFO: Starting error injection
134
+ INFO: RX_PRBS_LOCKED: 1, RX_PRBS_ERR_CNT: 7
135
+ ```
136
+
137
+ P and N signals of the TX and RX channel are connected as in the following image:
138
+
139
+ <p align="center" width="100%">
140
+ <img width="50%" src="../0.doc/SerDes-Loopback.jpg">
141
+ </p>
142
+
143
+
144
+
145
+ ### End of Document
chili-chips-ba_openCologne/7.SerDes/1.serdestool_by_gm/serdes_lb.v ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `timescale 1ns / 1ps
2
+
3
+
4
+ // # serdestool -- GateMate FPGA SerDes Toolkit
5
+ // #
6
+ // # Permission to use, copy, modify, and/or distribute this software for any
7
+ // # purpose with or without fee is hereby granted, provided that the above
8
+ // # copyright notice and this permission notice appear in all copies.
9
+ // #
10
+ // # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
+ // # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ // # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
+ // # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ // # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ // # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
+ // # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+ // #
18
+ // # Visit https://colognechip.com for more information.
19
+ // #
20
+ // # Copyright (C) 2022 - 2025 Cologne Chip AG <support@colognechip.com>
21
+ // # Authors: Patrick Urban
22
+
23
+ module serdes_lb (
24
+ input pll_rstn_i,
25
+ input trx_rstn_i,
26
+ input ref_clk,
27
+
28
+ input RX_PRBS_CNT_RESET_I,
29
+ input TX_PRBS_FORCE_ERR_I,
30
+
31
+ output [63:0] RX_DATA_O,
32
+ output PLL_CLK_O,
33
+ output RX_CLK_O,
34
+
35
+ output RX_RESET_DONE_O_N, TX_RESET_DONE_O_N,
36
+ output TX_DETECT_RX_PRESENT_O_N, TX_DETECT_RX_DONE_O_N,
37
+ output TX_BUF_ERR_O_N, RX_BUF_ERR_O_N,
38
+ output RX_PRBS_ERR_O_N
39
+ );
40
+
41
+ wire RX_COMMA_DETECT_EN_I = 1'b1;
42
+
43
+ // reset
44
+ reg [8:0] rst_cnt = 0;
45
+ wire rstn = &rst_cnt;
46
+ wire rst = !rstn;
47
+
48
+ always @(posedge ref_clk) begin
49
+ rst_cnt <= rst_cnt + !rstn;
50
+ end
51
+
52
+ wire trx_rst_i = ~trx_rstn_i | rst;
53
+ wire pll_rst_i = ~pll_rstn_i | rst;
54
+
55
+ wire CLK_CORE_PLL_O_N;
56
+
57
+ wire TX_RESET_DONE_O;
58
+ wire RX_RESET_DONE_O;
59
+ assign TX_RESET_DONE_O_N = ~TX_RESET_DONE_O;
60
+ assign RX_RESET_DONE_O_N = ~RX_RESET_DONE_O;
61
+
62
+ wire TX_DETECT_RX_PRESENT_O;
63
+ wire TX_DETECT_RX_DONE_O;
64
+ assign TX_DETECT_RX_PRESENT_O_N = ~TX_DETECT_RX_PRESENT_O;
65
+ assign TX_DETECT_RX_DONE_O_N = ~TX_DETECT_RX_DONE_O;
66
+
67
+ wire RX_PRBS_ERR_O;
68
+ assign RX_PRBS_ERR_O_N = ~RX_PRBS_ERR_O;
69
+
70
+ wire TX_BUF_ERR_O;
71
+ wire RX_BUF_ERR_O;
72
+ assign TX_BUF_ERR_O_N = ~TX_BUF_ERR_O;
73
+ assign RX_BUF_ERR_O_N = ~RX_BUF_ERR_O;
74
+
75
+ wire [63:0] RX_DATA_O;
76
+
77
+ wire RX_EI_EN_O, REGFILE_RDY_O, CLK_CORE_RX_O;
78
+ wire [7:0] RX_CHAR_IS_K_O, RX_CHAR_IS_COMMA_O, RX_NOT_IN_TABLE_O;
79
+ wire [15:0] REGFILE_DO_O;
80
+
81
+ // 8b/10b control bytes
82
+ parameter [27:0] kChar =
83
+ //{8'hxx, 10'h000, 10'h000}; // K28_5
84
+ //{8'h1C, 10'h303, 10'h0FC}; // K28_0
85
+ //{8'h3C, 10'h343, 10'h1FC}; // K28_1
86
+ //{8'h5C, 10'h383, 10'h27C}; // K28_2
87
+ //{8'h7C, 10'h3C3, 10'h2FC}; // K28_3
88
+ //{8'h9C, 10'h443, 10'h37C}; // K28_4
89
+ {8'hBC, 10'h283, 10'h17C}; // K28_5
90
+ //{8'hDC, 10'h4C3, 10'h3FC}; // K28_6
91
+ //{8'hFC, 10'h503, 10'h47C}; // K28_7
92
+ //{8'hFB, 10'h11C, 10'h38C}; // K27_7
93
+ //{8'hFD, 10'h11C, 10'h38C}; // K29_7
94
+ //{8'hFE, 10'h11C, 10'h38C}; // K30_7
95
+
96
+ // ADPLL clock settings
97
+ parameter N1 = 1; // 1/2
98
+ parameter N2 = 2; // 2/3/4/5
99
+ parameter N3 = 3; // 3/4/5
100
+ parameter OUTDIV = 4; // 1/2/4
101
+
102
+ parameter DATAPATH = 80; // 80, 40, 20
103
+
104
+ parameter ENABLE_8B10B = 1'b1;
105
+ parameter ENABLE_COMMADETECT = 1'b1;
106
+
107
+ parameter [2:0] PRBS_SEL =
108
+ 3'b000; // PRBS checker disabled
109
+ //3'b001; // PRBS-7
110
+ //3'b010; // PRBS-15
111
+ //3'b011; // PRBS-23
112
+ //3'b100; // PRBS-31
113
+ //3'b101; // RESERVED
114
+ //3'b110; // 2 UI square wave (TX ONLY)
115
+ //3'b111; // 20/40/80 UI square wave, depending on data path width (TX ONLY)
116
+
117
+ parameter [2:0] LOOPBACK_SEL =
118
+ 3'b000; // normal operation
119
+ //3'b001; // near-end PCS Loopback
120
+ //3'b010; // near-end PMA Loopback
121
+ //3'b011; // reserved
122
+ //3'b100; // far-end PMA Loopback
123
+ //3'b101; // reserved
124
+ //3'b110; // far-end PCS Loopback
125
+ //3'b111; // reserved
126
+
127
+ parameter [1:0] TX_PMA_LOOPBACK =
128
+ 2'b00; // disabled
129
+ //2'b01; // loopback from TX driver
130
+ //2'b10; // loopback from TX pads
131
+
132
+ parameter [1:0] DATAPATH_SEL = {
133
+ (DATAPATH == 80) ? 2'b11 : (DATAPATH == 40) ? 2'b01 : (DATAPATH == 20) ? 2'b00 : 2'bx
134
+ }; // default: 2'h3
135
+
136
+ parameter [5:0] PLL_FCNTRL = {
137
+ DATAPATH == 80 ? 6'h3A : (DATAPATH == 40 ? 6'h3A : (DATAPATH == 20 ? 6'd26 : 6'bx))
138
+ }; // default: 6'h3A = 58 ^= 20;
139
+
140
+ parameter [5:0] PLL_MAIN_DIVSEL = {
141
+ 1'b0, // PLL_MAINDIV[5]: not used
142
+ N3 == 3 ? 2'b00 : (N3 == 4 ? 2'b10 : (N3 == 5 ? 2'b11 : 2'bx)),
143
+ N1 == 1 ? 1'b0 : (N1 == 2 ? 1'b1 : 1'bx),
144
+ N2 == 3 ? 2'b00 : (N2 == 2 ? 2'b01 : (N2 == 4 ? 2'b10 : (N2 == 5 ? 2'b11 : 2'bx)))
145
+ }; // default: 6'h1B;
146
+
147
+ parameter [1:0] PLL_OUT_DIVSEL = {
148
+ OUTDIV == 1 ? 2'b00 : OUTDIV == 2 ? 2'b01 : OUTDIV == 4 ? 2'b11 : 2'bx
149
+ }; // default: 2'h0;
150
+
151
+ parameter [14:0] RX_EYE_MEAS_CFG = {11'b0, 3'b0};
152
+
153
+ parameter K_POS = 0;
154
+
155
+ function [63:0] calcTxData(input integer pos, input comma);
156
+ begin
157
+ if (comma == 1'b1) begin
158
+ calcTxData =
159
+ (pos == 0) ? 64'h4A4A4A4A_4A4A4ABC :
160
+ (pos == 1) ? 64'h4A4A4A4A_4A4ABC4A :
161
+ (pos == 2) ? 64'h4A4A4A4A_4ABC4A4A :
162
+ (pos == 3) ? 64'h4A4A4A4A_BC4A4A4A :
163
+ (pos == 4) ? 64'h4A4A4ABC_4A4A4A4A :
164
+ (pos == 5) ? 64'h4A4ABC4A_4A4A4A4A :
165
+ (pos == 6) ? 64'h4ABC4A4A_4A4A4A4A : 64'hBC4A4A4A_4A4A4A4A;
166
+ end
167
+ else begin
168
+ calcTxData =
169
+ (pos == 0) ? 64'h08070605_04030201 :
170
+ (pos == 1) ? 64'h07060504_03020108 :
171
+ (pos == 2) ? 64'h06050403_02010807 :
172
+ (pos == 3) ? 64'h05040302_01080706 :
173
+ (pos == 4) ? 64'h04030201_08070605 :
174
+ (pos == 5) ? 64'h03020108_07060504 :
175
+ (pos == 6) ? 64'h02010807_06050403 : 64'h01080706_05040302;
176
+ end
177
+ end
178
+ endfunction
179
+
180
+ function [7:0] calcTxK(input integer pos, input comma);
181
+ begin
182
+ if (comma == 1'b1) begin
183
+ calcTxK =
184
+ (comma_pos == 0) ? 8'b0000_0001 :
185
+ (comma_pos == 1) ? 8'b0000_0010 :
186
+ (comma_pos == 2) ? 8'b0000_0100 :
187
+ (comma_pos == 3) ? 8'b0000_1000 :
188
+ (comma_pos == 4) ? 8'b0001_0000 :
189
+ (comma_pos == 5) ? 8'b0010_0000 :
190
+ (comma_pos == 6) ? 8'b0100_0000 : 8'b1000_0000;
191
+ end
192
+ else begin
193
+ calcTxK = 8'b0000_0000;
194
+ end
195
+ end
196
+ endfunction
197
+
198
+
199
+ // CC_SERDES instance generator
200
+ // generated: 2024-01-31 13:57:01
201
+
202
+ CC_SERDES #(
203
+ .RX_BUF_RESET_TIME(5'h3),
204
+ .RX_PCS_RESET_TIME(5'h3),
205
+ .RX_RESET_TIMER_PRESC(5'h0),
206
+ .RX_RESET_DONE_GATE(1'h0),
207
+ .RX_CDR_RESET_TIME(5'h3),
208
+ .RX_EQA_RESET_TIME(5'h3),
209
+ .RX_PMA_RESET_TIME(5'h3),
210
+ .RX_WAIT_CDR_LOCK(1'b0), // turn off if loopback enabled
211
+ .RX_CALIB_EN(1'h1),
212
+ .RX_CALIB_OVR(1'h0),
213
+ .RX_CALIB_VAL(4'h0),
214
+ .RX_RTERM_VCMSEL(3'h4),
215
+ .RX_RTERM_PD(1'h0),
216
+ .RX_EQA_CKP_LF(8'hA3),
217
+ .RX_EQA_CKP_HF(8'hA3),
218
+ .RX_EQA_CKP_OFFSET(8'h01),
219
+ .RX_EN_EQA(1'h0),
220
+ .RX_EQA_LOCK_CFG(4'h0),
221
+ .RX_TH_MON1(5'h8),
222
+ .RX_EN_EQA_EXT_VALUE(4'h0),
223
+ .RX_TH_MON2(5'h8),
224
+ .RX_TAPW(5'h8),
225
+ .RX_AFE_OFFSET(5'h8),
226
+ .RX_EQA_CONFIG(16'h1C0),
227
+ .RX_AFE_PEAK(5'hF),
228
+ .RX_AFE_GAIN(4'h8),
229
+ .RX_AFE_VCMSEL(3'h4),
230
+ .RX_CDR_CKP(8'hF8),
231
+ .RX_CDR_CKI(8'h00),
232
+ .RX_CDR_TRANS_TH(9'h80), // h15?
233
+ .RX_CDR_LOCK_CFG(6'hB),
234
+ .RX_CDR_FREQ_ACC(15'h0),
235
+ .RX_CDR_PHASE_ACC(16'h0000),
236
+ .RX_CDR_SET_ACC_CONFIG(2'h0),
237
+ .RX_CDR_FORCE_LOCK(1'h0),
238
+ .RX_ALIGN_MCOMMA_VALUE(kChar[19:10]),
239
+ .RX_MCOMMA_ALIGN_OVR(1'h0),
240
+ .RX_MCOMMA_ALIGN(1'h0),
241
+ .RX_ALIGN_PCOMMA_VALUE(kChar[9:0]),
242
+ .RX_PCOMMA_ALIGN_OVR(1'h0),
243
+ .RX_PCOMMA_ALIGN(1'h0),
244
+ .RX_ALIGN_COMMA_WORD(2'h3), // 11: 32 bit, 01: 16 bit, 00: 8 bit
245
+ .RX_ALIGN_COMMA_ENABLE(10'h3FF),
246
+ .RX_SLIDE_MODE(2'b00), // !!!
247
+ .RX_COMMA_DETECT_EN_OVR(1'h0),
248
+ .RX_COMMA_DETECT_EN(1'h0),
249
+ .RX_SLIDE(2'h0),
250
+ .RX_EYE_MEAS_EN(1'h0),
251
+ .RX_EYE_MEAS_CFG(RX_EYE_MEAS_CFG),
252
+ .RX_MON_PH_OFFSET(6'h0),
253
+ .RX_EI_BIAS(4'h4),
254
+ .RX_EI_BW_SEL(4'h4),
255
+ .RX_EN_EI_DETECTOR_OVR(1'h0),
256
+ .RX_EN_EI_DETECTOR(1'h0),
257
+ .RX_DATA_SEL(1'h0),
258
+ .RX_BUF_BYPASS(1'h0),
259
+ .RX_CLKCOR_USE(1'h0),
260
+ .RX_CLKCOR_MIN_LAT(6'h20),
261
+ .RX_CLKCOR_MAX_LAT(6'h27),
262
+ .RX_CLKCOR_SEQ_1_0(10'h1F7),
263
+ .RX_CLKCOR_SEQ_1_1(10'h1F7),
264
+ .RX_CLKCOR_SEQ_1_2(10'h1F7),
265
+ .RX_CLKCOR_SEQ_1_3(10'h1F7),
266
+ .RX_PMA_LOOPBACK(1'h0),
267
+ .RX_PCS_LOOPBACK(1'h0),
268
+ .RX_DATAPATH_SEL(DATAPATH_SEL),
269
+ .RX_PRBS_OVR(1'b0),
270
+ .RX_PRBS_SEL(PRBS_SEL),
271
+ .RX_LOOPBACK_OVR(1'h0),
272
+ .RX_PRBS_CNT_RESET(1'h0),
273
+ .RX_POWER_DOWN_OVR(1'h0),
274
+ .RX_POWER_DOWN_N(1'h1),
275
+ .RX_RESET_OVR(1'h0),
276
+ .RX_RESET(1'h0),
277
+ .RX_PMA_RESET_OVR(1'h0),
278
+ .RX_PMA_RESET(1'h0),
279
+ .RX_EQA_RESET_OVR(1'h0),
280
+ .RX_EQA_RESET(1'h0),
281
+ .RX_CDR_RESET_OVR(1'h0),
282
+ .RX_CDR_RESET(1'h0),
283
+ .RX_PCS_RESET_OVR(1'h0),
284
+ .RX_PCS_RESET(1'h0),
285
+ .RX_BUF_RESET_OVR(1'h0),
286
+ .RX_BUF_RESET(1'h0),
287
+ .RX_POLARITY_OVR(1'h0),
288
+ .RX_POLARITY(1'h0),
289
+ .RX_8B10B_EN_OVR(1'h0),
290
+ .RX_8B10B_EN(1'h0),
291
+ .RX_8B10B_BYPASS(8'h0),
292
+ .RX_BYTE_REALIGN(1'h0),
293
+ .TX_SEL_PRE(5'h0),
294
+ .TX_SEL_POST(5'h0),
295
+ .TX_AMP(5'hF),
296
+ .TX_BRANCH_EN_PRE(5'h0),
297
+ .TX_BRANCH_EN_MAIN(6'h3F),
298
+ .TX_BRANCH_EN_POST(5'h0),
299
+ .TX_TAIL_CASCODE(3'h4),
300
+ .TX_DC_ENABLE(7'h3F),
301
+ .TX_DC_OFFSET(5'h8), // ? note: set to 8
302
+ .TX_CM_RAISE(5'h0),
303
+ .TX_CM_THRESHOLD_0(5'hE),
304
+ .TX_CM_THRESHOLD_1(5'h10),
305
+ .TX_SEL_PRE_EI(5'h0),
306
+ .TX_SEL_POST_EI(5'h0),
307
+ .TX_AMP_EI(5'hF),
308
+ .TX_BRANCH_EN_PRE_EI(5'h0),
309
+ .TX_BRANCH_EN_MAIN_EI(6'h3F),
310
+ .TX_BRANCH_EN_POST_EI(5'h0),
311
+ .TX_TAIL_CASCODE_EI(3'h4),
312
+ .TX_DC_ENABLE_EI(7'h3F),
313
+ .TX_DC_OFFSET_EI(5'h0),
314
+ .TX_CM_RAISE_EI(5'h0),
315
+ .TX_CM_THRESHOLD_0_EI(5'hE),
316
+ .TX_CM_THRESHOLD_1_EI(5'h10),
317
+ .TX_SEL_PRE_RXDET(5'h0),
318
+ .TX_SEL_POST_RXDET(5'h0),
319
+ .TX_AMP_RXDET(5'hF),
320
+ .TX_BRANCH_EN_PRE_RXDET(5'h0),
321
+ .TX_BRANCH_EN_MAIN_RXDET(6'h3F),
322
+ .TX_BRANCH_EN_POST_RXDET(5'h0),
323
+ .TX_TAIL_CASCODE_RXDET(3'h4),
324
+ .TX_DC_ENABLE_RXDET(7'h3F),
325
+ .TX_DC_OFFSET_RXDET(5'h0),
326
+ .TX_CM_RAISE_RXDET(5'h0),
327
+ .TX_CM_THRESHOLD_0_RXDET(5'hE),
328
+ .TX_CM_THRESHOLD_1_RXDET(5'h10),
329
+ .TX_CALIB_EN(1'h0),
330
+ .TX_CALIB_OVR(1'h0),
331
+ .TX_CALIB_VAL(4'h0),
332
+ .TX_CM_REG_KI(8'h80),
333
+ .TX_CM_SAR_EN(1'h0),
334
+ .TX_CM_REG_EN(1'h1),
335
+ .TX_PMA_RESET_TIME(5'h3),
336
+ .TX_PCS_RESET_TIME(5'h3),
337
+ .TX_PCS_RESET_OVR(1'h0),
338
+ .TX_PCS_RESET(1'h0),
339
+ .TX_PMA_RESET_OVR(1'h0),
340
+ .TX_PMA_RESET(1'h0),
341
+ .TX_RESET_OVR(1'h0),
342
+ .TX_RESET(1'h0),
343
+ .TX_PMA_LOOPBACK(TX_PMA_LOOPBACK),
344
+ .TX_PCS_LOOPBACK(1'h0),
345
+ .TX_DATAPATH_SEL(DATAPATH_SEL),
346
+ .TX_PRBS_OVR(1'b0),
347
+ .TX_PRBS_SEL(PRBS_SEL),
348
+ .TX_PRBS_FORCE_ERR(1'h0),
349
+ .TX_LOOPBACK_OVR(1'h0),
350
+ .TX_POWER_DOWN_OVR(1'h0),
351
+ .TX_POWER_DOWN_N(1'h1),
352
+ .TX_ELEC_IDLE_OVR(1'h0),
353
+ .TX_ELEC_IDLE(1'h0),
354
+ .TX_DETECT_RX_OVR(1'h0),
355
+ .TX_DETECT_RX(1'h0),
356
+ .TX_POLARITY_OVR(1'h0),
357
+ .TX_POLARITY(1'h0),
358
+ .TX_8B10B_EN_OVR(1'h0),
359
+ .TX_8B10B_EN(1'h0),
360
+ .TX_DATA_OVR(1'h0),
361
+ .TX_DATA_CNT(3'h0),
362
+ .TX_DATA_VALID(1'h0),
363
+ .PLL_EN_ADPLL_CTRL(1'h1),
364
+ .PLL_CONFIG_SEL(1'h1), // 0: internal, 1: regfile
365
+ .PLL_SET_OP_LOCK(1'h0),
366
+ .PLL_ENFORCE_LOCK(1'h0),
367
+ .PLL_DISABLE_LOCK(1'h0),
368
+ .PLL_LOCK_WINDOW(1'h1), // 0: long, 1: short
369
+ .PLL_FAST_LOCK(1'h1),
370
+ .PLL_SYNC_BYPASS(1'h0),
371
+ .PLL_PFD_SELECT(1'h0),
372
+ .PLL_REF_BYPASS(1'h0),
373
+ .PLL_REF_SEL(1'h1), // 0: single-ended, 1: lvds
374
+ .PLL_REF_RTERM(1'h1),
375
+ .PLL_FCNTRL(PLL_FCNTRL),
376
+ .PLL_MAIN_DIVSEL(PLL_MAIN_DIVSEL),
377
+ .PLL_OUT_DIVSEL(PLL_OUT_DIVSEL),
378
+ .PLL_CI(5'h3),
379
+ .PLL_CP(10'h50),
380
+ .PLL_AO(4'h0),
381
+ .PLL_SCAP(3'h0),
382
+ .PLL_FILTER_SHIFT(2'h2),
383
+ .PLL_SAR_LIMIT(3'h2),
384
+ .PLL_FT(11'h200),
385
+ .PLL_OPEN_LOOP(1'h0),
386
+ .PLL_SCAP_AUTO_CAL(1'h1),
387
+ .PLL_BISC_MODE(3'h5), // MODE B, enable
388
+ .PLL_BISC_TIMER_MAX(4'hC),
389
+ .PLL_BISC_OPT_DET_IND(1'h0),
390
+ .PLL_BISC_PFD_SEL(1'h0),
391
+ .PLL_BISC_DLY_DIR(1'h0),
392
+ .PLL_BISC_COR_DLY(3'h1),
393
+ .PLL_BISC_CAL_SIGN(1'h1),
394
+ .PLL_BISC_CAL_AUTO(1'h1),
395
+ .PLL_BISC_CP_MIN(5'h6),
396
+ .PLL_BISC_CP_MAX(5'h1E),
397
+ .PLL_BISC_CP_START(5'h6),
398
+ .PLL_BISC_DLY_PFD_MON_REF(5'h0),
399
+ .PLL_BISC_DLY_PFD_MON_DIV(5'h2),
400
+ .SERDES_ENABLE(1'h1),
401
+ .SERDES_AUTO_INIT(1'h0),
402
+ .SERDES_TESTMODE(1'h1)
403
+ ) i_cc_serdes (
404
+ // ADPLL
405
+ .RX_CLK_O(RX_CLK_O), // CDR CLK
406
+ .PLL_CLK_O(PLL_CLK_O),
407
+ // LOPPBACK
408
+ .LOOPBACK_I(LOOPBACK_SEL),
409
+ // RESET
410
+ .TX_RESET_I(trx_rst_i),
411
+ .RX_RESET_I(trx_rst_i),
412
+ .RX_PMA_RESET_I(1'b0),
413
+ .RX_EQA_RESET_I(1'b0),
414
+ .RX_CDR_RESET_I(1'b0),
415
+ .RX_PCS_RESET_I(1'b0),
416
+ .RX_BUF_RESET_I(1'b0),
417
+ .TX_PCS_RESET_I(1'b0),
418
+ .TX_PMA_RESET_I(1'b0),
419
+ .PLL_RESET_I(pll_rst_i),
420
+ .TX_RESET_DONE_O(TX_RESET_DONE_O),
421
+ .RX_RESET_DONE_O(RX_RESET_DONE_O),
422
+ // TX
423
+ .TX_CLK_I(PLL_CLK_O),
424
+ .TX_DATA_I(calcTxData(K_POS, 1'b1)),
425
+ .TX_POWER_DOWN_N_I(1'h1),
426
+ .TX_POLARITY_I(1'h0),
427
+ .TX_PRBS_SEL_I(PRBS_SEL),
428
+ .TX_PRBS_FORCE_ERR_I(TX_PRBS_FORCE_ERR_I),
429
+ .TX_8B10B_EN_I(ENABLE_8B10B),
430
+ .TX_8B10B_BYPASS_I(8'h0),
431
+ .TX_CHAR_IS_K_I(calcTxK(K_POS, RX_COMMA_DETECT_EN_I)),
432
+ .TX_CHAR_DISPMODE_I(8'h0),
433
+ .TX_CHAR_DISPVAL_I(8'h0),
434
+ .TX_ELEC_IDLE_I(1'h0),
435
+ .TX_DETECT_RX_I(1'b1),
436
+ .TX_BUF_ERR_O(TX_BUF_ERR_O),
437
+ // RX
438
+ .RX_CLK_I(RX_CLK_O),
439
+ .RX_POWER_DOWN_N_I(1'h1),
440
+ .RX_POLARITY_I(1'h0),
441
+ .RX_PRBS_SEL_I(PRBS_SEL),
442
+ .RX_PRBS_CNT_RESET_I(RX_PRBS_CNT_RESET_I),
443
+ .RX_PRBS_ERR_O(RX_PRBS_ERR_O),
444
+ .RX_8B10B_EN_I(ENABLE_8B10B),
445
+ .RX_8B10B_BYPASS_I(8'h0),
446
+ .RX_EN_EI_DETECTOR_I(1'h0),
447
+ .RX_COMMA_DETECT_EN_I(RX_COMMA_DETECT_EN_I),
448
+ .RX_SLIDE_I(1'h0),
449
+ .RX_MCOMMA_ALIGN_I(RX_COMMA_DETECT_EN_I),
450
+ .RX_PCOMMA_ALIGN_I(RX_COMMA_DETECT_EN_I),
451
+ .RX_DATA_O(RX_DATA_O),
452
+ .RX_NOT_IN_TABLE_O(),
453
+ .RX_CHAR_IS_COMMA_O(),
454
+ .RX_CHAR_IS_K_O(),
455
+ .RX_DISP_ERR_O(),
456
+ .TX_DETECT_RX_DONE_O(TX_DETECT_RX_DONE_O),
457
+ .TX_DETECT_RX_PRESENT_O(TX_DETECT_RX_PRESENT_O),
458
+ .RX_BUF_ERR_O(RX_BUF_ERR_O),
459
+ .RX_BYTE_IS_ALIGNED_O(),
460
+ .RX_BYTE_REALIGN_O(),
461
+ .RX_EI_EN_O(),
462
+ // REGFILE
463
+ .REGFILE_CLK_I(1'h0),
464
+ .REGFILE_WE_I(1'h0),
465
+ .REGFILE_EN_I(1'h0),
466
+ .REGFILE_ADDR_I(8'h0),
467
+ .REGFILE_DI_I(16'h0),
468
+ .REGFILE_MASK_I(16'h0),
469
+ .REGFILE_DO_O(REGFILE_DO_O),
470
+ .REGFILE_RDY_O(REGFILE_RDY_O)
471
+ );
472
+
473
+ endmodule
chili-chips-ba_openCologne/7.SerDes/1.serdestool_by_gm/serdestool.py ADDED
@@ -0,0 +1,1584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ #
3
+ # serdestool -- GateMate FPGA SerDes Toolkit
4
+ #
5
+ # Permission to use, copy, modify, and/or distribute this software for any
6
+ # purpose with or without fee is hereby granted, provided that the above
7
+ # copyright notice and this permission notice appear in all copies.
8
+ #
9
+ # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
+ #
17
+ # Visit https://colognechip.com for more information.
18
+ #
19
+ # Copyright (C) 2022 - 2025 Cologne Chip AG <support@colognechip.com>
20
+ # Authors: Patrick Urban
21
+ #
22
+
23
+ import re
24
+ import sys
25
+ import math
26
+ import curses
27
+ import random
28
+ import signal
29
+ import argparse
30
+ import datetime
31
+ import threading
32
+
33
+ from time import sleep
34
+ from itertools import chain
35
+
36
+ from pyftdi.ftdi import Ftdi
37
+ from pyftdi.jtag import JtagEngine
38
+ from pyftdi.usbtools import UsbTools
39
+ from pyftdi.bits import BitSequence
40
+
41
+ Boards_e = ['auto', 'pgm', 'evb']
42
+ ArgEpilog = 'example usage: python3 serdestool.py'
43
+
44
+ SER_CLK_PERIOD_NS = 10.0
45
+
46
+ class bcolors:
47
+ OK = '\033[92m' # GREEN
48
+ WARN = '\033[93m' # YELLOW
49
+ FAIL = '\033[91m' # RED
50
+ OVR = '\033[94m' # BLUE
51
+ RESET = '\033[0m' # RESET COLOR
52
+
53
+ def ArgHzRegex(value, pat=re.compile(r"^[0-9]+[kM]")):
54
+ if not pat.match(value):
55
+ raise argparse.ArgumentTypeError
56
+ return value
57
+
58
+ def ArgHzParse(value) -> int:
59
+ freq = 0
60
+ if value.endswith('k'):
61
+ freq = int(value[:-1]) * 1e3
62
+ elif value.endswith('M'):
63
+ freq = int(value[:-1]) * 1e6
64
+ else:
65
+ freq = int(value)
66
+ return freq
67
+
68
+ def FindAndFormatFtdiAddr(idx=0) -> str:
69
+ ftdiname = {
70
+ 0x6010: '2232h',
71
+ 0x6014: '232h'
72
+ }
73
+ usb = UsbTools()
74
+ vps_lst = list()
75
+ vps_lst.append((0x0403, 0x6010)) # evb: FT2232H
76
+ vps_lst.append((0x0403, 0x6014)) # pgm: FT232H
77
+ d = usb.find_all(vps=vps_lst)
78
+ if not d:
79
+ raise Exception('Error: No FTDI device found.')
80
+ d = d[idx][0]
81
+ return f'ftdi://ftdi:{ftdiname[d[1]]}/1'
82
+
83
+ class ColorFormatter:
84
+ pos_cond = ["DONE", "PRESENT", "LOCKED", "IS_ALIGNED", "EN_ADPLL_CTRL", "CONFIG_SEL", "SERDES_ENABLE"]
85
+ neg_cond = ["ERR", "DOWN", "TESTMODE"]
86
+ ovr_cond = ["OVR"]
87
+
88
+ @staticmethod
89
+ def get_color_pair(key, value):
90
+ """Returns the curses color pair based on the value conditions."""
91
+ try:
92
+ value = int(value) # Convert safely to integer
93
+ except ValueError:
94
+ return 0 # Default color if conversion fails
95
+
96
+ if any(cond in key for cond in ColorFormatter.pos_cond):
97
+ return 1 if value != 0 else 2 # Green for positive, Yellow for zero
98
+ elif any(cond in key for cond in ColorFormatter.neg_cond) and not any(cond in key for cond in ColorFormatter.ovr_cond):
99
+ return 3 if (value < 1 if key.endswith('_N') else value > 0) else 0 # Red for errors
100
+ elif any(cond in key for cond in ColorFormatter.ovr_cond) and value > 0:
101
+ return 4 # Blue for "OVR" values
102
+ return 0 # Default
103
+
104
+ class JtagTool:
105
+ CMD_JTAG_ID = '000000' # 0x00
106
+ CMD_JTAG_BYPASS = '111111' # 0x3F
107
+ CMD_JTAG_CONFIGURE = '000110' # 0x06
108
+ CMD_JTAG_WR_SERDES_REGFILE = '100101' # 0x25
109
+ CMD_JTAG_RD_SERDES_REGFILE = '100110' # 0x26
110
+
111
+ CMD_JTAG_STATUS_PLL0 = '011100' # 0x1C
112
+ CMD_JTAG_STATUS_PLL1 = '011101' # 0x1D
113
+ CMD_JTAG_STATUS_PLL2 = '011110' # 0x1E
114
+ CMD_JTAG_STATUS_PLL3 = '011111' # 0x1F
115
+
116
+ _chain_idx = 0
117
+ _taps_before = 0
118
+
119
+ def __init__(self, engine):
120
+ self._engine = engine
121
+ self._chain_idx = args.idx
122
+ self.idcode()
123
+
124
+ def write_ir(self, instruction) -> None:
125
+ byp_before = BitSequence('1'*6*self._taps_before, msb=True)
126
+ byp_after = BitSequence('1'*6*self._chain_idx, msb=True)
127
+ self._engine.write_ir(byp_before+instruction+byp_after)
128
+
129
+ def write_dr(self, data) -> None:
130
+ byp_before = BitSequence('0'*self._taps_before, msb=True)
131
+ byp_after = BitSequence('0'*self._chain_idx, msb=True)
132
+ self._engine.write_dr(byp_after+data+byp_before)
133
+
134
+ def read_dr(self, length: int) -> BitSequence:
135
+ word = self._engine.read_dr(length+self._taps_before)
136
+ if self._chain_idx > 0:
137
+ return word[self._taps_before:-self._chain_idx]
138
+ else:
139
+ return word[self._taps_before:]
140
+
141
+ def get_chunk(self, data, start, length):
142
+ return (data >> start) & ((1 << length) - 1)
143
+
144
+ # Read the IDCODE right after JTAG reset
145
+ def idcode(self) -> int:
146
+ idcodes = self._engine.read_dr(128)
147
+ self._engine.go_idle()
148
+ chain_len = 0
149
+ for i in range(0, 128, 32):
150
+ chunk_data = self.get_chunk(int(idcodes), i, 32)
151
+ if chunk_data != 0:
152
+ chain_len += 1
153
+ print(f'INFO: Found {chain_len} device{"s" if chain_len > 1 else ""} in JTAG chain.')
154
+ self._taps_before = chain_len - self._chain_idx - 1
155
+ return chain_len
156
+
157
+ # Read the IDCODE using CMD_JTAG_ID
158
+ def idcode_seq(self) -> int:
159
+ self.write_ir(BitSequence(self.CMD_JTAG_ID, msb=True))
160
+ status = self.read_dr(32)
161
+ self._engine.go_idle()
162
+ return int(status)
163
+
164
+ # Configure FPGA using CMD_JTAG_CONFIGURE
165
+ def wr_cfg(self, cfg_data):
166
+ a = []
167
+ b = bytearray(cfg_data)
168
+
169
+ for i in range(len(b)):
170
+ a.append(int(b[i]))
171
+
172
+ seq = BitSequence(bytes_=a[:-1], length=len(b)*8, msb=False, msby=True)
173
+
174
+ self.write_ir(BitSequence(self.CMD_JTAG_CONFIGURE, msb=True))
175
+ self.write_dr(seq)
176
+ self._engine.go_idle()
177
+
178
+ def wr_serdes_regfile(self, addr, data, mask, wren):
179
+ self.write_ir(BitSequence(self.CMD_JTAG_WR_SERDES_REGFILE, msb=True))
180
+ cmd = BitSequence(value=addr, length=8, msb=False, msby=True)
181
+ cmd += BitSequence(value=data, length=16, msb=False, msby=True)
182
+ cmd += BitSequence(value=mask, length=16, msb=False, msby=True)
183
+ cmd += BitSequence(value=wren, length=1, msb=False, msby=True)
184
+ self.write_dr(cmd)
185
+ self._engine.go_idle()
186
+
187
+ def rd_serdes_regfile(self):
188
+ self.write_ir(BitSequence(self.CMD_JTAG_RD_SERDES_REGFILE, msb=True))
189
+ word = self.read_dr(16)
190
+ self._engine.go_idle()
191
+ return word
192
+
193
+ def rd_status_pll(self, device=1, pll=0, verbose=0):
194
+ bs = BitSequence()
195
+ if pll == 0:
196
+ bs += BitSequence(self.CMD_JTAG_STATUS_PLL0, msb=True)
197
+ elif pll == 1:
198
+ bs += BitSequence(self.CMD_JTAG_STATUS_PLL1, msb=True)
199
+ elif pll == 2:
200
+ bs += BitSequence(self.CMD_JTAG_STATUS_PLL2, msb=True)
201
+ elif pll == 3:
202
+ bs += BitSequence(self.CMD_JTAG_STATUS_PLL3, msb=True)
203
+ else:
204
+ raise JtagError("Invalid PLL number: %s" % pll)
205
+ return 0
206
+ self._engine.write_ir(bs)
207
+ status = self._engine.read_dr(17)
208
+ self._engine.go_idle()
209
+
210
+ pll_status_bin = '{:017b}'.format(int(status))
211
+ if verbose:
212
+ print('pll{}: 0x{:05X}'.format(pll, int(status)))
213
+ print('pll%d: 0b%s' %(pll, pll_status_bin))
214
+
215
+ # 0: fine tune overflow flag
216
+ # 1: fine tune underflow flag
217
+ # 11: 2: fine tune value
218
+ # 13:12: state
219
+ # 16:14: coarse tune value
220
+ print('pll%d: fine tune overflow flag : %s ' %(pll, pll_status_bin[-1]))
221
+ print('pll%d: fine tune underflow flag : %s ' %(pll, pll_status_bin[-2]))
222
+ print('pll%d: fine tune value : %s ' %(pll, pll_status_bin[-12:-2]))
223
+
224
+ #S_IDLE = ‘d0; S_LOCK_IN = ‘d1; S_LOCKED = ‘d2; S_FAST_LOCK = ‘d3;
225
+ if pll_status_bin[-14:-12] == '00':
226
+ print('pll%d: state : %s -> S_IDLE' %(pll, pll_status_bin[-14:-12]))
227
+ elif pll_status_bin[-14:-12] == '01':
228
+ print('pll%d: state : %s -> S_LOCK_IN' %(pll, pll_status_bin[-14:-12]))
229
+ elif pll_status_bin[-14:-12] == '10':
230
+ print('pll%d: state : %s -> S_LOCKED' %(pll, pll_status_bin[-14:-12]))
231
+ elif pll_status_bin[-14:-12] == '11':
232
+ print('pll%d: state : %s -> S_FAST_LOCK' %(pll, pll_status_bin[-14:-12]))
233
+ print('pll%d: coarse tune value : %s ' %(pll, pll_status_bin[-17:-14]))
234
+ return (pll_status_bin[-14:-12] == '10') # locked
235
+
236
+ class SerdesRegfile:
237
+ def __init__(self, initial_fields):
238
+ self.fields = initial_fields
239
+
240
+ class SerdesTool:
241
+ regfile = SerdesRegfile({
242
+ 'RX_BUF_RESET_TIME': {'addr': 0x00, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 3},
243
+ 'RX_PCS_RESET_TIME': {'addr': 0x00, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 3},
244
+ 'RX_RESET_TIMER_PRESC': {'addr': 0x00, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 0},
245
+ 'RX_RESET_DONE_GATE': {'addr': 0x00, 'mode': 'R/W', 'hbit': 15, 'lbit': 15, 'val': 0},
246
+ 'RX_CDR_RESET_TIME': {'addr': 0x01, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 3},
247
+ 'RX_EQA_RESET_TIME': {'addr': 0x01, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 3},
248
+ 'RX_PMA_RESET_TIME': {'addr': 0x01, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 3},
249
+ 'RX_WAIT_CDR_LOCK': {'addr': 0x01, 'mode': 'R/W', 'hbit': 15, 'lbit': 15, 'val': 0},
250
+ 'RX_CALIB_EN': {'addr': 0x02, 'mode': 'W/C', 'hbit': 0, 'lbit': 0, 'val': 0},
251
+ 'RX_CALIB_DONE': {'addr': 0x02, 'mode': 'R', 'hbit': 1, 'lbit': 1, 'val': 1},
252
+ 'RX_CALIB_OVR': {'addr': 0x02, 'mode': 'R/W', 'hbit': 2, 'lbit': 2, 'val': 0},
253
+ 'RX_CALIB_VAL': {'addr': 0x02, 'mode': 'R/W', 'hbit': 6, 'lbit': 3, 'val': 0},
254
+ 'RX_CALIB_CAL': {'addr': 0x02, 'mode': 'R', 'hbit': 10, 'lbit': 7, 'val': 0},
255
+ 'RX_RTERM_VCMSEL': {'addr': 0x02, 'mode': 'R/W', 'hbit': 13, 'lbit': 11, 'val': 4},
256
+ 'RX_RTERM_PD': {'addr': 0x02, 'mode': 'R/W', 'hbit': 14, 'lbit': 14, 'val': 0},
257
+ 'RX_EQA_CKP_LF': {'addr': 0x03, 'mode': 'R/W', 'hbit': 7, 'lbit': 0, 'val': 0xA3},
258
+ 'RX_EQA_CKP_HF': {'addr': 0x03, 'mode': 'R/W', 'hbit': 15, 'lbit': 8, 'val': 0xA3},
259
+ 'RX_EQA_CKP_OFFSET': {'addr': 0x04, 'mode': 'R/W', 'hbit': 7, 'lbit': 0, 'val': 1},
260
+ 'RX_EN_EQA': {'addr': 0x04, 'mode': 'R/W', 'hbit': 8, 'lbit': 8, 'val': 0},
261
+ 'RX_EQA_LOCK_CFG': {'addr': 0x04, 'mode': 'R/W', 'hbit': 12, 'lbit': 9, 'val': 0},
262
+ 'RX_EQA_LOCKED': {'addr': 0x04, 'mode': 'R', 'hbit': 13, 'lbit': 13, 'val': 0},
263
+ 'RX_TH_MON1': {'addr': 0x05, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 8},
264
+ 'RX_EN_EQA_EXT_VALUE[0]': {'addr': 0x05, 'mode': 'R/W', 'hbit': 5, 'lbit': 5, 'val': 0},
265
+ 'RX_TH_MON2': {'addr': 0x05, 'mode': 'R/W', 'hbit': 10, 'lbit': 6, 'val': 8},
266
+ 'RX_EN_EQA_EXT_VALUE[1]': {'addr': 0x05, 'mode': 'R/W', 'hbit': 11, 'lbit': 11, 'val': 0},
267
+ 'RX_TAPW': {'addr': 0x06, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 8},
268
+ 'RX_EN_EQA_EXT_VALUE[2]': {'addr': 0x06, 'mode': 'R/W', 'hbit': 5, 'lbit': 5, 'val': 0},
269
+ 'RX_AFE_OFFSET': {'addr': 0x06, 'mode': 'R/W', 'hbit': 10, 'lbit': 6, 'val': 8},
270
+ 'RX_EN_EQA_EXT_VALUE[3]': {'addr': 0x06, 'mode': 'R/W', 'hbit': 11, 'lbit': 11, 'val': 0},
271
+ 'RX_EQA_TAPW': {'addr': 0x07, 'mode': 'R', 'hbit': 4, 'lbit': 0, 'val': 0},
272
+ 'RX_TH_MON': {'addr': 0x07, 'mode': 'R', 'hbit': 9, 'lbit': 5, 'val': 0},
273
+ 'RX_OFFSET': {'addr': 0x07, 'mode': 'R', 'hbit': 13, 'lbit': 10, 'val': 0},
274
+ 'RX_EQA_CONFIG': {'addr': 0x08, 'mode': 'R/W', 'hbit': 15, 'lbit': 0, 'val': 0x01C0},
275
+ 'RX_AFE_PEAK': {'addr': 0x09, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 15},
276
+ 'RX_AFE_GAIN': {'addr': 0x09, 'mode': 'R/W', 'hbit': 8, 'lbit': 5, 'val': 8},
277
+ 'RX_AFE_VCMSEL': {'addr': 0x09, 'mode': 'R/W', 'hbit': 11, 'lbit': 9, 'val': 4},
278
+ 'RX_CDR_CKP': {'addr': 0x0A, 'mode': 'R/W', 'hbit': 7, 'lbit': 0, 'val': 0xF8},
279
+ 'RX_CDR_CKI': {'addr': 0x0A, 'mode': 'R/W', 'hbit': 15, 'lbit': 8, 'val': 0},
280
+ 'RX_CDR_TRANS_TH': {'addr': 0x0B, 'mode': 'R/W', 'hbit': 8, 'lbit': 0, 'val': 128},
281
+ 'RX_CDR_LOCK_CFG': {'addr': 0x0B, 'mode': 'R/W', 'hbit': 14, 'lbit': 9, 'val': 0x0B},
282
+ 'RX_CDR_LOCKED': {'addr': 0x0B, 'mode': 'R', 'hbit': 15, 'lbit': 15, 'val': 0},
283
+ 'RX_CDR_FREQ_ACC_VAL': {'addr': 0x0C, 'mode': 'R', 'hbit': 14, 'lbit': 0, 'val': 0},
284
+ 'RX_CDR_PHASE_ACC_VAL': {'addr': 0x0D, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
285
+ 'RX_CDR_FREQ_ACC': {'addr': 0x0E, 'mode': 'R/W', 'hbit': 14, 'lbit': 0, 'val': 0},
286
+ 'RX_CDR_PHASE_ACC': {'addr': 0x0F, 'mode': 'R/W', 'hbit': 15, 'lbit': 0, 'val': 0},
287
+ 'RX_CDR_SET_ACC_CONFIG': {'addr': 0x10, 'mode': 'R/W', 'hbit': 1, 'lbit': 0, 'val': 0},
288
+ 'RX_CDR_FORCE_LOCK': {'addr': 0x10, 'mode': 'R/W', 'hbit': 2, 'lbit': 2, 'val': 0},
289
+ 'RX_ALIGN_MCOMMA_VALUE': {'addr': 0x11, 'mode': 'R/W', 'hbit': 9, 'lbit': 0, 'val': 0x283},
290
+ 'RX_MCOMMA_ALIGN_OVR': {'addr': 0x11, 'mode': 'R/W', 'hbit': 10, 'lbit': 10, 'val': 0},
291
+ 'RX_MCOMMA_ALIGN': {'addr': 0x11, 'mode': 'R/W', 'hbit': 11, 'lbit': 11, 'val': 0},
292
+ 'RX_ALIGN_PCOMMA_VALUE': {'addr': 0x12, 'mode': 'R/W', 'hbit': 9, 'lbit': 0, 'val': 0x17C},
293
+ 'RX_PCOMMA_ALIGN_OVR': {'addr': 0x12, 'mode': 'R/W', 'hbit': 10, 'lbit': 10, 'val': 0},
294
+ 'RX_PCOMMA_ALIGN': {'addr': 0x12, 'mode': 'R/W', 'hbit': 11, 'lbit': 11, 'val': 0},
295
+ 'RX_ALIGN_COMMA_WORD': {'addr': 0x12, 'mode': 'R/W', 'hbit': 13, 'lbit': 12, 'val': 0},
296
+ 'RX_ALIGN_COMMA_ENABLE': {'addr': 0x13, 'mode': 'R/W', 'hbit': 9, 'lbit': 0, 'val': 0x3FF},
297
+ 'RX_SLIDE_MODE': {'addr': 0x13, 'mode': 'R/W', 'hbit': 11, 'lbit': 10, 'val': 0},
298
+ 'RX_COMMA_DETECT_EN_OVR': {'addr': 0x13, 'mode': 'R/W', 'hbit': 12, 'lbit': 12, 'val': 0},
299
+ 'RX_COMMA_DETECT_EN': {'addr': 0x13, 'mode': 'R/W', 'hbit': 13, 'lbit': 13, 'val': 0},
300
+ 'RX_SLIDE[0]': {'addr': 0x13, 'mode': 'R/W', 'hbit': 14, 'lbit': 14, 'val': 0},
301
+ 'RX_SLIDE[1]': {'addr': 0x13, 'mode': 'W/C', 'hbit': 15, 'lbit': 15, 'val': 0},
302
+ 'RX_EYE_MEAS_EN': {'addr': 0x14, 'mode': 'W/C', 'hbit': 0, 'lbit': 0, 'val': 0},
303
+ 'RX_EYE_MEAS_CFG': {'addr': 0x14, 'mode': 'R/W', 'hbit': 15, 'lbit': 1, 'val': 0},
304
+ 'RX_MON_PH_OFFSET': {'addr': 0x15, 'mode': 'R/W', 'hbit': 5, 'lbit': 0, 'val': 0},
305
+ 'RX_EYE_MEAS_CORRECT_11S': {'addr': 0x16, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
306
+ 'RX_EYE_MEAS_WRONG_11S': {'addr': 0x17, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
307
+ 'RX_EYE_MEAS_CORRECT_00S': {'addr': 0x18, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
308
+ 'RX_EYE_MEAS_WRONG_00S': {'addr': 0x19, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
309
+ 'RX_EYE_MEAS_CORRECT_001S': {'addr': 0x1A, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
310
+ 'RX_EYE_MEAS_WRONG_001S': {'addr': 0x1B, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
311
+ 'RX_EYE_MEAS_CORRECT_110S': {'addr': 0x1C, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
312
+ 'RX_EYE_MEAS_WRONG_110S': {'addr': 0x1D, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
313
+ 'RX_EI_BIAS': {'addr': 0x1E, 'mode': 'R/W', 'hbit': 3, 'lbit': 0, 'val': 4},
314
+ 'RX_EI_BW_SEL': {'addr': 0x1E, 'mode': 'R/W', 'hbit': 7, 'lbit': 4, 'val': 4},
315
+ 'RX_EN_EI_DETECTOR_OVR': {'addr': 0x1E, 'mode': 'R/W', 'hbit': 8, 'lbit': 8, 'val': 0},
316
+ 'RX_EN_EI_DETECTOR': {'addr': 0x1E, 'mode': 'R/W', 'hbit': 9, 'lbit': 9, 'val': 0},
317
+ 'RX_EI_EN': {'addr': 0x1E, 'mode': 'R', 'hbit': 10, 'lbit': 10, 'val': 0},
318
+ 'RX_PRBS_ERR_CNT': {'addr': 0x1F, 'mode': 'R', 'hbit': 14, 'lbit': 0, 'val': 0},
319
+ 'RX_PRBS_LOCKED': {'addr': 0x1F, 'mode': 'R', 'hbit': 15, 'lbit': 15, 'val': 0},
320
+ 'RX_DATA_SEL': {'addr': 0x20, 'mode': 'R/W', 'hbit': 0, 'lbit': 0, 'val': 0},
321
+ 'RX_DATA[15:0]': {'addr': 0x20, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
322
+ 'RX_DATA[31:16]': {'addr': 0x21, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
323
+ 'RX_DATA[47:32]': {'addr': 0x22, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
324
+ 'RX_DATA[63:48]': {'addr': 0x23, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
325
+ 'RX_DATA[79:64]': {'addr': 0x24, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
326
+ 'RX_BUF_BYPASS': {'addr': 0x25, 'mode': 'R/W', 'hbit': 0, 'lbit': 0, 'val': 0},
327
+ 'RX_CLKCOR_USE': {'addr': 0x25, 'mode': 'R/W', 'hbit': 1, 'lbit': 1, 'val': 0},
328
+ 'RX_CLKCOR_MIN_LAT': {'addr': 0x25, 'mode': 'R/W', 'hbit': 7, 'lbit': 2, 'val': 32},
329
+ 'RX_CLKCOR_MAX_LAT': {'addr': 0x25, 'mode': 'R/W', 'hbit': 13, 'lbit': 8, 'val': 39},
330
+ 'RX_CLKCOR_SEQ_1_0': {'addr': 0x26, 'mode': 'R/W', 'hbit': 9, 'lbit': 0, 'val': 0x1F7},
331
+ 'RX_CLKCOR_SEQ_1_1': {'addr': 0x27, 'mode': 'R/W', 'hbit': 9, 'lbit': 0, 'val': 0x1F7},
332
+ 'RX_CLKCOR_SEQ_1_2': {'addr': 0x28, 'mode': 'R/W', 'hbit': 9, 'lbit': 0, 'val': 0x1F7},
333
+ 'RX_CLKCOR_SEQ_1_3': {'addr': 0x29, 'mode': 'R/W', 'hbit': 9, 'lbit': 0, 'val': 0x1F7},
334
+ 'RX_PMA_LOOPBACK': {'addr': 0x2A, 'mode': 'R/W', 'hbit': 0, 'lbit': 0, 'val': 0},
335
+ 'RX_PCS_LOOPBACK': {'addr': 0x2A, 'mode': 'R/W', 'hbit': 1, 'lbit': 1, 'val': 0},
336
+ 'RX_DATAPATH_SEL': {'addr': 0x2A, 'mode': 'R/W', 'hbit': 3, 'lbit': 2, 'val': 3},
337
+ 'RX_PRBS_OVR': {'addr': 0x2A, 'mode': 'R/W', 'hbit': 4, 'lbit': 4, 'val': 0},
338
+ 'RX_PRBS_SEL': {'addr': 0x2A, 'mode': 'R/W', 'hbit': 7, 'lbit': 5, 'val': 0},
339
+ 'RX_LOOPBACK_OVR': {'addr': 0x2A, 'mode': 'R/W', 'hbit': 8, 'lbit': 8, 'val': 0},
340
+ 'RX_PRBS_CNT_RESET': {'addr': 0x2A, 'mode': 'W/C', 'hbit': 9, 'lbit': 9, 'val': 0},
341
+ 'RX_POWER_DOWN_OVR': {'addr': 0x2A, 'mode': 'R/W', 'hbit': 10, 'lbit': 10, 'val': 0},
342
+ 'RX_POWER_DOWN_N': {'addr': 0x2A, 'mode': 'R/W', 'hbit': 11, 'lbit': 11, 'val': 0},
343
+ 'RX_PRESENT': {'addr': 0x2A, 'mode': 'R', 'hbit': 12, 'lbit': 12, 'val': 0},
344
+ 'RX_DETECT_DONE': {'addr': 0x2A, 'mode': 'R', 'hbit': 13, 'lbit': 13, 'val': 0},
345
+ 'RX_BUF_ERR': {'addr': 0x2A, 'mode': 'R', 'hbit': 14, 'lbit': 14, 'val': 0},
346
+ 'RX_RESET_OVR': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 0, 'lbit': 0, 'val': 0},
347
+ 'RX_RESET': {'addr': 0x2B, 'mode': 'W/C', 'hbit': 1, 'lbit': 1, 'val': 0},
348
+ 'RX_PMA_RESET_OVR': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 2, 'lbit': 2, 'val': 0},
349
+ 'RX_PMA_RESET': {'addr': 0x2B, 'mode': 'W/C', 'hbit': 3, 'lbit': 3, 'val': 0},
350
+ 'RX_EQA_RESET_OVR': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 4, 'lbit': 4, 'val': 0},
351
+ 'RX_EQA_RESET': {'addr': 0x2B, 'mode': 'W/C', 'hbit': 5, 'lbit': 5, 'val': 0},
352
+ 'RX_CDR_RESET_OVR': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 6, 'lbit': 6, 'val': 0},
353
+ 'RX_CDR_RESET': {'addr': 0x2B, 'mode': 'W/C', 'hbit': 7, 'lbit': 7, 'val': 0},
354
+ 'RX_PCS_RESET_OVR': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 8, 'lbit': 8, 'val': 0},
355
+ 'RX_PCS_RESET': {'addr': 0x2B, 'mode': 'W/C', 'hbit': 9, 'lbit': 9, 'val': 0},
356
+ 'RX_BUF_RESET_OVR': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 10, 'lbit': 10, 'val': 0},
357
+ 'RX_BUF_RESET': {'addr': 0x2B, 'mode': 'W/C', 'hbit': 11, 'lbit': 11, 'val': 0},
358
+ 'RX_POLARITY_OVR': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 12, 'lbit': 12, 'val': 0},
359
+ 'RX_POLARITY': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 13, 'lbit': 13, 'val': 0},
360
+ 'RX_8B10B_EN_OVR': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 14, 'lbit': 14, 'val': 0},
361
+ 'RX_8B10B_EN': {'addr': 0x2B, 'mode': 'R/W', 'hbit': 15, 'lbit': 15, 'val': 0},
362
+ 'RX_8B10B_BYPASS': {'addr': 0x2C, 'mode': 'R/W', 'hbit': 7, 'lbit': 0, 'val': 0},
363
+ 'RX_BYTE_IS_ALIGNED': {'addr': 0x2C, 'mode': 'R', 'hbit': 8, 'lbit': 8, 'val': 0},
364
+ 'RX_BYTE_REALIGN': {'addr': 0x2C, 'mode': 'R/C', 'hbit': 9, 'lbit': 9, 'val': 0},
365
+ 'RX_RESET_DONE': {'addr': 0x2C, 'mode': 'R', 'hbit': 10, 'lbit': 10, 'val': 0},
366
+ #'RX_DBG_EN': {'addr': 0x2D, 'mode': 'W/C', 'hbit': 0, 'lbit': 0, 'val': 0},
367
+ #'RX_DBG_SEL': {'addr': 0x2D, 'mode': 'R/W', 'hbit': 4, 'lbit': 1, 'val': 0},
368
+ #'RX_DBG_MODE': {'addr': 0x2D, 'mode': 'R/W', 'hbit': 5, 'lbit': 5, 'val': 0},
369
+ #'RX_DBG_SRAM_DELAY': {'addr': 0x2D, 'mode': 'R/W', 'hbit': 11, 'lbit': 6, 'val': 5},
370
+ #'RX_DBG_ADDR': {'addr': 0x2E, 'mode': 'R/W', 'hbit': 9, 'lbit': 0, 'val': 0},
371
+ #'RX_DBG_RE': {'addr': 0x2E, 'mode': 'W/C', 'hbit': 10, 'lbit': 10, 'val': 0},
372
+ #'RX_DBG_WE': {'addr': 0x2E, 'mode': 'W/C', 'hbit': 11, 'lbit': 11, 'val': 0},
373
+ #'RX_DBG_DATA[3:0]': {'addr': 0x2E, 'mode': 'R/W', 'hbit': 15, 'lbit': 12, 'val': 0},
374
+ #'RX_DBG_DATA[19:4]': {'addr': 0x2F, 'mode': 'R/W', 'hbit': 15, 'lbit': 0, 'val': 0},
375
+ 'TX_SEL_PRE': {'addr': 0x30, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
376
+ 'TX_SEL_POST': {'addr': 0x30, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 0},
377
+ 'TX_AMP': {'addr': 0x30, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 15},
378
+ 'TX_BRANCH_EN_PRE': {'addr': 0x31, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
379
+ 'TX_BRANCH_EN_MAIN': {'addr': 0x31, 'mode': 'R/W', 'hbit': 10, 'lbit': 5, 'val': 0x3F},
380
+ 'TX_BRANCH_EN_POST': {'addr': 0x31, 'mode': 'R/W', 'hbit': 15, 'lbit': 11, 'val': 0},
381
+ 'TX_TAIL_CASCODE': {'addr': 0x32, 'mode': 'R/W', 'hbit': 2, 'lbit': 0, 'val': 4},
382
+ 'TX_DC_ENABLE': {'addr': 0x32, 'mode': 'R/W', 'hbit': 9, 'lbit': 3, 'val': 63},
383
+ 'TX_DC_OFFSET': {'addr': 0x32, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 8},
384
+ 'TX_CM_RAISE': {'addr': 0x33, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
385
+ 'TX_CM_THRESHOLD_0': {'addr': 0x33, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 14},
386
+ 'TX_CM_THRESHOLD_1': {'addr': 0x33, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 16},
387
+ 'TX_SEL_PRE_EI': {'addr': 0x34, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
388
+ 'TX_SEL_POST_EI': {'addr': 0x34, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 0},
389
+ 'TX_AMP_EI': {'addr': 0x34, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 15},
390
+ 'TX_BRANCH_EN_PRE_EI': {'addr': 0x35, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
391
+ 'TX_BRANCH_EN_MAIN_EI': {'addr': 0x35, 'mode': 'R/W', 'hbit': 10, 'lbit': 5, 'val': 0x3F},
392
+ 'TX_BRANCH_EN_POST_EI': {'addr': 0x35, 'mode': 'R/W', 'hbit': 15, 'lbit': 11, 'val': 0},
393
+ 'TX_TAIL_CASCODE_EI': {'addr': 0x36, 'mode': 'R/W', 'hbit': 2, 'lbit': 0, 'val': 4},
394
+ 'TX_DC_ENABLE_EI': {'addr': 0x36, 'mode': 'R/W', 'hbit': 9, 'lbit': 3, 'val': 63},
395
+ 'TX_DC_OFFSET_EI': {'addr': 0x36, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 0},
396
+ 'TX_CM_RAISE_EI': {'addr': 0x37, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
397
+ 'TX_CM_THRESHOLD_0_EI': {'addr': 0x37, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 14},
398
+ 'TX_CM_THRESHOLD_1_EI': {'addr': 0x37, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 16},
399
+ 'TX_SEL_PRE_RXDET': {'addr': 0x38, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
400
+ 'TX_SEL_POST_RXDET': {'addr': 0x38, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 0},
401
+ 'TX_AMP_RXDET': {'addr': 0x38, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 15},
402
+ 'TX_BRANCH_EN_PRE_RXDET': {'addr': 0x39, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
403
+ 'TX_BRANCH_EN_MAIN_RXDET': {'addr': 0x39, 'mode': 'R/W', 'hbit': 10, 'lbit': 5, 'val': 0x3F},
404
+ 'TX_BRANCH_EN_POST_RXDET': {'addr': 0x39, 'mode': 'R/W', 'hbit': 15, 'lbit': 11, 'val': 0},
405
+ 'TX_TAIL_CASCODE_RXDET': {'addr': 0x3A, 'mode': 'R/W', 'hbit': 2, 'lbit': 0, 'val': 4},
406
+ 'TX_DC_ENABLE_RXDET': {'addr': 0x3A, 'mode': 'R/W', 'hbit': 9, 'lbit': 3, 'val': 63},
407
+ 'TX_DC_OFFSET_RXDET': {'addr': 0x3A, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 0},
408
+ 'TX_CM_RAISE_RXDET': {'addr': 0x3B, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
409
+ 'TX_CM_THRESHOLD_0_RXDET': {'addr': 0x3B, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 14},
410
+ 'TX_CM_THRESHOLD_1_RXDET': {'addr': 0x3B, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 16},
411
+ 'TX_CALIB_EN': {'addr': 0x3C, 'mode': 'W/C', 'hbit': 0, 'lbit': 0, 'val': 0},
412
+ 'TX_CALIB_DONE': {'addr': 0x3C, 'mode': 'R', 'hbit': 1, 'lbit': 1, 'val': 1},
413
+ 'TX_CALIB_OVR': {'addr': 0x3C, 'mode': 'R/W', 'hbit': 2, 'lbit': 2, 'val': 0},
414
+ 'TX_CALIB_VAL': {'addr': 0x3C, 'mode': 'R/W', 'hbit': 6, 'lbit': 3, 'val': 0},
415
+ 'TX_CALIB_CAL': {'addr': 0x3C, 'mode': 'R', 'hbit': 10, 'lbit': 7, 'val': 0},
416
+ 'TX_CM_REG_KI': {'addr': 0x3D, 'mode': 'R/W', 'hbit': 7, 'lbit': 0, 'val': 0x80},
417
+ 'TX_CM_SAR_EN': {'addr': 0x3D, 'mode': 'R/W', 'hbit': 8, 'lbit': 8, 'val': 0},
418
+ 'TX_CM_REG_EN': {'addr': 0x3D, 'mode': 'R/W', 'hbit': 9, 'lbit': 9, 'val': 1},
419
+ 'TX_CM_SAR_RESULT_0': {'addr': 0x3E, 'mode': 'R', 'hbit': 4, 'lbit': 0, 'val': 0},
420
+ 'TX_CM_SAR_RESULT_1': {'addr': 0x3E, 'mode': 'R', 'hbit': 9, 'lbit': 5, 'val': 0},
421
+ 'TX_PMA_RESET_TIME': {'addr': 0x3F, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 3},
422
+ 'TX_PCS_RESET_TIME': {'addr': 0x3F, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 3},
423
+ 'TX_PCS_RESET_OVR': {'addr': 0x3F, 'mode': 'R/W', 'hbit': 10, 'lbit': 10, 'val': 0},
424
+ 'TX_PCS_RESET': {'addr': 0x3F, 'mode': 'W/C', 'hbit': 11, 'lbit': 11, 'val': 0},
425
+ 'TX_PMA_RESET_OVR': {'addr': 0x3F, 'mode': 'R/W', 'hbit': 12, 'lbit': 12, 'val': 0},
426
+ 'TX_PMA_RESET': {'addr': 0x3F, 'mode': 'W/C', 'hbit': 13, 'lbit': 13, 'val': 0},
427
+ 'TX_RESET_OVR': {'addr': 0x3F, 'mode': 'R/W', 'hbit': 14, 'lbit': 14, 'val': 0},
428
+ 'TX_RESET': {'addr': 0x3F, 'mode': 'W/C', 'hbit': 15, 'lbit': 15, 'val': 0},
429
+ 'TX_PMA_LOOPBACK': {'addr': 0x40, 'mode': 'R/W', 'hbit': 1, 'lbit': 0, 'val': 0},
430
+ 'TX_PCS_LOOPBACK': {'addr': 0x40, 'mode': 'R/W', 'hbit': 2, 'lbit': 2, 'val': 0},
431
+ 'TX_DATAPATH_SEL': {'addr': 0x40, 'mode': 'R/W', 'hbit': 4, 'lbit': 3, 'val': 3},
432
+ 'TX_PRBS_OVR': {'addr': 0x40, 'mode': 'R/W', 'hbit': 5, 'lbit': 5, 'val': 0},
433
+ 'TX_PRBS_SEL': {'addr': 0x40, 'mode': 'R/W', 'hbit': 8, 'lbit': 6, 'val': 0},
434
+ 'TX_PRBS_FORCE_ERR': {'addr': 0x40, 'mode': 'W/C', 'hbit': 9, 'lbit': 9, 'val': 0},
435
+ 'TX_LOOPBACK_OVR': {'addr': 0x40, 'mode': 'R/W', 'hbit': 10, 'lbit': 10, 'val': 0},
436
+ 'TX_POWER_DOWN_OVR': {'addr': 0x40, 'mode': 'R/W', 'hbit': 11, 'lbit': 11, 'val': 0},
437
+ 'TX_POWER_DOWN_N': {'addr': 0x40, 'mode': 'R/W', 'hbit': 12, 'lbit': 12, 'val': 0},
438
+ 'TX_ELEC_IDLE_OVR': {'addr': 0x41, 'mode': 'R/W', 'hbit': 0, 'lbit': 0, 'val': 0},
439
+ 'TX_ELEC_IDLE': {'addr': 0x41, 'mode': 'R/W', 'hbit': 1, 'lbit': 1, 'val': 0},
440
+ 'TX_DETECT_RX_OVR': {'addr': 0x41, 'mode': 'R/W', 'hbit': 2, 'lbit': 2, 'val': 0},
441
+ 'TX_DETECT_RX': {'addr': 0x41, 'mode': 'R/W', 'hbit': 3, 'lbit': 3, 'val': 0},
442
+ 'TX_POLARITY_OVR': {'addr': 0x41, 'mode': 'R/W', 'hbit': 4, 'lbit': 4, 'val': 0},
443
+ 'TX_POLARITY': {'addr': 0x41, 'mode': 'R/W', 'hbit': 5, 'lbit': 5, 'val': 0},
444
+ 'TX_8B10B_EN_OVR': {'addr': 0x41, 'mode': 'R/W', 'hbit': 6, 'lbit': 6, 'val': 0},
445
+ 'TX_8B10B_EN': {'addr': 0x41, 'mode': 'R/W', 'hbit': 7, 'lbit': 7, 'val': 0},
446
+ 'TX_DATA_OVR': {'addr': 0x41, 'mode': 'R/W', 'hbit': 8, 'lbit': 8, 'val': 0},
447
+ 'TX_DATA_CNT': {'addr': 0x41, 'mode': 'R/W', 'hbit': 11, 'lbit': 9, 'val': 0},
448
+ 'TX_DATA_VALID': {'addr': 0x41, 'mode': 'W/C', 'hbit': 12, 'lbit': 12, 'val': 0},
449
+ 'TX_BUF_ERR': {'addr': 0x41, 'mode': 'R', 'hbit': 13, 'lbit': 13, 'val': 0},
450
+ 'TX_RESET_DONE': {'addr': 0x41, 'mode': 'R', 'hbit': 14, 'lbit': 14, 'val': 0},
451
+ 'TX_DATA': {'addr': 0x42, 'mode': 'R/W', 'hbit': 15, 'lbit': 0, 'val': 0},
452
+ # 0x43..0x4F unused
453
+ 'PLL_EN_ADPLL_CTRL': {'addr': 0x50, 'mode': 'R/W', 'hbit': 0, 'lbit': 0, 'val': 0},
454
+ 'PLL_CONFIG_SEL': {'addr': 0x50, 'mode': 'R/W', 'hbit': 1, 'lbit': 1, 'val': 1},
455
+ 'PLL_SET_OP_LOCK': {'addr': 0x50, 'mode': 'R/W', 'hbit': 2, 'lbit': 2, 'val': 0},
456
+ 'PLL_ENFORCE_LOCK': {'addr': 0x50, 'mode': 'R/W', 'hbit': 3, 'lbit': 3, 'val': 0},
457
+ 'PLL_DISABLE_LOCK': {'addr': 0x50, 'mode': 'R/W', 'hbit': 4, 'lbit': 4, 'val': 0},
458
+ 'PLL_LOCK_WINDOW': {'addr': 0x50, 'mode': 'R/W', 'hbit': 5, 'lbit': 5, 'val': 1},
459
+ 'PLL_FAST_LOCK': {'addr': 0x50, 'mode': 'R/W', 'hbit': 6, 'lbit': 6, 'val': 1},
460
+ 'PLL_SYNC_BYPASS': {'addr': 0x50, 'mode': 'R/W', 'hbit': 7, 'lbit': 7, 'val': 0},
461
+ 'PLL_PFD_SELECT': {'addr': 0x50, 'mode': 'R/W', 'hbit': 8, 'lbit': 8, 'val': 0},
462
+ 'PLL_REF_BYPASS': {'addr': 0x50, 'mode': 'R/W', 'hbit': 9, 'lbit': 9, 'val': 0},
463
+ 'PLL_REF_SEL': {'addr': 0x50, 'mode': 'R/W', 'hbit': 10, 'lbit': 10, 'val': 1},
464
+ 'PLL_REF_RTERM': {'addr': 0x50, 'mode': 'R/W', 'hbit': 11, 'lbit': 11, 'val': 1},
465
+ 'PLL_FCNTRL': {'addr': 0x51, 'mode': 'R/W', 'hbit': 5, 'lbit': 0, 'val': 58},
466
+ 'PLL_MAIN_DIVSEL': {'addr': 0x51, 'mode': 'R/W', 'hbit': 11, 'lbit': 6, 'val': 27},
467
+ 'PLL_OUT_DIVSEL': {'addr': 0x51, 'mode': 'R/W', 'hbit': 13, 'lbit': 12, 'val': 0},
468
+ 'PLL_CI': {'addr': 0x52, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 3},
469
+ 'PLL_CP': {'addr': 0x52, 'mode': 'R/W', 'hbit': 14, 'lbit': 5, 'val': 80},
470
+ 'PLL_AO': {'addr': 0x53, 'mode': 'R/W', 'hbit': 3, 'lbit': 0, 'val': 0},
471
+ 'PLL_SCAP': {'addr': 0x53, 'mode': 'R/W', 'hbit': 6, 'lbit': 4, 'val': 0},
472
+ 'PLL_FILTER_SHIFT': {'addr': 0x53, 'mode': 'R/W', 'hbit': 8, 'lbit': 7, 'val': 2},
473
+ 'PLL_SAR_LIMIT': {'addr': 0x53, 'mode': 'R/W', 'hbit': 11, 'lbit': 9, 'val': 2},
474
+ 'PLL_FT': {'addr': 0x54, 'mode': 'R/W', 'hbit': 10, 'lbit': 0, 'val': 512},
475
+ 'PLL_OPEN_LOOP': {'addr': 0x54, 'mode': 'R/W', 'hbit': 11, 'lbit': 11, 'val': 0},
476
+ 'PLL_SCAP_AUTO_CAL': {'addr': 0x54, 'mode': 'R/W', 'hbit': 12, 'lbit': 12, 'val': 1},
477
+ 'PLL_LOCKED': {'addr': 0x55, 'mode': 'R', 'hbit': 0, 'lbit': 0, 'val': 0},
478
+ 'PLL_CAP_FT_OF': {'addr': 0x55, 'mode': 'R', 'hbit': 1, 'lbit': 1, 'val': 0},
479
+ 'PLL_CAP_FT_UF': {'addr': 0x55, 'mode': 'R', 'hbit': 2, 'lbit': 2, 'val': 0},
480
+ 'PLL_CAP_FT': {'addr': 0x55, 'mode': 'R', 'hbit': 12, 'lbit': 3, 'val': 0},
481
+ 'PLL_CAP_STATE': {'addr': 0x55, 'mode': 'R', 'hbit': 14, 'lbit': 13, 'val': 0},
482
+ 'PLL_SYNC_VALUE': {'addr': 0x56, 'mode': 'R', 'hbit': 7, 'lbit': 0, 'val': 0},
483
+ 'PLL_BISC_MODE': {'addr': 0x57, 'mode': 'R/W', 'hbit': 2, 'lbit': 0, 'val': 4},
484
+ 'PLL_BISC_TIMER_MAX': {'addr': 0x57, 'mode': 'R/W', 'hbit': 6, 'lbit': 3, 'val': 15},
485
+ 'PLL_BISC_OPT_DET_IND': {'addr': 0x57, 'mode': 'R/W', 'hbit': 7, 'lbit': 7, 'val': 0},
486
+ 'PLL_BISC_PFD_SEL': {'addr': 0x57, 'mode': 'R/W', 'hbit': 8, 'lbit': 8, 'val': 0},
487
+ 'PLL_BISC_DLY_DIR': {'addr': 0x57, 'mode': 'R/W', 'hbit': 9, 'lbit': 9, 'val': 0},
488
+ 'PLL_BISC_COR_DLY': {'addr': 0x57, 'mode': 'R/W', 'hbit': 12, 'lbit': 10, 'val': 1},
489
+ 'PLL_BISC_CAL_SIGN': {'addr': 0x57, 'mode': 'R/W', 'hbit': 13, 'lbit': 13, 'val': 0},
490
+ 'PLL_BISC_CAL_AUTO': {'addr': 0x57, 'mode': 'R/W', 'hbit': 14, 'lbit': 14, 'val': 1},
491
+ 'PLL_BISC_CP_MIN': {'addr': 0x58, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 4},
492
+ 'PLL_BISC_CP_MAX': {'addr': 0x58, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 18},
493
+ 'PLL_BISC_CP_START': {'addr': 0x58, 'mode': 'R/W', 'hbit': 14, 'lbit': 10, 'val': 12},
494
+ 'PLL_BISC_DLY_PFD_MON_REF': {'addr': 0x59, 'mode': 'R/W', 'hbit': 4, 'lbit': 0, 'val': 0},
495
+ 'PLL_BISC_DLY_PFD_MON_DIV': {'addr': 0x59, 'mode': 'R/W', 'hbit': 9, 'lbit': 5, 'val': 2},
496
+ 'PLL_BISC_TIMER_DONE': {'addr': 0x5A, 'mode': 'R', 'hbit': 0, 'lbit': 0, 'val': 0},
497
+ 'PLL_BISC_CP': {'addr': 0x5A, 'mode': 'R', 'hbit': 7, 'lbit': 1, 'val': 0}, # BISC_RESULT[15:1]
498
+ 'PLL_BISC_CO': {'addr': 0x5B, 'mode': 'R', 'hbit': 15, 'lbit': 0, 'val': 0},
499
+ 'SERDES_ENABLE': {'addr': 0x5C, 'mode': 'R/C', 'hbit': 0, 'lbit': 0, 'val': 1},
500
+ 'SERDES_AUTO_INIT': {'addr': 0x5C, 'mode': 'R/C', 'hbit': 1, 'lbit': 1, 'val': 0},
501
+ 'SERDES_TESTMODE': {'addr': 0x5C, 'mode': 'R/C', 'hbit': 2, 'lbit': 2, 'val': 0},
502
+ })
503
+
504
+ ports = {
505
+ # name: width
506
+ 'TX_DATA_I': 64,
507
+ 'TX_RESET_I': 1,
508
+ 'TX_PCS_RESET_I': 1,
509
+ 'TX_PMA_RESET_I': 1,
510
+ 'PLL_RESET_I': 1,
511
+ 'TX_POWER_DOWN_N_I': 1,
512
+ 'TX_POLARITY_I': 1,
513
+ 'TX_PRBS_SEL_I': 3,
514
+ 'TX_PRBS_FORCE_ERR_I': 1,
515
+ 'TX_8B10B_EN_I': 1,
516
+ 'TX_8B10B_BYPASS_I': 8,
517
+ 'TX_CHAR_IS_K_I': 8,
518
+ 'TX_CHAR_DISPMODE_I': 8,
519
+ 'TX_CHAR_DISPVAL_I': 8,
520
+ 'TX_ELEC_IDLE_I': 1,
521
+ 'TX_DETECT_RX_I': 1,
522
+ 'LOOPBACK_I': 3,
523
+ 'TX_CLK_I': 1,
524
+ 'RX_CLK_I': 1,
525
+ 'RX_RESET_I': 1,
526
+ 'RX_PMA_RESET_I': 1,
527
+ 'RX_EQA_RESET_I': 1,
528
+ 'RX_CDR_RESET_I': 1,
529
+ 'RX_PCS_RESET_I': 1,
530
+ 'RX_BUF_RESET_I': 1,
531
+ 'RX_POWER_DOWN_N_I': 1,
532
+ 'RX_POLARITY_I': 1,
533
+ 'RX_PRBS_SEL_I': 3,
534
+ 'RX_PRBS_CNT_RESET_I': 1,
535
+ 'RX_8B10B_EN_I': 1,
536
+ 'RX_8B10B_BYPASS_I': 8,
537
+ 'RX_EN_EI_DETECTOR_I': 1,
538
+ 'RX_COMMA_DETECT_EN_I': 1,
539
+ 'RX_SLIDE_I': 1,
540
+ 'RX_MCOMMA_ALIGN_I': 1,
541
+ 'RX_PCOMMA_ALIGN_I': 1,
542
+ 'REGFILE_CLK_I': 1,
543
+ 'REGFILE_WE_I': 1,
544
+ 'REGFILE_EN_I': 1,
545
+ 'REGFILE_ADDR_I': 8,
546
+ 'REGFILE_DI_I': 16,
547
+ 'REGFILE_MASK_I': 16,
548
+ 'RX_DATA_O': 64,
549
+ 'RX_NOT_IN_TABLE_O': 8,
550
+ 'RX_CHAR_IS_COMMA_O': 8,
551
+ 'RX_CHAR_IS_K_O': 8,
552
+ 'RX_DISP_ERR_O': 8,
553
+ 'TX_DETECT_RX_DONE_O': 1,
554
+ 'TX_DETECT_RX_PRESENT_O': 1,
555
+ 'TX_BUF_ERR_O': 1,
556
+ 'TX_RESET_DONE_O': 1,
557
+ 'RX_PRBS_ERR_O': 1,
558
+ 'RX_BUF_ERR_O': 1,
559
+ 'RX_BYTE_IS_ALIGNED_O': 1,
560
+ 'RX_BYTE_REALIGN_O': 1,
561
+ 'RX_RESET_DONE_O': 1,
562
+ 'RX_EI_EN_O': 1,
563
+ 'RX_CLK_O': 1,
564
+ 'PLL_CLK_O': 1,
565
+ 'REGFILE_DO_O': 16,
566
+ 'REGFILE_RDY_O': 1
567
+ }
568
+
569
+ olclkg = { # open loop clock generator
570
+ # fcntrl : N
571
+ 0: 1, 1: 2, 2: 3, 3: 3.5,
572
+ 4: 3.5, 5: 3.75, 6: 4, 7: 4,
573
+ 8: 4.5, 9: 5.25, 10: 5, 11: 5.5,
574
+ 12: 5.5, 13: 5.75, 14: 6, 15: 6,
575
+ 16: 6, 17: 7, 18: 6, 19: 7,
576
+ 20: 7, 21: 7.5, 22: 8, 23: 8,
577
+ 24: 9, 25: 10.5, 26: 10, 27: 11,
578
+ 28: 11, 29: 11.5, 30: 12, 31: 12,
579
+ 32: 9, 33: 10.5, 34: 9, 35: 10.5,
580
+ 36: 10.5, 37: 11.25, 38: 12, 39: 12,
581
+ 40: 13.5, 41: 15.75, 42: 15, 43: 16.5,
582
+ 44: 16.5, 45: 17.25, 46: 18, 47: 18,
583
+ 48: 12, 49: 14, 50: 12, 51: 14,
584
+ 52: 14, 53: 15.75, 54: 16.5, 55: 16.5,
585
+ 56: 18, 57: 21, 58: 20, 59: 22,
586
+ 60: 22, 61: 23, 62: 24, 63: 24,
587
+ }
588
+
589
+ # keywords for conditional coloring
590
+ pos_cond = ["DONE", "PRESENT", "LOCKED", "IS_ALIGNED", "EN_ADPLL_CTRL", "CONFIG_SEL", "SERDES_ENABLE"]
591
+ neg_cond = ["ERR", "DOWN", "TESTMODE"]
592
+ ovr_cond = ["OVR"]
593
+
594
+ # PFDAC settings
595
+ ADPLL_PFDAC_TIMER = 12
596
+ ADPLL_PFDAC_COR_DLY = 1
597
+ ADPLL_PFDAC_CP_MIN = 6
598
+ ADPLL_PFDAC_CP_MAX = 30
599
+ ADPLL_PFDAC_CP_START = 6
600
+ ADPLL_PFDAC_CAL_SIGN = 1
601
+ ADPLL_PFDAC_AUTO_CAL = 1
602
+
603
+ # Thread-safe lock for updating values
604
+ param_lock = threading.Lock()
605
+
606
+ def __init__(self, args, jtag, hwinit):
607
+ if hwinit:
608
+ self._jtag = jtag
609
+ self._board = args.board
610
+ if self._jtag is not None:
611
+ self.configure()
612
+
613
+ def configure(self):
614
+ if self._board == Boards_e[0]: # auto
615
+ self._jtag.configure(FindAndFormatFtdiAddr(0))
616
+ elif self._board == Boards_e[1]: # pgm
617
+ self._jtag.configure('ftdi://ftdi:232h/1')
618
+ elif self._board == Boards_e[2]: # evb
619
+ self._jtag.configure('ftdi://ftdi:2232h/1')
620
+
621
+ self._jtag.reset()
622
+ self._tool = JtagTool(self._jtag)
623
+
624
+ def rd_id(self):
625
+ self._tool.idcode()
626
+
627
+ def wr_cfg(self, bitfile):
628
+ self._tool.wr_cfg(bitfile)
629
+
630
+ def gen_module_vlog(self, filename):
631
+ print(f'Generate verilog template: {filename}')
632
+ with open(filename, 'w') as file:
633
+ file.write('// CC_SERDES instance generator\n')
634
+ file.write(f'// generated: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
635
+ file.write('\n')
636
+ file.write('CC_SERDES #(\n')
637
+ for idx, (param, data) in enumerate(self.regfile.fields.items()):
638
+ end = '' if idx == len(self.regfile.fields.items())-1 else ','
639
+ if data['mode'] != 'R':
640
+ width = data['hbit']-data['lbit']+1
641
+ file.write(f' .{param}({width}\'h{data['val']:X}){end}\n')
642
+ file.write(') i_cc_serdes (\n')
643
+ for idx, (port, width) in enumerate(self.ports.items()):
644
+ end = '' if idx == len(self.ports.items())-1 else ','
645
+ if port.endswith('_I'):
646
+ file.write(f' .{port}({width}\'h{0:X}){end}\n')
647
+ else: # port.endswith('_O'):
648
+ file.write(f' .{port}(){end}\n')
649
+ file.write(');\n')
650
+
651
+ def gen_module_vhdl(self, filename):
652
+ print(f'Generate VHDL template: {filename}')
653
+ with open(filename, 'w') as file:
654
+ file.write('-- CC_SERDES instance generator\n')
655
+ file.write(f'-- generated: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
656
+ # component
657
+ file.write('\n')
658
+ file.write('component CC_SERDES is\n')
659
+ file.write('generic (\n')
660
+ for idx, (param, data) in enumerate(self.regfile.fields.items()):
661
+ end = '' if (idx == len(self.regfile.fields.items())-1) else ';'
662
+ if data['mode'] != 'R':
663
+ hbit = data['hbit']-data['lbit']
664
+ file.write(f' {param} : bit_vector({hbit} downto 0){end}\n')
665
+ file.write(');\n')
666
+ file.write('port (\n')
667
+ for idx, (port, width) in enumerate(self.ports.items()):
668
+ end = '' if idx == len(self.ports.items())-1 else ';'
669
+ if port.endswith('_I'):
670
+ if width > 1:
671
+ file.write(f' {port} : in std_logic_vector({width-1} downto 0){end}\n')
672
+ else:
673
+ file.write(f' {port} : in std_logic{end}\n')
674
+ else: # port.endswith('_O'):
675
+ if width > 1:
676
+ file.write(f' {port} : out std_logic_vector({width-1} downto 0){end}\n')
677
+ else:
678
+ file.write(f' {port} : out std_logic{end}\n')
679
+ file.write(');\n')
680
+ file.write('end component;\n')
681
+ # instance
682
+ file.write('\n')
683
+ file.write('i_cc_serdes: CC_SERDES\n')
684
+ file.write('generic map (\n')
685
+ for idx, (param, data) in enumerate(self.regfile.fields.items()):
686
+ end = '' if (idx == len(self.regfile.fields.items())-1) else ','
687
+ if data['mode'] != 'R':
688
+ width = data['hbit']-data['lbit']+1
689
+ file.write(f' {param} => {width}X"{data['val']:X}"{end}\n')
690
+ file.write(')\n')
691
+ file.write('port map (\n')
692
+ for idx, (port, width) in enumerate(self.ports.items()):
693
+ end = '' if idx == len(self.ports.items())-1 else ','
694
+ if port.endswith('_I'):
695
+ if width > 1:
696
+ file.write(f' {port} => (others => \'0\'){end}\n')
697
+ else:
698
+ file.write(f' {port} => \'{0}\'{end}\n')
699
+ else: # port.endswith('_O'):
700
+ file.write(f' {port} => open{end}\n')
701
+ file.write(');\n')
702
+
703
+ def fprint(self, key, value, line):
704
+ if any(cond in key for cond in self.pos_cond) and int(value) != 0:
705
+ print(bcolors.OK + line + bcolors.RESET)
706
+ elif any(cond in key for cond in self.pos_cond) and int(value) == 0:
707
+ print(bcolors.WARN + line + bcolors.RESET)
708
+ elif any(cond in key for cond in self.neg_cond) and (int(value) < 1 if key.endswith('_N') else int(value) > 0):
709
+ print(bcolors.FAIL + line + bcolors.RESET)
710
+ elif any(cond in key for cond in self.ovr_cond) and int(value) > 0:
711
+ print(bcolors.OVR + line + bcolors.RESET)
712
+ else:
713
+ print(line)
714
+
715
+ def rd_regfile(self, addr) -> int:
716
+ self._tool.wr_serdes_regfile(addr=addr, data=0, mask=0, wren=0)
717
+ return self._tool.rd_serdes_regfile()
718
+
719
+ def wr_regfile(self, addr, data, mask):
720
+ self._tool.wr_serdes_regfile(addr=addr, data=data, mask=mask, wren=1)
721
+ self._tool.rd_serdes_regfile()
722
+
723
+ def rd_regfile_rx(self, verbose=0):
724
+ for addr in range(0x00, 0x30):
725
+ word = self.rd_regfile(addr)
726
+ if verbose == 1:
727
+ print(f'{addr:02X}: 0x{int(word):04X}')
728
+ elif verbose == 2:
729
+ filtered_entries = {key: value for key, value in self.regfile.fields.items() if value['addr'] == addr}
730
+ for (key, value) in filtered_entries.items():
731
+ v = word[value['lbit']:value['hbit']+1]
732
+ line = f'{key:24} {int(v):4X}\'h {int(v):6}\'d'
733
+ self.fprint(key, v, line)
734
+
735
+ def rd_regfile_rx_data(self):
736
+ rxd_80bit = BitSequence()
737
+ for addr in range(0x20, 0x25):
738
+ rxd_80bit += self.rd_regfile(addr)
739
+ rxd_64bit = rxd_80bit[0:7+1] + rxd_80bit[10:17+1] + rxd_80bit[20:27+1] + rxd_80bit[30:37+1] + rxd_80bit[40:47+1] + rxd_80bit[50:57+1] + rxd_80bit[60:67+1] + rxd_80bit[70:77+1]
740
+ return rxd_64bit, rxd_80bit
741
+
742
+ def print_regfile_rx_data(self, verbose=0):
743
+ rx_data_80bit = 0
744
+ word_idx = 0
745
+ for addr in range(0x20, 0x25):
746
+ word = self.rd_regfile(addr)
747
+ if verbose == 1:
748
+ print(f'{addr:02X}: 0x{int(word):04X}')
749
+ rx_fields = {
750
+ key: field for key, field in self.regfile.fields.items()
751
+ if field['addr'] == addr and key.startswith('RX_DATA[')
752
+ }
753
+ for field_name, field_info in rx_fields.items():
754
+ # Extract the relevant bits from the word
755
+ bit_slice = word[field_info['lbit']:field_info['hbit'] + 1]
756
+ rx_data_80bit |= int(bit_slice) << (16 * word_idx)
757
+ word_idx += 1
758
+
759
+ if verbose == 2:
760
+ print(f'{"RX_DATA[79:0]":24} {rx_data_80bit:020X}\'h')
761
+
762
+ # Convert to 64-bit format by packing every 10 bits into bytes
763
+ rx_data_64bit = 0
764
+ byte_position = 0
765
+ for bit_offset in range(0, 80, 10):
766
+ byte_value = (rx_data_80bit >> bit_offset) & 0xFF
767
+ rx_data_64bit |= byte_value << (byte_position * 8)
768
+ byte_position += 1
769
+
770
+ if verbose == 2:
771
+ print(f'{"RX_DATA[63:0]":24} {rx_data_64bit:016X}\'h')
772
+
773
+ return rx_data_64bit, rx_data_80bit
774
+
775
+ def wr_regfile_tx_data(self, data):
776
+ self.wr_regfile(addr=0x41, data=0x1000, mask=0x1F00) # TX_DATA_OVR=1, TX_DATA_CNT=0, TX_DATA_VALID=0
777
+ for i in range(5):
778
+ self.wr_regfile(addr=0x42, data=(data >> 16*i) & 0xFFFF, mask=0xFFFF) # auto inc
779
+ self.wr_regfile(addr=0x41, data=0x1B00, mask=0x1F00) # TX_DATA_OVR=1, TX_DATA_CNT=5, TX_DATA_VALID=1
780
+
781
+ def rd_regfile_tx(self, verbose=0):
782
+ for addr in range(0x30, 0x43): # 0x43..0x4F unused
783
+ word = self.rd_regfile(addr)
784
+ if verbose == 1:
785
+ print(f'{addr:02X}: 0x{int(word):04X}')
786
+ elif verbose == 2:
787
+ filtered_entries = {key: value for key, value in self.regfile.fields.items() if value['addr'] == addr}
788
+ for (key, value) in filtered_entries.items():
789
+ v = word[value['lbit']:value['hbit']+1]
790
+ line = f'{key:24} {int(v):4X}\'h {int(v):6}\'d'
791
+ self.fprint(key, v, line)
792
+
793
+ def rd_regfile_pll(self, verbose=0):
794
+ for addr in range(0x50, 0x5D):
795
+ word = self.rd_regfile(addr)
796
+ if verbose == 1:
797
+ print(f'{addr:02X}: 0x{int(word):04X}')
798
+ elif verbose == 2:
799
+ filtered_entries = {key: value for key, value in self.regfile.fields.items() if value['addr'] == addr}
800
+ for (key, value) in filtered_entries.items():
801
+ v = word[value['lbit']:value['hbit']+1]
802
+ line = f'{key:24} {int(v):4X}\'h {int(v):6}\'d'
803
+ self.fprint(key, v, line)
804
+
805
+ def rd_regfile_pll_div_settings(self):
806
+ word = self.rd_regfile(addr=0x51)
807
+ FCNTRL = word[0:5+1]
808
+ MAIN_DIVSEL = word[6:11+1]
809
+ OUT_DIVSEL = word[12:13+1]
810
+ n1 = MAIN_DIVSEL[2]
811
+ n2 = MAIN_DIVSEL[0:1+1]
812
+ n3 = MAIN_DIVSEL[3:4+1]
813
+ return n1, n2, n3, OUT_DIVSEL
814
+
815
+ def rd_regfile_pll_status(self):
816
+ return self.rd_regfile(addr=0x55) + self.rd_regfile(addr=0x56)
817
+
818
+ def rd_regfile_pll_bisc_status(self):
819
+ return self.rd_regfile(addr=0x5A) + self.rd_regfile(addr=0x5B)
820
+
821
+ def reset_serdes_tx(self):
822
+ print('INFO: Resetting SerDes TX')
823
+
824
+ word = self.rd_regfile(addr=0x5C)
825
+ if (word[0] != 1 or word[2] != 1):
826
+ print(f'ERROR: SerDes not enabled or in testmode. 0x5C=0x{int(word):04X}')
827
+ return
828
+
829
+ # TX reset
830
+ self.wr_regfile(addr=0x3F, data=0xC000, mask=0xC000) # TX_RESET_OVR=1, TX_RESET=1
831
+ self.wr_regfile(addr=0x3F, data=0x0000, mask=0xC000) # TX_RESET_OVR=0, TX_RESET=0
832
+ word = self.rd_regfile(addr=0x41)
833
+ timeout = 5
834
+ while timeout > 0:
835
+ if (int(word[14]) != 1): # TX_RESET_DONE
836
+ timeout = timeout - 1
837
+ if timeout == 0:
838
+ print(f'ERROR: TX_RESET_DONE timeout')
839
+ else:
840
+ break
841
+
842
+ def set_serdes_datapath(self, mode=80):
843
+ if mode == 0 or mode == 20:
844
+ self.wr_regfile(addr=0x2A, data=0x0000, mask=0x000C) # RX_DATAPATH_SEL=0
845
+ self.wr_regfile(addr=0x40, data=0x0000, mask=0x0018) # TX_DATAPATH_SEL=0 (16/20)
846
+ elif mode == 1 or mode == 40:
847
+ datapath_sel = 1
848
+ self.wr_regfile(addr=0x2A, data=0x0001, mask=0x000C) # RX_DATAPATH_SEL=1
849
+ self.wr_regfile(addr=0x40, data=0x0008, mask=0x0018) # TX_DATAPATH_SEL=1 (32/40)
850
+ elif mode == 2 or mode == 3 or mode == 80:
851
+ datapath_sel = 3
852
+ self.wr_regfile(addr=0x2A, data=0x000C, mask=0x000C) # RX_DATAPATH_SEL=3
853
+ self.wr_regfile(addr=0x40, data=0x0018, mask=0x0018) # TX_DATAPATH_SEL=3 (64/80)
854
+ else:
855
+ print(f'ERROR: Invalid datapath configruation {mode}')
856
+
857
+ def check_serdes_datapath(self, mode):
858
+ check = 3 if mode == 80 else 1 if mode == 40 else 0 if mode == 20 else mode
859
+ word = self.rd_regfile(addr=0x2A)
860
+ if (int(word[2:3+1]) != check):
861
+ print(f'ERROR: RX_DATAPATH_SEL != {check} ({int(word[2:3+1]):2X})')
862
+ word = self.rd_regfile(addr=0x40)
863
+ if (int(word[3:4+1]) != check):
864
+ print(f'ERROR: TX_DATAPATH_SEL != {check} ({int(word[3:4+1]):2X})')
865
+
866
+ def reset_serdes_rx(self):
867
+ print('INFO: Resetting SerDes RX')
868
+
869
+ word = self.rd_regfile(addr=0x5C)
870
+ if (word[0] != 1 or word[2] != 1):
871
+ print(f'ERROR: SerDes not enabled or in testmode. 0x5C=0x{int(word):04X}')
872
+ return
873
+
874
+ # RX reset
875
+ self.wr_regfile(addr=0x2B, data=0x0003, mask=0x0003) # RX_RESET_OVR=1, RX_RESET=1
876
+ self.wr_regfile(addr=0x3F, data=0x0000, mask=0x0003) # RX_RESET_OVR=0, RX_RESET=0
877
+ word = self.rd_regfile(addr=0x2C)
878
+ timeout = 5
879
+ while timeout > 0:
880
+ if (int(word[10]) != 1): # RX_RESET_DONE
881
+ timeout = timeout - 1
882
+ if timeout == 0:
883
+ print(f'ERROR: RX_RESET_DONE timeout')
884
+ else:
885
+ break
886
+
887
+ def reset_serdes_trx(self):
888
+ self.reset_serdes_tx()
889
+ self.reset_serdes_rx()
890
+
891
+ def start_serdes_pll(self, n1=1, n2=2, n3=3, outdiv=4, calib=False):
892
+ print('INFO: Configuring SerDes ADPLL')
893
+
894
+ if (n1 < 1 or n1 > 2):
895
+ print(f'ERROR: Main divider N1 is out of range 1..2')
896
+ return
897
+ if (n2 < 2 or n2 > 5):
898
+ print(f'ERROR: Main divider N2 is out of range 2..5')
899
+ return
900
+ if (n3 < 3 or n3 > 5):
901
+ print(f'ERROR: Main divider N3 is out of range 3..5')
902
+ return
903
+ if (outdiv != 1 and outdiv != 2 and outdiv != 4):
904
+ print(f'ERROR: Output divider N3 is limited to 1, 2 or 4')
905
+ return
906
+
907
+ dco = 1000.0 / SER_CLK_PERIOD_NS * n1 * n2 * n3
908
+ freq = dco / outdiv
909
+ print(f'INFO: SerDes ADPLL frequency / data rate is {freq} MHz / {freq*2} Mbit/s')
910
+
911
+ status = self.rd_regfile_pll_status()
912
+ if (status[0] == 1):
913
+ print('INFO: Disabling SerDes ADPLL')
914
+ self.wr_regfile(addr=0x50, data=0x0000, mask=0x0001)
915
+
916
+ if outdiv == 1:
917
+ pll_div = 0x0000
918
+ elif outdiv == 2:
919
+ pll_div = 0x1000
920
+ else:
921
+ pll_div = 0x3000
922
+ if n2 == 5:
923
+ pll_div = (pll_div & ~(0b11 << 6)) | (0b11 << 6)
924
+ elif n2 == 4:
925
+ pll_div = (pll_div & ~(0b11 << 6)) | (0b10 << 6)
926
+ elif n2 == 2:
927
+ pll_div = (pll_div & ~(0b11 << 6)) | (0b01 << 6)
928
+ if n1 == 2:
929
+ pll_div |= (1 << 8)
930
+ if n3 == 5:
931
+ pll_div = (pll_div & ~(0b11 << 9)) | (0b11 << 9)
932
+ elif n3 == 4:
933
+ pll_div = (pll_div & ~(0b11 << 9)) | (0b10 << 9)
934
+
935
+ print('INFO: Writing SerDes ADPLL divider settings')
936
+ self.wr_regfile(addr=0x51, data=pll_div, mask=0x3FC0)
937
+
938
+ if (calib):
939
+ print('INFO: Stopping SerDes ADPLL self-calibration')
940
+ self.wr_regfile(addr=0x57, data=0x0004, mask=0x0007)
941
+ self.wr_regfile(addr=0x57, data=
942
+ ((self.ADPLL_PFDAC_TIMER & 0x000F) << 3) |
943
+ ((self.ADPLL_PFDAC_COR_DLY & 0x0007) << 10) |
944
+ ((self.ADPLL_PFDAC_CAL_SIGN & 0x0001) << 13) |
945
+ ((self.ADPLL_PFDAC_AUTO_CAL & 0x0001) << 14),
946
+ mask=0xFFF8)
947
+ self.wr_regfile(addr=0x58, data=
948
+ ((self.ADPLL_PFDAC_COR_DLY & 0x001F) << 0) |
949
+ ((self.ADPLL_PFDAC_CAL_SIGN & 0x001F) << 5) |
950
+ ((self.ADPLL_PFDAC_AUTO_CAL & 0x001F) << 10),
951
+ mask=0xFFFF)
952
+
953
+ print('INFO: Starting SerDes ADPLL')
954
+ self.wr_regfile(addr=0x50, data=0x0002, mask=0x0007)
955
+ self.wr_regfile(addr=0x50, data=0x0003, mask=0x0003)
956
+
957
+ if (calib):
958
+ print('INFO: Starting SerDes ADPLL self-calibration')
959
+ self.wr_regfile(addr=0x57, data=0x0004, mask=0x0007)
960
+ self.wr_regfile(addr=0x57, data=0x0005, mask=0x0007) # BISC mode B, enable
961
+
962
+ timeout = 5
963
+ while timeout > 0:
964
+ sleep(0.5)
965
+ status = self.rd_regfile_pll_status()
966
+ if (status[0] == 0):
967
+ timeout = timeout - 1
968
+ print(f'INFO: LCK: {int(status[0]):1d} FTO: {int(status[1]):1d} FTU: {int(status[2]):1d} FT: {int(status[3:12+1]):4d} SY: {int(status[16:23+1]):3d} ST: {int(status[13:14+1]):1d}')
969
+ if timeout == 0:
970
+ print(f'ERROR: SerDes ADPLL lock timeout')
971
+ else:
972
+ print(f'INFO: SerDes ADPLL locked')
973
+ break
974
+
975
+ if (calib):
976
+ result = self.rd_regfile_pll_bisc_status()
977
+ print(f'INFO: PFDAC result: max reached: {int(result[0]):1d}, ac_result: {int(result[1:17+1]):6d}, CP: {int(result[18:22+1]):2d}')
978
+
979
+ print(f'INFO: ADPLL status: LCK: {int(status[0]):1d} FTO: {int(status[1]):1d} FTU: {int(status[2]):1d} FT: {int(status[3:12+1]):4d} SY: {int(status[16:23+1]):3d} ST: {int(status[13:14+1]):1d}')
980
+
981
+ def tc_prbs(self, force_err=False):
982
+ print(f'INFO: Starting SerDes PRBS testcases')
983
+
984
+ word = self.rd_regfile(addr=0x5C)
985
+ if (word[0] != 1 or word[2] != 1):
986
+ print(f'ERROR: SerDes not enabled or in testmode. 0x5C=0x{int(word):04X}')
987
+ return
988
+
989
+ # set 80-bit datapath
990
+ self.set_serdes_datapath(80)
991
+
992
+ self.start_serdes_pll(n1=1, n2=5, n3=5, outdiv=4, calib=True) # 1250 Mbit/s, PFDAC=on
993
+ self.reset_serdes_trx()
994
+
995
+ # check datapath
996
+ self.check_serdes_datapath(80)
997
+
998
+ # disable testmode?
999
+ self.wr_regfile(addr=0x2A, data=0x0210, mask=0x02F0) # RX_PRBS_OVR=1, RX_PRBS_SEL=0, RX_PRBS_CNT_RESET=1
1000
+
1001
+ for i in range(0, 2):
1002
+ prbs = 7 if i == 0 else 15 if i == 1 else 23 if i == 2 else 31 if i == 3 else 0
1003
+ print(f'INFO: Setting up PRBS-{prbs}')
1004
+
1005
+ self.wr_regfile(addr=0x40, data=((i+1) << 6) | (1 << 5), mask=0x01E0) # TX_PRBS_OVR=1, TX_PRBS_SEL=i
1006
+ word = self.rd_regfile(addr=0x40)
1007
+ #if (word[5] == 1):
1008
+ # print(f'ERROR: TX PRBS overwrite is not disabled')
1009
+ if (int(word[6:8+1]) != i+1):
1010
+ print(f'ERROR: TX PRBS mode is invalid')
1011
+
1012
+ self.wr_regfile(addr=0x2A, data=((i+1) << 5) | (1 << 4), mask=0x00F0) # RX_PRBS_OVR=1, RX_PRBS_SEL=i
1013
+ word = self.rd_regfile(addr=0x2A)
1014
+ #if (word[4] == 1):
1015
+ # print(f'ERROR: RX PRBS overwrite is not disabled')
1016
+ if (word[9] == 1):
1017
+ print(f'ERROR: RX_PRBS_CNT_RESET is active')
1018
+ if (int(word[5:7+1]) != i+1):
1019
+ print(f'ERROR: RX PRBS mode is invalid')
1020
+
1021
+ # send data
1022
+ print(f'INFO: Sending data (this might take a while) ...')
1023
+ n = 10
1024
+ for i in range(n):
1025
+ print(f'INFO: {i}/{n}')
1026
+ sleep(1)
1027
+
1028
+ word = self.rd_regfile(addr=0x1F)
1029
+ print(f'INFO: RX_PRBS_LOCKED: {int(word[15]):1d}, RX_PRBS_ERR_CNT: {int(word[0:14+1]):X}')
1030
+ if (word[15] == 0):
1031
+ print(f'ERROR: RX PRBS did not lock')
1032
+ if (int(word[0:14+1]) > 0):
1033
+ print(f'ERROR: RX PRBS errors detected ({int(word[0:14+1])})')
1034
+
1035
+ if (force_err):
1036
+ print(f'INFO: Starting error injection')
1037
+ self.wr_regfile(addr=0x40, data=0x0200, mask=0x0200) # TX_PRBS_FORCE_ERR=1
1038
+ word = self.rd_regfile(addr=0x1F)
1039
+ print(f'INFO: RX_PRBS_LOCKED: {int(word[15]):1d}, RX_PRBS_ERR_CNT: {int(word[0:14+1]):X}')
1040
+ if (int(word[0:14+1]) == 0):
1041
+ print(f'ERROR: RX PRBS error detection failed')
1042
+
1043
+ self.wr_regfile(addr=0x2A, data=0x0210, mask=0x02F0) # RX_PRBS_CNT_RESET=1, RX_PRBS_OVR=1, RX_PRBS_SEL=0
1044
+ self.wr_regfile(addr=0x40, data=0x0020, mask=0x01E0) # TX_PRBS_OVR=1, TX_PRBS_SEL=0
1045
+ return
1046
+
1047
+ def tc_uipattern(self, mode=0):
1048
+ print(f'INFO: Starting SerDes UI pattern testcase')
1049
+
1050
+ if not mode in [0,2,20,40,80]:
1051
+ print(f'ERROR: Invalid UI pattern mode ({mode}), must be in [0,2,20,40,80]')
1052
+ return
1053
+
1054
+ word = self.rd_regfile(addr=0x5C)
1055
+ if (word[0] != 1 or word[2] != 1):
1056
+ print(f'ERROR: SerDes not enabled or in testmode. 0x5C=0x{int(word):04X}')
1057
+ return
1058
+
1059
+ # set datapath if mode in [20,40,80]
1060
+ self.set_serdes_datapath(mode)
1061
+
1062
+ self.start_serdes_pll(n1=1, n2=2, n3=3, outdiv=4, calib=True) # 300 Mbit/s, PFDAC=on
1063
+ self.reset_serdes_trx()
1064
+
1065
+ # check datapath
1066
+ self.check_serdes_datapath(mode)
1067
+
1068
+ # disable testmode?
1069
+ self.wr_regfile(addr=0x2A, data=0x0210, mask=0x02F0) # RX_PRBS_OVR=1, RX_PRBS_SEL=0, RX_PRBS_CNT_RESET=1
1070
+
1071
+ print(f'INFO: Setting up {mode} UI square wave')
1072
+
1073
+ i = 5 if mode == 2 else 6 if mode in [20,40,80] else 0
1074
+ self.wr_regfile(addr=0x40, data=((i+1) << 6) | (1 << 5), mask=0x01E0) # TX_PRBS_OVR=1, TX_PRBS_SEL=i
1075
+ word = self.rd_regfile(addr=0x40)
1076
+ if (int(word[6:8+1]) != i+1):
1077
+ print(f'ERROR: TX PRBS mode is invalid')
1078
+
1079
+ def tc_eyemeas(self):
1080
+ print(f'INFO: Starting SerDes eye measurement')
1081
+
1082
+ word = self.rd_regfile(addr=0x5C)
1083
+ if (word[0] != 1 or word[2] != 1):
1084
+ print(f'ERROR: SerDes not enabled or in testmode. 0x5C=0x{int(word):04X}')
1085
+ return
1086
+
1087
+ def tc_loopback(self):
1088
+ print(f'INFO: Starting SerDes loopback testcases')
1089
+
1090
+ word = self.rd_regfile(addr=0x5C)
1091
+ if (word[0] != 1 or word[2] != 1):
1092
+ print(f'ERROR: SerDes not enabled or in testmode. 0x5C=0x{int(word):04X}')
1093
+ return
1094
+
1095
+ # testcases:
1096
+ #
1097
+ # 0: TX PMA (near-end, mode 1: pre-driver), TX_PMA_LOOPBACK=01 or TX_PMA_LOOPBACK=11
1098
+ # 1: TX PMA (near-end, mode 2: pad), TX_PMA_LOOPBACK=10, NOTE: requires termination!
1099
+ # 3: TX PCS (near-end)
1100
+ for j in [0, 1, 3]:
1101
+ if (j < 3):
1102
+ print(f'\nINFO: Enabling TX PMA Loopback (Mode {j:1d})')
1103
+ else:
1104
+ print(f'\nINFO: Enabling TX PCS Loopback')
1105
+
1106
+ # TX_LOOPBACK_OVR=1 | TX_PMA_LOOPBACK=(001=pma-drv, 011=pma-drv, 010=pma-pad, 100=pcs)
1107
+ self.wr_regfile(addr=0x40, data=(0x0400 | (j+1) & 0x7), mask=0x0407)
1108
+ word = self.rd_regfile(addr=0x40)
1109
+ if (word[10] == 0):
1110
+ print(f'ERROR: TX loopback overwrite is not enabled')
1111
+ if (int(word[0:1+1]) != j+1 and j < 3):
1112
+ print(f'ERROR: TX PMA loopback is not enabled')
1113
+ if (word[2] == 0 and j == 3):
1114
+ print(f'ERROR: TX PCS loopback is not enabled')
1115
+
1116
+ # turn tx driver off
1117
+ if (j == 1 or j == 3):
1118
+ self.wr_regfile(addr=0x30, data=0x0000, mask=0x001F) # TODO TX_SEL_PRE=0, TX_SEL_POST=x, TX_AMP=x
1119
+ self.wr_regfile(addr=0x31, data=0x07E0, mask=0x07E0) # TX_BRANCH_EN_MAIN=63
1120
+ word = self.rd_regfile(addr=0x30)
1121
+ if (int(word[0:4+1]) != 0):
1122
+ print(f'ERROR: Invalid TX_SEL_PRE driver setting')
1123
+ word = self.rd_regfile(addr=0x31)
1124
+ if (int(word[5:10+1]) != 63):
1125
+ print(f'ERROR: Invalid TX_BRANCH_EN_MAIN setting')
1126
+ else:
1127
+ self.wr_regfile(addr=0x30, data=0x0001, mask=0x001F) # TODO TX_SEL_PRE=1, TX_SEL_POST=x, TX_AMP=x
1128
+ self.wr_regfile(addr=0x31, data=0x0000, mask=0x07E0) # TX_BRANCH_EN_MAIN=0
1129
+ word = self.rd_regfile(addr=0x30)
1130
+ if (int(word[0:4+1]) != 1):
1131
+ print(f'ERROR: Invalid TX_SEL_PRE driver setting')
1132
+ word = self.rd_regfile(addr=0x31)
1133
+ if (int(word[5:10+1]) != 0):
1134
+ print(f'ERROR: Invalid TX_BRANCH_EN_MAIN setting')
1135
+
1136
+ self.start_serdes_pll(n1=1, n2=5, n3=5, outdiv=4, calib=True) # 1250 Mbit/s, PFDAC=on
1137
+ self.reset_serdes_trx()
1138
+
1139
+ self.wr_regfile(addr=0x41, data=0x00C0, mask=0x00C0) # TX_8B10B_EN_OVR=1, TX_8B10B_EN=1
1140
+ self.wr_regfile(addr=0x2B, data=0xC000, mask=0xC000) # RX_8B10B_EN_OVR=1, RX_8B10B_EN=1
1141
+
1142
+ # 32-Bit comma alignment test
1143
+ self.wr_regfile(addr=0x12, data=0x3000, mask=0x3000) # RX_ALIGN_COMMA_WORD=3 (32 bit)
1144
+
1145
+ # NOTE: Please define position of the k-word using the `TX_CHAR_IS_K_I` input: set to 8'h0000_0001
1146
+ self.wr_regfile_tx_data(data=0x1284A1284A1284A128BC) # 64'h4A4A4A4A_4A4A4ABC
1147
+
1148
+ self.wr_regfile(addr=0x11, data=0x0C00, mask=0x0C00) # RX_MCOMMA_ALIGN_OVR=1, RX_MCOMMA_ALIGN=1
1149
+ self.wr_regfile(addr=0x12, data=0x0C00, mask=0x0C00) # RX_PCOMMA_ALIGN_OVR=1, RX_PCOMMA_ALIGN=1
1150
+ self.wr_regfile(addr=0x13, data=0x3000, mask=0x3000) # RX_COMMA_DETECT_EN_OVR=1, RX_COMMA_DETECT_EN=1
1151
+
1152
+ print(f'INFO: Sending data (this might take a while) ...')
1153
+ sleep(2)
1154
+
1155
+ self.wr_regfile(addr=0x11, data=0x0000, mask=0x0C00) # RX_MCOMMA_ALIGN_OVR=1, RX_MCOMMA_ALIGN=0
1156
+ self.wr_regfile(addr=0x12, data=0x0000, mask=0x0C00) # RX_PCOMMA_ALIGN_OVR=1, RX_PCOMMA_ALIGN=0
1157
+
1158
+ print(f'INFO: Checking 32-Bit comma alignment')
1159
+ rx_data, _ = self.rd_regfile_rx_data()
1160
+ align_pos = 0 if int(rx_data[0:7+1]) == 0xBC else 1
1161
+ rx_recv = 0x4A4A4A4A4A4A4ABC if align_pos == 0 else 0x4A4A4ABC4A4A4A4A
1162
+
1163
+ if (int(rx_data[0:7+1]) != 0xBC and int(rx_data[32:39+1]) != 0xBC):
1164
+ print(f'ERROR: Comma is not aligned to 32-Bit boundary')
1165
+ if (int(rx_data) != rx_recv):
1166
+ print(f'ERROR: Invalid idle sequence received: RX_DATA[63:0]: {int(rx_data):016X}')
1167
+
1168
+ # 16-Bit comma alignment test
1169
+ self.reset_serdes_trx()
1170
+ self.wr_regfile(addr=0x12, data=0x1000, mask=0x3000) # RX_ALIGN_COMMA_WORD=1 (16 bit)
1171
+
1172
+ # NOTE: Please define position of the k-word using the `TX_CHAR_IS_K_I` input: set to 8'h0000_0001
1173
+ self.wr_regfile_tx_data(data=0x1284A1284A1284A128BC) # 64'h4A4A4A4A_4A4A4ABC
1174
+
1175
+ self.wr_regfile(addr=0x11, data=0x0C00, mask=0x0C00) # RX_MCOMMA_ALIGN_OVR=1, RX_MCOMMA_ALIGN=1
1176
+ self.wr_regfile(addr=0x12, data=0x0C00, mask=0x0C00) # RX_PCOMMA_ALIGN_OVR=1, RX_PCOMMA_ALIGN=1
1177
+ self.wr_regfile(addr=0x13, data=0x3000, mask=0x3000) # RX_COMMA_DETECT_EN_OVR=1, RX_COMMA_DETECT_EN=1
1178
+
1179
+ print(f'INFO: Sending data (this might take a while) ...')
1180
+ sleep(2)
1181
+
1182
+ self.wr_regfile(addr=0x11, data=0x0000, mask=0x0C00) # RX_MCOMMA_ALIGN_OVR=1, RX_MCOMMA_ALIGN=0
1183
+ self.wr_regfile(addr=0x12, data=0x0000, mask=0x0C00) # RX_PCOMMA_ALIGN_OVR=1, RX_PCOMMA_ALIGN=0
1184
+
1185
+ print(f'INFO: Checking 16-Bit comma alignment')
1186
+ rx_data, _ = self.rd_regfile_rx_data()
1187
+ align_pos = 0 if int(rx_data[ 0:7+1]) == 0xBC else \
1188
+ 1 if int(rx_data[16:23+1]) == 0xBC else \
1189
+ 2 if int(rx_data[32:39+1]) == 0xBC else 3
1190
+ rx_recv = 0x4A4A4A4A4A4A4ABC if align_pos == 0 else \
1191
+ 0x4A4A4A4A4ABC4A4A if align_pos == 1 else \
1192
+ 0x4A4A4ABC4A4A4A4A if align_pos == 2 else 0x4ABC4A4A4A4A4A4A
1193
+
1194
+ if (int(rx_data[0:7+1]) != 0xBC and int(rx_data[16:23+1]) != 0xBC and int(rx_data[32:39+1]) != 0xBC and int(rx_data[48:55+1]) != 0xBC):
1195
+ print(f'ERROR: Comma is not aligned to 16-Bit boundary')
1196
+ if (int(rx_data) != rx_recv):
1197
+ print(f'ERROR: Invalid idle sequence received: RX_DATA[63:0]: {int(rx_data):016X}')
1198
+
1199
+ # 8-Bit comma alignment test
1200
+ self.reset_serdes_trx()
1201
+ self.wr_regfile(addr=0x12, data=0x0000, mask=0x3000) # RX_ALIGN_COMMA_WORD=0 (8 bit)
1202
+
1203
+ # NOTE: Please define position of the k-word using the `TX_CHAR_IS_K_I` input: set to 8'h0000_0001
1204
+ self.wr_regfile_tx_data(data=0x1284A1284A1284A128BC) # 64'h4A4A4A4A_4A4A4ABC
1205
+
1206
+ self.wr_regfile(addr=0x11, data=0x0C00, mask=0x0C00) # RX_MCOMMA_ALIGN_OVR=1, RX_MCOMMA_ALIGN=1
1207
+ self.wr_regfile(addr=0x12, data=0x0C00, mask=0x0C00) # RX_PCOMMA_ALIGN_OVR=1, RX_PCOMMA_ALIGN=1
1208
+ self.wr_regfile(addr=0x13, data=0x3000, mask=0x3000) # RX_COMMA_DETECT_EN_OVR=1, RX_COMMA_DETECT_EN=1
1209
+
1210
+ print(f'INFO: Sending data (this might take a while) ...')
1211
+ sleep(2)
1212
+
1213
+ self.wr_regfile(addr=0x11, data=0x0000, mask=0x0C00) # RX_MCOMMA_ALIGN_OVR=1, RX_MCOMMA_ALIGN=0
1214
+ self.wr_regfile(addr=0x12, data=0x0000, mask=0x0C00) # RX_PCOMMA_ALIGN_OVR=1, RX_PCOMMA_ALIGN=0
1215
+
1216
+ print(f'INFO: Checking 8-Bit comma alignment')
1217
+ rx_data, _ = self.rd_regfile_rx_data()
1218
+ align_pos = 0 if int(rx_data[ 0:7+1]) == 0xBC else \
1219
+ 1 if int(rx_data[ 8:15+1]) == 0xBC else \
1220
+ 2 if int(rx_data[16:23+1]) == 0xBC else \
1221
+ 3 if int(rx_data[24:31+1]) == 0xBC else \
1222
+ 4 if int(rx_data[32:39+1]) == 0xBC else \
1223
+ 5 if int(rx_data[40:47+1]) == 0xBC else \
1224
+ 6 if int(rx_data[48:55+1]) == 0xBC else 7
1225
+ rx_recv = 0x4A4A4A4A4A4A4ABC if align_pos == 0 else \
1226
+ 0x4A4A4A4A4A4ABC4A if align_pos == 1 else \
1227
+ 0x4A4A4A4A4ABC4A4A if align_pos == 2 else \
1228
+ 0x4A4A4A4ABC4A4A4A if align_pos == 3 else \
1229
+ 0x4A4A4ABC4A4A4A4A if align_pos == 4 else \
1230
+ 0x4A4ABC4A4A4A4A4A if align_pos == 5 else \
1231
+ 0x4ABC4A4A4A4A4A4A if align_pos == 6 else 0xBC4A4A4A4A4A4A4A
1232
+
1233
+ if (int(rx_data[0:7+1]) != 0xBC and int(rx_data[ 8:15+1]) != 0xBC and int(rx_data[16:23+1]) != 0xBC and int(rx_data[24:31+1]) != 0xBC and int(rx_data[32:39+1]) != 0xBC and int(rx_data[40:47+1]) != 0xBC and int(rx_data[48:55+1]) != 0xBC and int(rx_data[56:63+1]) != 0xBC):
1234
+ print(f'ERROR: Comma is not aligned to 8-Bit boundary')
1235
+ if (int(rx_data) != rx_recv):
1236
+ print(f'ERROR: Invalid idle sequence received: RX_DATA[63:0]: {int(rx_data):016X}')
1237
+
1238
+ def calc_rxterm_vcm(self, vddio=1.0, vcmsel=None) -> float:
1239
+ if vcmsel is None:
1240
+ vcmsel = self.rd_regfile(addr=0x02)
1241
+ vcmsel = int(vcmsel[11:13+1])
1242
+ return (vcmsel/29) * vddio
1243
+
1244
+ def update_values(self):
1245
+ while True:
1246
+ sleep(0.5) # 500ms update interval
1247
+ with self.param_lock:
1248
+ #for param in self.regfile.fields:
1249
+ # self.regfile.fields[param]['val'] = random.randint(0, 16)
1250
+ for addr in chain(range(0x00, 0x30), range(0x30, 0x43), range(0x50, 0x5D)):
1251
+ word = self.rd_regfile(addr)
1252
+ filtered_entries = {key: value for key, value in self.regfile.fields.items() if value['addr'] == addr}
1253
+ for (key, value) in filtered_entries.items():
1254
+ val = word[value['lbit']:value['hbit']+1]
1255
+ self.regfile.fields[key]['val'] = int(val)
1256
+
1257
+ def draw_parameters(self, stdscr):
1258
+ curses.curs_set(0)
1259
+ stdscr.keypad(True)
1260
+ stdscr.timeout(10) #stdscr.nodelay(True) # Non-blocking input
1261
+
1262
+ # Initialize colors
1263
+ curses.start_color()
1264
+ curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) # OK (Green)
1265
+ curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) # WARN (Yellow)
1266
+ curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) # FAIL (Red)
1267
+ curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK) # OVR (Blue)
1268
+ curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLACK) # Normal text
1269
+
1270
+ def handle_resize(signum, frame):
1271
+ curses.endwin()
1272
+ stdscr.refresh()
1273
+
1274
+ signal.signal(signal.SIGWINCH, handle_resize)
1275
+
1276
+ selected_index = 0
1277
+ show_hex = False
1278
+ search_results = []
1279
+ search_index = 0
1280
+
1281
+ while True:
1282
+ max_y, max_x = stdscr.getmaxyx()
1283
+ max_name_length = max(len(name) for name in self.regfile.fields.keys())
1284
+ col_width = max_name_length + 8
1285
+ num_columns = max(1, max_x // col_width)
1286
+ num_rows = math.ceil(len(self.regfile.fields) / num_columns)
1287
+ param_list = list(self.regfile.fields.items())
1288
+
1289
+ # Extract values for bit rate calculation
1290
+ PLL_MAIN_DIVSEL = self.regfile.fields.get("PLL_MAIN_DIVSEL", {}).get("val", 0x1B)
1291
+ PLL_OUT_DIVSEL = self.regfile.fields.get("PLL_OUT_DIVSEL", {}).get("val", 0x0)
1292
+ TX_DATAPATH_SEL = self.regfile.fields.get("TX_DATAPATH_SEL", {}).get("val", 0x0)
1293
+
1294
+ # Decode PLL values
1295
+ N3 = {0b00: 3, 0b10: 4, 0b11: 5}.get((PLL_MAIN_DIVSEL >> 3) & 0b11, None)
1296
+ N1 = {0b0: 1, 0b1: 2}.get((PLL_MAIN_DIVSEL >> 2) & 0b1, None)
1297
+ N2 = {0b00: 3, 0b01: 2, 0b10: 4, 0b11: 5}.get(PLL_MAIN_DIVSEL & 0b11, None)
1298
+ OUTDIV = {0b00: 1, 0b01: 2, 0b11: 4}.get(PLL_OUT_DIVSEL, None)
1299
+
1300
+ bit_rate_clock = 2 * 100e6 * N1 * N2 * N3 / OUTDIV if None not in (N1, N2, N3, OUTDIV) else None
1301
+
1302
+ # Decode TX_DATAPATH_SEL
1303
+ datapath_mode = (TX_DATAPATH_SEL & 0b10) >> 1 # Extract MSB
1304
+ is_64_bit = datapath_mode == 1 # If `1x`, it is 64-bit
1305
+
1306
+ # Determine AddDiv based on OUTDIV
1307
+ if is_64_bit:
1308
+ AddDiv = {0b00: 2, 0b01: 4, 0b11: 8}.get(PLL_OUT_DIVSEL, None)
1309
+ else:
1310
+ AddDiv = {0b00: 1, 0b01: 2, 0b11: 4}.get(PLL_OUT_DIVSEL, None)
1311
+
1312
+ PLL_FCNTRL = self.regfile.fields.get("PLL_FCNTRL", {}).get("val", 0x0)
1313
+ data_path_clock = (100e6 * N1 * N2 * N3) / (self.olclkg[PLL_FCNTRL] * AddDiv) if None not in (N1, N2, N3, OUTDIV, AddDiv) else None
1314
+
1315
+ bit_rate_str = f"Bit Rate Clock: {bit_rate_clock / 1e6:.2f} MHz" if bit_rate_clock else "Invalid PLL Config"
1316
+ data_path_str = f"TX Data Path Clock: {data_path_clock / 1e6:.2f} MHz" if data_path_clock else "Invalid Data Path Config"
1317
+
1318
+ stdscr.clear()
1319
+ stdscr.addstr(0, 2, " FPGA SerDes Parameters (Auto-Update Enabled) ", curses.A_BOLD | curses.A_REVERSE)
1320
+
1321
+ with self.param_lock:
1322
+ for row in range(num_rows):
1323
+ for col in range(num_columns):
1324
+ index = row + col * num_rows
1325
+ if index >= len(param_list):
1326
+ continue
1327
+
1328
+ name, data = param_list[index]
1329
+ value = data['val']
1330
+ mode = data['mode'] # Get mode (R/W, W/C, R/C, R)
1331
+ color_pair = ColorFormatter.get_color_pair(name, value)
1332
+
1333
+ formatted_value = f"0x{value:X}" if show_hex else f"{value}"
1334
+
1335
+ # Read-only and Write/Clear (dimmed text)
1336
+ text_attr = curses.color_pair(color_pair) | curses.A_DIM if mode in ["R", "R/C"] else curses.color_pair(color_pair)
1337
+
1338
+ x_pos = col * col_width + 2
1339
+ y_pos = row + 2
1340
+
1341
+ # Highlight selected row
1342
+ if index == selected_index:
1343
+ stdscr.addstr(y_pos, x_pos, f"{name:<{max_name_length}} {formatted_value:<8}", curses.A_REVERSE)
1344
+ else:
1345
+ # Print parameter name (dimmed for R & W/C)
1346
+ stdscr.addstr(y_pos, x_pos, f"{name:<{max_name_length}}", text_attr)
1347
+
1348
+ # Print value in color
1349
+ stdscr.addstr(y_pos, x_pos + max_name_length + 1, f"{formatted_value:<8}", curses.color_pair(color_pair))
1350
+
1351
+
1352
+ stdscr.addstr(max_y - 5, 2, bit_rate_str)
1353
+ stdscr.addstr(max_y - 4, 2, data_path_str)
1354
+
1355
+ search_hint = "[n] Next match | " if search_results else ""
1356
+ stdscr.addstr(max_y - 2, 2, f"{search_hint}[Arrow Keys] Navigate | [Enter] Edit | [/] Find | [h] Toggle HEX/DEC | [q] Quit", curses.A_BOLD)
1357
+
1358
+ stdscr.refresh()
1359
+
1360
+ try:
1361
+ key = stdscr.getch()
1362
+ except curses.error:
1363
+ key = -1 # No input
1364
+
1365
+ if key == ord("h"):
1366
+ show_hex = not show_hex
1367
+ elif key == curses.KEY_UP and selected_index - 1 >= 0:
1368
+ selected_index -= 1
1369
+ elif key == curses.KEY_DOWN and selected_index + 1 < len(param_list):
1370
+ selected_index += 1
1371
+ elif key == curses.KEY_LEFT and selected_index - num_rows >= 0:
1372
+ selected_index -= num_rows
1373
+ elif key == curses.KEY_RIGHT and selected_index + num_rows < len(param_list):
1374
+ selected_index += num_rows
1375
+ elif key == ord("\n"):
1376
+ if param_list[selected_index][1]['mode'] in ["R", "R/C"]:
1377
+ self.error_message(stdscr, "Cannot edit read-only parameter!")
1378
+ else:
1379
+ self.edit_value_popup(stdscr, param_list[selected_index])
1380
+ elif key == ord("/"):
1381
+ search_results, search_index = self.find_parameter(stdscr, param_list)
1382
+ if search_results:
1383
+ selected_index = search_results[search_index]
1384
+ elif key == ord("n") and search_results:
1385
+ search_index = (search_index + 1) % len(search_results)
1386
+ selected_index = search_results[search_index]
1387
+ elif key == ord("q"):
1388
+ break
1389
+
1390
+ def edit_value_popup(self, stdscr, param):
1391
+ name, data = param
1392
+ max_y, max_x = stdscr.getmaxyx()
1393
+
1394
+ # Calculate the valid range from `hbit` and `lbit`
1395
+ hbit, lbit = data['hbit'], data['lbit']
1396
+ mask = ((1 << (hbit - lbit + 1)) - 1) << lbit
1397
+ addr = data['addr']
1398
+ min_value = 0
1399
+ max_value = (1 << (hbit - lbit + 1)) - 1 # Compute max based on bit range
1400
+
1401
+ win_height, win_width = 9, 50
1402
+ start_y = (max_y - win_height) // 2
1403
+ start_x = (max_x - win_width) // 2
1404
+
1405
+ win = curses.newwin(win_height, win_width, start_y, start_x)
1406
+ win.box()
1407
+ win.addstr(1, 2, f"Editing: {name}", curses.A_BOLD)
1408
+ win.addstr(2, 2, f"Position: addr=0x{addr:02X} mask=0x{mask:04X}")
1409
+ win.addstr(3, 2, f"Current: {data['val']} (Range: {min_value} - {max_value})") # Show valid range
1410
+ win.addstr(5, 2, "New value: ")
1411
+ win.addstr(7, 2, "[Enter] Save | [ESC/q] Cancel", curses.A_DIM)
1412
+
1413
+ win.refresh()
1414
+ curses.curs_set(1)
1415
+ win.keypad(True)
1416
+
1417
+ curses.echo()
1418
+ new_val = ""
1419
+
1420
+ while True:
1421
+ key = win.getch()
1422
+
1423
+ if key in (27, ord("q")):
1424
+ break
1425
+ elif key == ord("\n"):
1426
+ try:
1427
+ entered_value = int(new_val, 0) # Convert input to integer
1428
+ if min_value <= entered_value <= max_value:
1429
+ with self.param_lock:
1430
+ #data['val'] = entered_value # Apply change if within range
1431
+ self._tool.wr_serdes_regfile(addr=addr, data=entered_value << lbit, mask=mask, wren=1)
1432
+ self._tool.rd_serdes_regfile()
1433
+ break
1434
+ else:
1435
+ win.addstr(6, 2, "Out of range! Try again.", curses.A_BOLD | curses.color_pair(3))
1436
+ win.refresh()
1437
+ time.sleep(1)
1438
+ win.addstr(6, 2, " " * 30) # Clear error message
1439
+ except ValueError:
1440
+ win.addstr(6, 2, "Invalid input!", curses.A_BOLD | curses.color_pair(3))
1441
+ win.refresh()
1442
+ time.sleep(1)
1443
+ win.addstr(6, 2, " " * 30) # Clear error message
1444
+ elif key in (curses.KEY_BACKSPACE, 127):
1445
+ new_val = new_val[:-1]
1446
+ win.addstr(5, 13, " " * 10) # Clear previous input
1447
+ elif key in range(32, 127):
1448
+ new_val += chr(key)
1449
+
1450
+ win.addstr(5, 13, new_val)
1451
+ win.refresh()
1452
+
1453
+ curses.noecho()
1454
+ curses.curs_set(0)
1455
+
1456
+ def find_parameter(self, stdscr, param_list):
1457
+ max_y, max_x = stdscr.getmaxyx()
1458
+ win_height, win_width = 4, 50
1459
+ start_y = (max_y - win_height) // 2
1460
+ start_x = (max_x - win_width) // 2
1461
+
1462
+ win = curses.newwin(win_height, win_width, start_y, start_x)
1463
+ win.box()
1464
+ win.addstr(1, 2, "Find: ")
1465
+ win.addstr(2, 2, "[ESC/q] Cancel", curses.A_DIM)
1466
+
1467
+ win.refresh()
1468
+ curses.curs_set(1)
1469
+ curses.echo()
1470
+
1471
+ search_term = ""
1472
+
1473
+ while True:
1474
+ key = win.getch()
1475
+
1476
+ if key in (27, ord("q")):
1477
+ return [], 0
1478
+ elif key == ord("\n"):
1479
+ break
1480
+ elif key in (curses.KEY_BACKSPACE, 127):
1481
+ search_term = search_term[:-1]
1482
+ win.addstr(1, 8, " " * 40)
1483
+ elif key in range(32, 127):
1484
+ search_term += chr(key)
1485
+
1486
+ win.addstr(1, 8, search_term)
1487
+ win.refresh()
1488
+
1489
+ curses.noecho()
1490
+ curses.curs_set(0)
1491
+
1492
+ search_term = search_term.strip().lower()
1493
+
1494
+ if not search_term:
1495
+ return [], 0
1496
+
1497
+ matches = [i for i, (name, _) in enumerate(param_list) if search_term in name.lower()]
1498
+
1499
+ if not matches:
1500
+ self.error_message(stdscr, "No matches found!")
1501
+ return [], 0
1502
+
1503
+ return matches, 0
1504
+
1505
+ def error_message(self, stdscr, message):
1506
+ max_y, max_x = stdscr.getmaxyx()
1507
+ win_height, win_width = 3, len(message) + 10
1508
+ start_y = (max_y - win_height) // 2
1509
+ start_x = (max_x - win_width) // 2
1510
+
1511
+ win = curses.newwin(win_height, win_width, start_y, start_x)
1512
+ win.box()
1513
+ win.addstr(1, 2, message, curses.A_BOLD)
1514
+
1515
+ win.refresh()
1516
+ curses.napms(1500)
1517
+ del win
1518
+
1519
+
1520
+ if __name__ == '__main__':
1521
+ try:
1522
+ p = argparse.ArgumentParser(prog='serdestool', description='', epilog=ArgEpilog)
1523
+
1524
+ p.add_argument('-l', '--list', dest='listdev', action='store_true', help='list available boards/programmers and exit')
1525
+ p.add_argument('-b', dest='board', type=str, metavar=Boards_e, default=Boards_e[0], required=False, help='select board (default: %(default)s)')
1526
+ p.add_argument('--index-chain', dest='idx', default=0, required=False, help='device index in JTAG chain (default: %(default)s)')
1527
+ p.add_argument('--freq', type=ArgHzRegex, default='20M', metavar="[0 - 30M]", required=False, help='frequency setting; append "k" to the argument for kilohertz or "M" for megahertz (default: %(default)s)')
1528
+ p.add_argument('-m', dest='genmod', type=str, required=False, help='generate verilog or vhdl module and exit; specify the file format with extension .v or .vhd')
1529
+ p.add_argument('--rdregrx', dest='rdregrx', action='store_true', help='read rx regfile')
1530
+ p.add_argument('--rdregrxdata', dest='rdregrxdata', action='store_true', help='read rx data')
1531
+ p.add_argument('--rdregtx', dest='rdregtx', action='store_true', help='read tx regfile')
1532
+ p.add_argument('--rdregpll', dest='rdregpll', action='store_true', help='read pll regfile')
1533
+ p.add_argument('--rdstatuspll', dest='rdstatuspll', action='store_true', help='read pll status registers')
1534
+ p.add_argument('--gui', dest='gui', action='store_true', help='start curses gui')
1535
+ p.add_argument('--tcprbs', dest='tcprbs', action='store_true', help='testcase: prbs')
1536
+ p.add_argument('--tcloopback', dest='tcloopback', action='store_true', help='testcase: loopback')
1537
+ p.add_argument('--tcuipattern', dest='tcuipattern', choices=['0','2','20','40','80'], default=None, required=False, help='testcase: 2,20,40,80 UI square wave pattern')
1538
+
1539
+ args = p.parse_args()
1540
+ usb = UsbTools()
1541
+ jtag = JtagEngine(frequency=ArgHzParse(args.freq))
1542
+
1543
+ if args.listdev:
1544
+ vps_lst = list()
1545
+ vps_lst.append((0x0403, 0x6010)) # evb: FT2232H
1546
+ vps_lst.append((0x0403, 0x6014)) # pgm: FT232H
1547
+ for line in usb.find_all(vps=vps_lst):
1548
+ print(*line)
1549
+ sys.exit()
1550
+
1551
+ s = SerdesTool(args, jtag, hwinit=not args.genmod)
1552
+
1553
+ if args.genmod is not None:
1554
+ filename = args.genmod.lower()
1555
+ if filename.endswith('.v') or filename.endswith('.sv'):
1556
+ s.gen_module_vlog(filename)
1557
+ elif filename.endswith('.vhd') or filename.endswith('.vhdl'):
1558
+ s.gen_module_vhdl(filename)
1559
+ sys.exit()
1560
+
1561
+ if args.gui:
1562
+ update_thread = threading.Thread(target=s.update_values, daemon=True)
1563
+ update_thread.start()
1564
+ curses.wrapper(s.draw_parameters)
1565
+ else:
1566
+ if args.tcprbs:
1567
+ s.tc_prbs(force_err=True)
1568
+ if args.tcloopback:
1569
+ s.tc_loopback()
1570
+ if args.tcuipattern is not None:
1571
+ s.tc_uipattern(int(args.tcuipattern))
1572
+ if args.rdregrx:
1573
+ s.rd_regfile_rx(verbose=2)
1574
+ if args.rdregrxdata:
1575
+ s.print_regfile_rx_data(verbose=2)
1576
+ if args.rdregtx:
1577
+ s.rd_regfile_tx(verbose=2)
1578
+ if args.rdregpll:
1579
+ s.rd_regfile_pll(verbose=2)
1580
+ if args.rdstatuspll:
1581
+ [s._tool.rd_status_pll(pll=i, verbose=1) for i in range(4)]
1582
+
1583
+ except Exception as e:
1584
+ print(e)
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [> Bare Metal Demo App
2
+ ----------------------
3
+
4
+ This directory provides a minimal bare metal demo app that demonstrates how to easily create a bare metal C application and load it/run it on the CPU of a SoC.
5
+
6
+ [> Build and Load over LiteX-Term
7
+ ---------------------------------
8
+
9
+ To build a LiteX SoC for the Arty board (available in LiteX-Boards) and build the demo app for it, execute the following commands:
10
+ ```
11
+ python3 -m litex_boards.targets.digilent_arty --build --load
12
+ litex_bare_metal_demo --build-path=build/digilent_arty
13
+ ```
14
+ Where `--build-path` is the build path to the Arty build directory. The Arty board is used here but almost any another board supported in LiteX-Boards could be used. When no external RAM is provided directly by the board, `--integrated-main-ram-size` argument could be used to add some integrated RAM in the SoC and be able to execute the demo from it. (ex `--integrated-main-ram-size=0x8000` will add 32KB of integrated RAM).
15
+
16
+ Loading the compiled demo app can be done in different ways as explain in LiteX's wiki:
17
+ https://github.com/enjoy-digital/litex/wiki/Load-Application-Code-To-CPU
18
+
19
+ Since our app is small and for simplicity we'll just load it over serial here:
20
+ `$ litex_term /dev/ttyUSBX --kernel=demo.bin`
21
+
22
+ You should see the minimal demo app running and should be able to interact with it:
23
+
24
+ --============== Boot ==================--
25
+ Booting from serial...
26
+ Press Q or ESC to abort boot completely.
27
+ sL5DdSMmkekro
28
+ [LITEX-TERM] Received firmware download request from the device.
29
+ [LITEX-TERM] Uploading demo.bin to 0x40000000 (9264 bytes)...
30
+ [LITEX-TERM] Upload complete (9.8KB/s).
31
+ [LITEX-TERM] Booting the device.
32
+ [LITEX-TERM] Done.
33
+ Executing booted program at 0x40000000
34
+
35
+ --============= Liftoff! ===============--
36
+
37
+ LiteX minimal demo app built Dec 10 2020 17:13:02
38
+
39
+ Available commands:
40
+ help - Show this command
41
+ reboot - Reboot CPU
42
+ led - Led demo
43
+ donut - Spinning Donut demo
44
+ litex-demo-app> led
45
+ Led demo...
46
+ Counter mode...
47
+ Shift mode...
48
+ Dance mode...
49
+ litex-demo-app> donut
50
+ Donut demo...
51
+
52
+ $$$$$@@@@@
53
+ $##########$$$$$$$$
54
+ ###*!!!!!!!!!***##$$$$$$
55
+ ***!!====;;;;===!!**###$$$$#
56
+ **!===;;;:::::;:===!!**####$##
57
+ !*!!==;;:~-,,.,-~::;;=!!**#######!
58
+ !!!!=;:~-,.......-~::==!!***#####*
59
+ !!!!==;~~-.........,-:;==!!***###**!
60
+ !**!!=;:~-... ..-:;=!!!********!
61
+ ;!*#####*!!;. ~:;==!!!******!!=
62
+ :!*###$$$$#*! :;==!!!!!****!!!=;
63
+ ~=!*#$$$@@@$$##!!!!!!!!!!!!****!!!!=;
64
+ ;=!*#$$$@@@@$$#*******!*!!*!!!!!==;~
65
+ -;!*###$$$$$$$###******!!!!!!!===;~
66
+ -;!!*####$#####******!!!!!!==;;:-
67
+ ,:=!!!!**#**#***!!!!!!!====;:~,
68
+ -:==!!!*!!*!!!!!!!===;;;:~-
69
+ .~:;;========;=;;:::~-,
70
+ .--~~::::~:~~--,.
71
+ litex-demo-app>
72
+
73
+ [> Replace the LiteX BIOS with the Demo App
74
+ -------------------------------------------
75
+ In some cases, we'll just want to replace the LiteX BIOS with our custom app. This demo can be used as a basis to create a such custom app.
76
+
77
+ The demo will be recompiled to target the ROM of the SoC:
78
+ ```
79
+ litex_bare_metal_demo --build-path=build/arty/ --mem=rom
80
+ ```
81
+
82
+ The SoC can then be re-compiled to integrate the demo app in the ROM with:
83
+ ```
84
+ python3 -m litex_boards.targets.digilent_arty --integrated-rom-init=demo.bin --build --load
85
+ ```
86
+
87
+ When loading the bitstream, you should then directly see the demo app executed:
88
+ ```
89
+ LiteX minimal demo app built Dec 10 2020 17:13:02
90
+
91
+ Available commands:
92
+ help - Show this command
93
+ reboot - Reboot CPU
94
+ led - Led demo
95
+ donut - Spinning Donut demo
96
+ litex-demo-app>
97
+ ```
98
+
99
+
100
+ [> Going further
101
+ ----------------
102
+ To create more complex apps, feel free to explore the source code of the BIOS or other open source projects build with LiteX at https://github.com/enjoy-digital/litex/wiki/Projects.
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/__init__.py ADDED
File without changes
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ #
4
+ # This file is part of LiteX.
5
+ #
6
+ # Copyright (c) 2020-2022 Florent Kermarrec <florent@enjoy-digital.fr>
7
+ # SPDX-License-Identifier: BSD-2-Clause
8
+
9
+ import os
10
+ import sys
11
+ import argparse
12
+
13
+ from litex.build.tools import replace_in_file
14
+
15
+ def main():
16
+ parser = argparse.ArgumentParser(description="LiteX Bare Metal Demo App.")
17
+ parser.add_argument("--build-path", help="Target's build path (ex build/board_name).", required=True)
18
+ parser.add_argument("--with-cxx", action="store_true", help="Enable CXX support.")
19
+ parser.add_argument("--mem", default="main_ram", help="Memory Region where code will be loaded/executed.")
20
+ args = parser.parse_args()
21
+
22
+ # Create demo directory
23
+ os.makedirs("demo", exist_ok=True)
24
+
25
+ # Copy contents to demo directory
26
+ os.system(f"cp {os.path.abspath(os.path.dirname(__file__))}/* demo")
27
+ os.system("chmod -R u+w demo") # Nix specific: Allow linker script to be modified.
28
+
29
+ # Update memory region.
30
+ replace_in_file("demo/linker.ld", "main_ram", args.mem)
31
+
32
+ # Compile demo
33
+ build_path = args.build_path if os.path.isabs(args.build_path) else os.path.join("..", args.build_path)
34
+ os.system(f"export BUILD_DIR={build_path} && {'export WITH_CXX=1 &&' if args.with_cxx else ''} cd demo && make")
35
+
36
+ # Copy demo.bin
37
+ os.system("cp demo/demo.bin ./")
38
+
39
+ # Prepare flash boot image.
40
+ python3 = sys.executable or "python3" # Nix specific: Reuse current Python executable if available.
41
+ os.system(f"{python3} -m litex.soc.software.crcfbigen demo.bin -o demo.fbi --fbi --little") # FIXME: Endianness.
42
+
43
+ if __name__ == "__main__":
44
+ main()
45
+
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [> Bare Metal Demo App
2
+ ----------------------
3
+
4
+ This directory provides a minimal bare metal demo app that demonstrates how to easily create a bare metal C application and load it/run it on the CPU of a SoC.
5
+
6
+ [> Build and Load over LiteX-Term
7
+ ---------------------------------
8
+
9
+ To build a LiteX SoC for the Arty board (available in LiteX-Boards) and build the demo app for it, execute the following commands:
10
+ ```
11
+ python3 -m litex_boards.targets.digilent_arty --build --load
12
+ litex_bare_metal_demo --build-path=build/digilent_arty
13
+ ```
14
+ Where `--build-path` is the build path to the Arty build directory. The Arty board is used here but almost any another board supported in LiteX-Boards could be used. When no external RAM is provided directly by the board, `--integrated-main-ram-size` argument could be used to add some integrated RAM in the SoC and be able to execute the demo from it. (ex `--integrated-main-ram-size=0x8000` will add 32KB of integrated RAM).
15
+
16
+ Loading the compiled demo app can be done in different ways as explain in LiteX's wiki:
17
+ https://github.com/enjoy-digital/litex/wiki/Load-Application-Code-To-CPU
18
+
19
+ Since our app is small and for simplicity we'll just load it over serial here:
20
+ `$ litex_term /dev/ttyUSBX --kernel=demo.bin`
21
+
22
+ You should see the minimal demo app running and should be able to interact with it:
23
+
24
+ --============== Boot ==================--
25
+ Booting from serial...
26
+ Press Q or ESC to abort boot completely.
27
+ sL5DdSMmkekro
28
+ [LITEX-TERM] Received firmware download request from the device.
29
+ [LITEX-TERM] Uploading demo.bin to 0x40000000 (9264 bytes)...
30
+ [LITEX-TERM] Upload complete (9.8KB/s).
31
+ [LITEX-TERM] Booting the device.
32
+ [LITEX-TERM] Done.
33
+ Executing booted program at 0x40000000
34
+
35
+ --============= Liftoff! ===============--
36
+
37
+ LiteX minimal demo app built Dec 10 2020 17:13:02
38
+
39
+ Available commands:
40
+ help - Show this command
41
+ reboot - Reboot CPU
42
+ led - Led demo
43
+ donut - Spinning Donut demo
44
+ litex-demo-app> led
45
+ Led demo...
46
+ Counter mode...
47
+ Shift mode...
48
+ Dance mode...
49
+ litex-demo-app> donut
50
+ Donut demo...
51
+
52
+ $$$$$@@@@@
53
+ $##########$$$$$$$$
54
+ ###*!!!!!!!!!***##$$$$$$
55
+ ***!!====;;;;===!!**###$$$$#
56
+ **!===;;;:::::;:===!!**####$##
57
+ !*!!==;;:~-,,.,-~::;;=!!**#######!
58
+ !!!!=;:~-,.......-~::==!!***#####*
59
+ !!!!==;~~-.........,-:;==!!***###**!
60
+ !**!!=;:~-... ..-:;=!!!********!
61
+ ;!*#####*!!;. ~:;==!!!******!!=
62
+ :!*###$$$$#*! :;==!!!!!****!!!=;
63
+ ~=!*#$$$@@@$$##!!!!!!!!!!!!****!!!!=;
64
+ ;=!*#$$$@@@@$$#*******!*!!*!!!!!==;~
65
+ -;!*###$$$$$$$###******!!!!!!!===;~
66
+ -;!!*####$#####******!!!!!!==;;:-
67
+ ,:=!!!!**#**#***!!!!!!!====;:~,
68
+ -:==!!!*!!*!!!!!!!===;;;:~-
69
+ .~:;;========;=;;:::~-,
70
+ .--~~::::~:~~--,.
71
+ litex-demo-app>
72
+
73
+ [> Replace the LiteX BIOS with the Demo App
74
+ -------------------------------------------
75
+ In some cases, we'll just want to replace the LiteX BIOS with our custom app. This demo can be used as a basis to create a such custom app.
76
+
77
+ The demo will be recompiled to target the ROM of the SoC:
78
+ ```
79
+ litex_bare_metal_demo --build-path=build/arty/ --mem=rom
80
+ ```
81
+
82
+ The SoC can then be re-compiled to integrate the demo app in the ROM with:
83
+ ```
84
+ python3 -m litex_boards.targets.digilent_arty --integrated-rom-init=demo.bin --build --load
85
+ ```
86
+
87
+ When loading the bitstream, you should then directly see the demo app executed:
88
+ ```
89
+ LiteX minimal demo app built Dec 10 2020 17:13:02
90
+
91
+ Available commands:
92
+ help - Show this command
93
+ reboot - Reboot CPU
94
+ led - Led demo
95
+ donut - Spinning Donut demo
96
+ litex-demo-app>
97
+ ```
98
+
99
+
100
+ [> Going further
101
+ ----------------
102
+ To create more complex apps, feel free to explore the source code of the BIOS or other open source projects build with LiteX at https://github.com/enjoy-digital/litex/wiki/Projects.
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/__init__.py ADDED
File without changes
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/demo.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ #
4
+ # This file is part of LiteX.
5
+ #
6
+ # Copyright (c) 2020-2022 Florent Kermarrec <florent@enjoy-digital.fr>
7
+ # SPDX-License-Identifier: BSD-2-Clause
8
+
9
+ import os
10
+ import sys
11
+ import argparse
12
+
13
+ from litex.build.tools import replace_in_file
14
+
15
+ def main():
16
+ parser = argparse.ArgumentParser(description="LiteX Bare Metal Demo App.")
17
+ parser.add_argument("--build-path", help="Target's build path (ex build/board_name).", required=True)
18
+ parser.add_argument("--with-cxx", action="store_true", help="Enable CXX support.")
19
+ parser.add_argument("--mem", default="main_ram", help="Memory Region where code will be loaded/executed.")
20
+ args = parser.parse_args()
21
+
22
+ # Create demo directory
23
+ os.makedirs("demo", exist_ok=True)
24
+
25
+ # Copy contents to demo directory
26
+ os.system(f"cp {os.path.abspath(os.path.dirname(__file__))}/* demo")
27
+ os.system("chmod -R u+w demo") # Nix specific: Allow linker script to be modified.
28
+
29
+ # Update memory region.
30
+ replace_in_file("demo/linker.ld", "main_ram", args.mem)
31
+
32
+ # Compile demo
33
+ build_path = args.build_path if os.path.isabs(args.build_path) else os.path.join("..", args.build_path)
34
+ os.system(f"export BUILD_DIR={build_path} && {'export WITH_CXX=1 &&' if args.with_cxx else ''} cd demo && make")
35
+
36
+ # Copy demo.bin
37
+ os.system("cp demo/demo.bin ./")
38
+
39
+ # Prepare flash boot image.
40
+ python3 = sys.executable or "python3" # Nix specific: Reuse current Python executable if available.
41
+ os.system(f"{python3} -m litex.soc.software.crcfbigen demo.bin -o demo.fbi --fbi --little") # FIXME: Endianness.
42
+
43
+ if __name__ == "__main__":
44
+ main()
45
+
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/donut.c ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The donut code with fixed-point arithmetic; no sines, cosines, square roots, or anything.
2
+ // a1k0n 2020
3
+ // Code from: https://gist.github.com/a1k0n/80f48aa8911fffd805316b8ba8f48e83
4
+ // For more info:
5
+ // - https://www.a1k0n.net/2011/07/20/donut-math.html
6
+ // - https://www.youtube.com/watch?v=DEqXNfs_HhY
7
+
8
+ #include <stdio.h>
9
+ #include <stdlib.h>
10
+ #include <string.h>
11
+
12
+ #include <libbase/console.h>
13
+
14
+ #define R(mul,shift,x,y) \
15
+ _=x; \
16
+ x -= mul*y>>shift; \
17
+ y += mul*_>>shift; \
18
+ _ = 3145728-x*x-y*y>>11; \
19
+ x = x*_>>10; \
20
+ y = y*_>>10;
21
+
22
+ signed char b[1760], z[1760];
23
+
24
+ void donut(void);
25
+ void donut(void) {
26
+ int sA=1024,cA=0,sB=1024,cB=0,_;
27
+ for (;;) {
28
+ memset(b, 32, 1760); // text buffer
29
+ memset(z, 127, 1760); // z buffer
30
+ int sj=0, cj=1024;
31
+ for (int j = 0; j < 90; j++) {
32
+ int si = 0, ci = 1024; // sine and cosine of angle i
33
+ for (int i = 0; i < 324; i++) {
34
+ int R1 = 1, R2 = 2048, K2 = 5120*1024;
35
+
36
+ int x0 = R1*cj + R2,
37
+ x1 = ci*x0 >> 10,
38
+ x2 = cA*sj >> 10,
39
+ x3 = si*x0 >> 10,
40
+ x4 = R1*x2 - (sA*x3 >> 10),
41
+ x5 = sA*sj >> 10,
42
+ x6 = K2 + R1*1024*x5 + cA*x3,
43
+ x7 = cj*si >> 10,
44
+ x = 40 + 30*(cB*x1 - sB*x4)/x6,
45
+ y = 12 + 15*(cB*x4 + sB*x1)/x6,
46
+ N = (-cA*x7 - cB*((-sA*x7>>10) + x2) - ci*(cj*sB >> 10) >> 10) - x5 >> 7;
47
+
48
+ int o = x + 80 * y;
49
+ signed char zz = (x6-K2)>>15;
50
+ if (22 > y && y > 0 && x > 0 && 80 > x && zz < z[o]) {
51
+ z[o] = zz;
52
+ b[o] = ".,-~:;=!*#$@"[N > 0 ? N : 0];
53
+ }
54
+ R(5, 8, ci, si) // rotate i
55
+ }
56
+ R(9, 7, cj, sj) // rotate j
57
+ }
58
+ for (int k = 0; 1761 > k; k++)
59
+ putchar(k % 80 ? b[k] : 10);
60
+ R(5, 7, cA, sA);
61
+ R(5, 8, cB, sB);
62
+ if (readchar_nonblock()) {
63
+ getchar();
64
+ break;
65
+ }
66
+ fputs("\x1b[23A", stdout);
67
+ }
68
+ }
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/helloc.c ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+
3
+ void helloc(void);
4
+ void helloc(void) {
5
+ printf("C: Hello, world!\n");
6
+ }
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/hellocpp.cpp ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+
3
+ extern "C" void hellocpp(void);
4
+ void hellocpp(void)
5
+ {
6
+ printf("C++: Hello, world!\n");
7
+ }
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/demo/main.c ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr>
2
+ // License: BSD
3
+
4
+ #include <stdio.h>
5
+ #include <stdlib.h>
6
+ #include <string.h>
7
+
8
+ #include <irq.h>
9
+ #include <libbase/uart.h>
10
+ #include <libbase/console.h>
11
+ #include <generated/csr.h>
12
+
13
+ /*-----------------------------------------------------------------------*/
14
+ /* Uart */
15
+ /*-----------------------------------------------------------------------*/
16
+
17
+ static char *readstr(void)
18
+ {
19
+ char c[2];
20
+ static char s[64];
21
+ static int ptr = 0;
22
+
23
+ if(readchar_nonblock()) {
24
+ c[0] = getchar();
25
+ c[1] = 0;
26
+ switch(c[0]) {
27
+ case 0x7f:
28
+ case 0x08:
29
+ if(ptr > 0) {
30
+ ptr--;
31
+ fputs("\x08 \x08", stdout);
32
+ }
33
+ break;
34
+ case 0x07:
35
+ break;
36
+ case '\r':
37
+ case '\n':
38
+ s[ptr] = 0x00;
39
+ fputs("\n", stdout);
40
+ ptr = 0;
41
+ return s;
42
+ default:
43
+ if(ptr >= (sizeof(s) - 1))
44
+ break;
45
+ fputs(c, stdout);
46
+ s[ptr] = c[0];
47
+ ptr++;
48
+ break;
49
+ }
50
+ }
51
+
52
+ return NULL;
53
+ }
54
+
55
+ static char *get_token(char **str)
56
+ {
57
+ char *c, *d;
58
+
59
+ c = (char *)strchr(*str, ' ');
60
+ if(c == NULL) {
61
+ d = *str;
62
+ *str = *str+strlen(*str);
63
+ return d;
64
+ }
65
+ *c = 0;
66
+ d = *str;
67
+ *str = c+1;
68
+ return d;
69
+ }
70
+
71
+ static void prompt(void)
72
+ {
73
+ printf("\e[92;1mlitex-demo-app\e[0m> ");
74
+ }
75
+
76
+ /*-----------------------------------------------------------------------*/
77
+ /* Help */
78
+ /*-----------------------------------------------------------------------*/
79
+
80
+ static void help(void)
81
+ {
82
+ puts("\nLiteX minimal demo app built "__DATE__" "__TIME__"\n");
83
+ puts("Available commands:");
84
+ puts("help - Show this command");
85
+ puts("reboot - Reboot CPU");
86
+ #ifdef CSR_LEDS_BASE
87
+ puts("led - Led demo");
88
+ #endif
89
+ puts("donut - Spinning Donut demo");
90
+ puts("helloc - Hello C");
91
+ #ifdef WITH_CXX
92
+ puts("hellocpp - Hello C++");
93
+ #endif
94
+ }
95
+
96
+ /*-----------------------------------------------------------------------*/
97
+ /* Commands */
98
+ /*-----------------------------------------------------------------------*/
99
+
100
+ static void reboot_cmd(void)
101
+ {
102
+ ctrl_reset_write(1);
103
+ }
104
+
105
+ #ifdef CSR_LEDS_BASE
106
+ static void led_cmd(void)
107
+ {
108
+ int i;
109
+ printf("Led demo...\n");
110
+
111
+ printf("Counter mode...\n");
112
+ for(i=0; i<32; i++) {
113
+ leds_out_write(i);
114
+ busy_wait(100);
115
+ }
116
+
117
+ printf("Shift mode...\n");
118
+ for(i=0; i<4; i++) {
119
+ leds_out_write(1<<i);
120
+ busy_wait(200);
121
+ }
122
+ for(i=0; i<4; i++) {
123
+ leds_out_write(1<<(3-i));
124
+ busy_wait(200);
125
+ }
126
+
127
+ printf("Dance mode...\n");
128
+ for(i=0; i<4; i++) {
129
+ leds_out_write(0x55);
130
+ busy_wait(200);
131
+ leds_out_write(0xaa);
132
+ busy_wait(200);
133
+ }
134
+ }
135
+ #endif
136
+
137
+ extern void donut(void);
138
+
139
+ static void donut_cmd(void)
140
+ {
141
+ printf("Donut demo...\n");
142
+ donut();
143
+ }
144
+
145
+ extern void helloc(void);
146
+
147
+ static void helloc_cmd(void)
148
+ {
149
+ printf("Hello C demo...\n");
150
+ helloc();
151
+ }
152
+
153
+ #ifdef WITH_CXX
154
+ extern void hellocpp(void);
155
+
156
+ static void hellocpp_cmd(void)
157
+ {
158
+ printf("Hello C++ demo...\n");
159
+ hellocpp();
160
+ }
161
+ #endif
162
+
163
+ /*-----------------------------------------------------------------------*/
164
+ /* Console service / Main */
165
+ /*-----------------------------------------------------------------------*/
166
+
167
+ static void console_service(void)
168
+ {
169
+ char *str;
170
+ char *token;
171
+
172
+ str = readstr();
173
+ if(str == NULL) return;
174
+ token = get_token(&str);
175
+ if(strcmp(token, "help") == 0)
176
+ help();
177
+ else if(strcmp(token, "reboot") == 0)
178
+ reboot_cmd();
179
+ #ifdef CSR_LEDS_BASE
180
+ else if(strcmp(token, "led") == 0)
181
+ led_cmd();
182
+ #endif
183
+ else if(strcmp(token, "donut") == 0)
184
+ donut_cmd();
185
+ else if(strcmp(token, "helloc") == 0)
186
+ helloc_cmd();
187
+ #ifdef WITH_CXX
188
+ else if(strcmp(token, "hellocpp") == 0)
189
+ hellocpp_cmd();
190
+ #endif
191
+ prompt();
192
+ }
193
+
194
+ int main(void)
195
+ {
196
+ #ifdef CONFIG_CPU_HAS_INTERRUPT
197
+ irq_setmask(0);
198
+ irq_setie(1);
199
+ #endif
200
+ uart_init();
201
+
202
+ help();
203
+ prompt();
204
+
205
+ while(1) {
206
+ console_service();
207
+ }
208
+
209
+ return 0;
210
+ }
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/donut.c ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The donut code with fixed-point arithmetic; no sines, cosines, square roots, or anything.
2
+ // a1k0n 2020
3
+ // Code from: https://gist.github.com/a1k0n/80f48aa8911fffd805316b8ba8f48e83
4
+ // For more info:
5
+ // - https://www.a1k0n.net/2011/07/20/donut-math.html
6
+ // - https://www.youtube.com/watch?v=DEqXNfs_HhY
7
+
8
+ #include <stdio.h>
9
+ #include <stdlib.h>
10
+ #include <string.h>
11
+
12
+ #include <libbase/console.h>
13
+
14
+ #define R(mul,shift,x,y) \
15
+ _=x; \
16
+ x -= mul*y>>shift; \
17
+ y += mul*_>>shift; \
18
+ _ = 3145728-x*x-y*y>>11; \
19
+ x = x*_>>10; \
20
+ y = y*_>>10;
21
+
22
+ signed char b[1760], z[1760];
23
+
24
+ void donut(void);
25
+ void donut(void) {
26
+ int sA=1024,cA=0,sB=1024,cB=0,_;
27
+ for (;;) {
28
+ memset(b, 32, 1760); // text buffer
29
+ memset(z, 127, 1760); // z buffer
30
+ int sj=0, cj=1024;
31
+ for (int j = 0; j < 90; j++) {
32
+ int si = 0, ci = 1024; // sine and cosine of angle i
33
+ for (int i = 0; i < 324; i++) {
34
+ int R1 = 1, R2 = 2048, K2 = 5120*1024;
35
+
36
+ int x0 = R1*cj + R2,
37
+ x1 = ci*x0 >> 10,
38
+ x2 = cA*sj >> 10,
39
+ x3 = si*x0 >> 10,
40
+ x4 = R1*x2 - (sA*x3 >> 10),
41
+ x5 = sA*sj >> 10,
42
+ x6 = K2 + R1*1024*x5 + cA*x3,
43
+ x7 = cj*si >> 10,
44
+ x = 40 + 30*(cB*x1 - sB*x4)/x6,
45
+ y = 12 + 15*(cB*x4 + sB*x1)/x6,
46
+ N = (-cA*x7 - cB*((-sA*x7>>10) + x2) - ci*(cj*sB >> 10) >> 10) - x5 >> 7;
47
+
48
+ int o = x + 80 * y;
49
+ signed char zz = (x6-K2)>>15;
50
+ if (22 > y && y > 0 && x > 0 && 80 > x && zz < z[o]) {
51
+ z[o] = zz;
52
+ b[o] = ".,-~:;=!*#$@"[N > 0 ? N : 0];
53
+ }
54
+ R(5, 8, ci, si) // rotate i
55
+ }
56
+ R(9, 7, cj, sj) // rotate j
57
+ }
58
+ for (int k = 0; 1761 > k; k++)
59
+ putchar(k % 80 ? b[k] : 10);
60
+ R(5, 7, cA, sA);
61
+ R(5, 8, cB, sB);
62
+ if (readchar_nonblock()) {
63
+ getchar();
64
+ break;
65
+ }
66
+ fputs("\x1b[23A", stdout);
67
+ }
68
+ }
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/helloc.c ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+
3
+ void helloc(void);
4
+ void helloc(void) {
5
+ printf("C: Hello, world!\n");
6
+ }
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/hellocpp.cpp ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+
3
+ extern "C" void hellocpp(void);
4
+ void hellocpp(void)
5
+ {
6
+ printf("C++: Hello, world!\n");
7
+ }
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/2.sw/main.c ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr>
2
+ // License: BSD
3
+
4
+ #include <stdio.h>
5
+ #include <stdlib.h>
6
+ #include <string.h>
7
+
8
+ #include <irq.h>
9
+ #include <libbase/uart.h>
10
+ #include <libbase/console.h>
11
+ #include <generated/csr.h>
12
+
13
+ /*-----------------------------------------------------------------------*/
14
+ /* Uart */
15
+ /*-----------------------------------------------------------------------*/
16
+
17
+ static char *readstr(void)
18
+ {
19
+ char c[2];
20
+ static char s[64];
21
+ static int ptr = 0;
22
+
23
+ if(readchar_nonblock()) {
24
+ c[0] = getchar();
25
+ c[1] = 0;
26
+ switch(c[0]) {
27
+ case 0x7f:
28
+ case 0x08:
29
+ if(ptr > 0) {
30
+ ptr--;
31
+ fputs("\x08 \x08", stdout);
32
+ }
33
+ break;
34
+ case 0x07:
35
+ break;
36
+ case '\r':
37
+ case '\n':
38
+ s[ptr] = 0x00;
39
+ fputs("\n", stdout);
40
+ ptr = 0;
41
+ return s;
42
+ default:
43
+ if(ptr >= (sizeof(s) - 1))
44
+ break;
45
+ fputs(c, stdout);
46
+ s[ptr] = c[0];
47
+ ptr++;
48
+ break;
49
+ }
50
+ }
51
+
52
+ return NULL;
53
+ }
54
+
55
+ static char *get_token(char **str)
56
+ {
57
+ char *c, *d;
58
+
59
+ c = (char *)strchr(*str, ' ');
60
+ if(c == NULL) {
61
+ d = *str;
62
+ *str = *str+strlen(*str);
63
+ return d;
64
+ }
65
+ *c = 0;
66
+ d = *str;
67
+ *str = c+1;
68
+ return d;
69
+ }
70
+
71
+ static void prompt(void)
72
+ {
73
+ printf("\e[92;1mlitex-demo-app\e[0m> ");
74
+ }
75
+
76
+ /*-----------------------------------------------------------------------*/
77
+ /* Help */
78
+ /*-----------------------------------------------------------------------*/
79
+
80
+ static void help(void)
81
+ {
82
+ puts("\nLiteX minimal demo app built "__DATE__" "__TIME__"\n");
83
+ puts("Available commands:");
84
+ puts("help - Show this command");
85
+ puts("reboot - Reboot CPU");
86
+ #ifdef CSR_LEDS_BASE
87
+ puts("led - Led demo");
88
+ #endif
89
+ puts("donut - Spinning Donut demo");
90
+ puts("helloc - Hello C");
91
+ #ifdef WITH_CXX
92
+ puts("hellocpp - Hello C++");
93
+ #endif
94
+ }
95
+
96
+ /*-----------------------------------------------------------------------*/
97
+ /* Commands */
98
+ /*-----------------------------------------------------------------------*/
99
+
100
+ static void reboot_cmd(void)
101
+ {
102
+ ctrl_reset_write(1);
103
+ }
104
+
105
+ #ifdef CSR_LEDS_BASE
106
+ static void led_cmd(void)
107
+ {
108
+ int i;
109
+ printf("Led demo...\n");
110
+
111
+ printf("Counter mode...\n");
112
+ for(i=0; i<32; i++) {
113
+ leds_out_write(i);
114
+ busy_wait(100);
115
+ }
116
+
117
+ printf("Shift mode...\n");
118
+ for(i=0; i<4; i++) {
119
+ leds_out_write(1<<i);
120
+ busy_wait(200);
121
+ }
122
+ for(i=0; i<4; i++) {
123
+ leds_out_write(1<<(3-i));
124
+ busy_wait(200);
125
+ }
126
+
127
+ printf("Dance mode...\n");
128
+ for(i=0; i<4; i++) {
129
+ leds_out_write(0x55);
130
+ busy_wait(200);
131
+ leds_out_write(0xaa);
132
+ busy_wait(200);
133
+ }
134
+ }
135
+ #endif
136
+
137
+ extern void donut(void);
138
+
139
+ static void donut_cmd(void)
140
+ {
141
+ printf("Donut demo...\n");
142
+ donut();
143
+ }
144
+
145
+ extern void helloc(void);
146
+
147
+ static void helloc_cmd(void)
148
+ {
149
+ printf("Hello C demo...\n");
150
+ helloc();
151
+ }
152
+
153
+ #ifdef WITH_CXX
154
+ extern void hellocpp(void);
155
+
156
+ static void hellocpp_cmd(void)
157
+ {
158
+ printf("Hello C++ demo...\n");
159
+ hellocpp();
160
+ }
161
+ #endif
162
+
163
+ /*-----------------------------------------------------------------------*/
164
+ /* Console service / Main */
165
+ /*-----------------------------------------------------------------------*/
166
+
167
+ static void console_service(void)
168
+ {
169
+ char *str;
170
+ char *token;
171
+
172
+ str = readstr();
173
+ if(str == NULL) return;
174
+ token = get_token(&str);
175
+ if(strcmp(token, "help") == 0)
176
+ help();
177
+ else if(strcmp(token, "reboot") == 0)
178
+ reboot_cmd();
179
+ #ifdef CSR_LEDS_BASE
180
+ else if(strcmp(token, "led") == 0)
181
+ led_cmd();
182
+ #endif
183
+ else if(strcmp(token, "donut") == 0)
184
+ donut_cmd();
185
+ else if(strcmp(token, "helloc") == 0)
186
+ helloc_cmd();
187
+ #ifdef WITH_CXX
188
+ else if(strcmp(token, "hellocpp") == 0)
189
+ hellocpp_cmd();
190
+ #endif
191
+ prompt();
192
+ }
193
+
194
+ int main(void)
195
+ {
196
+ #ifdef CONFIG_CPU_HAS_INTERRUPT
197
+ irq_setmask(0);
198
+ irq_setie(1);
199
+ #endif
200
+ uart_init();
201
+
202
+ help();
203
+ prompt();
204
+
205
+ while(1) {
206
+ console_service();
207
+ }
208
+
209
+ return 0;
210
+ }
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/4.migen/liteiclink/serdes/serdes_gm.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from migen import *
2
+ from migen.genlib.cdc import MultiReg
3
+ from migen.genlib.resetsync import AsyncResetSynchronizer
4
+
5
+ from litex.gen import LiteXModule
6
+ from litex.soc.interconnect.csr import CSRStorage, CSRStatus, CSRField
7
+ from litex.soc.interconnect import stream
8
+ from litex.soc.cores.prbs import PRBSTX, PRBSRX
9
+ from litex.soc.cores.code_8b10b import Encoder, Decoder
10
+
11
+ class SerDesGM(LiteXModule):
12
+ def __init__(self, sys_clk_freq, refclk_freq=125e6, linerate=1.25e9,
13
+ tx_polarity=0, rx_polarity=0,
14
+ internal_loopback=False):
15
+ # We use a fixed 20-bit data path (two 10-bit 8b/10b words) at half the line rate.
16
+ data_width = 20
17
+ self.nwords = data_width // 10
18
+
19
+ self.tx_enable = Signal(reset=1)
20
+ self.rx_enable = Signal(reset=1)
21
+ self.tx_ready = Signal()
22
+ self.rx_ready = Signal()
23
+ self.tx_idle = Signal()
24
+ self.loopback = Signal(reset=1 if internal_loopback else 0) # Loopback mode (fixed at init)
25
+
26
+ self.tx_prbs_config = Signal(2) # PRBS pattern for TX (00: off, 01: PRBS7, 10: PRBS15, 11: PRBS31)
27
+ self.rx_prbs_config = Signal(2) # PRBS pattern for RX (must match TX)
28
+ self.rx_prbs_pause = Signal()
29
+ self.rx_prbs_errors = Signal(32)
30
+
31
+ self.txoutclk = Signal()
32
+ self.rxoutclk = Signal()
33
+
34
+ self.cd_tx = ClockDomain()
35
+ self.cd_tx_half = ClockDomain(reset_less=True)
36
+ self.cd_rx = ClockDomain()
37
+
38
+ self.tx_clk_freq = linerate / data_width
39
+ self.rx_clk_freq = linerate / data_width
40
+
41
+ self.encoder = ClockDomainsRenamer("tx")(Encoder(self.nwords, True))
42
+ self.decoders = [ClockDomainsRenamer("rx")(Decoder(True)) for _ in range(self.nwords)]
43
+
44
+ self.tx_prbs = ClockDomainsRenamer("tx")(PRBSTX(data_width, reverse=True))
45
+ self.rx_prbs = ClockDomainsRenamer("rx")(PRBSRX(data_width, reverse=True))
46
+
47
+ tx_data = Signal(data_width)
48
+ rx_data = Signal(data_width)
49
+ tx_bus = Signal(24)
50
+ rx_bus = Signal(24)
51
+
52
+
53
+
54
+ _tx_prbs_config = Signal(2)
55
+ _rx_prbs_config = Signal(2)
56
+ _rx_prbs_pause = Signal()
57
+ self.specials += [
58
+ MultiReg(self.tx_prbs_config, _tx_prbs_config, "tx"),
59
+ MultiReg(self.rx_prbs_config, _rx_prbs_config, "rx"),
60
+ MultiReg(self.rx_prbs_pause, _rx_prbs_pause, "rx")
61
+ ]
62
+
63
+ _prbs_errors = Signal(32)
64
+ self.specials += MultiReg(self.rx_prbs.errors, _prbs_errors, "sys")
65
+ self.comb += self.rx_prbs_errors.eq(_prbs_errors)
66
+
67
+ tx_reset = Signal()
68
+ rx_reset = Signal()
69
+ tx_reset_done = Signal()
70
+ rx_reset_done = Signal()
71
+ adpll_reset = Signal(reset=1)
72
+ tx_detect_rx_done = Signal()
73
+ tx_detect_rx_present = Signal()
74
+ rx_buf_err = Signal()
75
+ tx_buf_err = Signal()
76
+ rx_prbs_err_flag = Signal() # you’ll have to OR–reduce your 32‑bit error count into 1 bit
77
+
78
+ tx_half_toggle = Signal(reset=0)
79
+ tx_half_clk = Signal()
80
+ self.rx_reset_done_n = rx_reset_done
81
+ self.tx_reset_done_n = tx_reset_done
82
+ self.tx_detect_rx_done_n = tx_detect_rx_done
83
+ self.tx_detect_rx_present_n = tx_detect_rx_present
84
+ self.rx_buf_err_n = rx_buf_err
85
+ self.tx_buf_err_n = tx_buf_err
86
+ self.comb += rx_prbs_err_flag.eq(self.rx_prbs_errors != 0)
87
+ self.rx_prbs_err_n = rx_prbs_err_flag
88
+ self.specials += [
89
+ Instance("CC_BUFG", i_I=self.txoutclk, o_O=self.cd_tx.clk), # 125 MHz TX domain
90
+ Instance("CC_BUFG", i_I=self.rxoutclk, o_O=self.cd_rx.clk) # 62.5 MHz RX domain
91
+ ]
92
+
93
+ # Generate 62.5 MHz TX half clock by dividing txoutclk by 2
94
+ self.sync.tx += tx_half_toggle.eq(~tx_half_toggle)
95
+ self.comb += tx_half_clk.eq(tx_half_toggle)
96
+ self.specials += Instance("CC_BUFG", i_I=tx_half_clk, o_O=self.cd_tx_half.clk)
97
+
98
+ self.comb += [
99
+ tx_reset.eq(~self.tx_enable | adpll_reset), # hold TX in reset if disabled or PLL not ready
100
+ rx_reset.eq(~self.rx_enable) # hold RX in reset if disabled
101
+ ]
102
+ self.comb += [
103
+ self.tx_prbs.config.eq(_tx_prbs_config),
104
+ self.rx_prbs.config.eq(_rx_prbs_config),
105
+ self.rx_prbs.pause.eq(_rx_prbs_pause)
106
+ ]
107
+ # ** TX Data Path Selection **
108
+ # Feed 8b/10b encoder output into PRBS generator (the PRBS block will pass data through if PRBS is disabled)
109
+ self.comb += self.tx_prbs.i.eq(Cat(*[self.encoder.output[i] for i in range(self.nwords)]))
110
+ # Select transmitted data: PRBS output if PRBS mode is enabled, otherwise 8b/10b encoded data
111
+ self.comb += If(self.tx_prbs_config != 0,
112
+ tx_data.eq(self.tx_prbs.o)
113
+ ).Else(
114
+ tx_data.eq(Cat(*[self.encoder.output[i] for i in range(self.nwords)]))
115
+ )
116
+ # Map 20-bit tx_data into SERDES TX bus (16 data bits + 4 control bits for disparity/K)
117
+ # Lower 10-bit word: data[0:8] -> TX_DATA bits 0-7, tx_data[8] -> dispval, tx_data[9] -> dispmode
118
+ # Upper 10-bit word: data[10:18] -> TX_DATA bits 8-15, tx_data[18] -> dispval, tx_data[19] -> dispmode
119
+ self.comb += [
120
+ tx_bus[0:8].eq(tx_data[0:8]), # lower byte of data
121
+ tx_bus[8].eq(0), tx_bus[9].eq(0), # we set all K/disp bits to 0 by default (assuming data already disparity-corrected)
122
+ tx_bus[10:18].eq(tx_data[10:18]), # upper byte of data
123
+ tx_bus[18:24].eq(0) # upper word K/disp bits also 0
124
+ ]
125
+ # ** RX Data Path **
126
+ # Map SERDES RX bus back to 20-bit data (inverse of TX mapping)
127
+ self.comb += [
128
+ rx_data[0:8].eq(rx_bus[0:8]), # lower 8 data bits
129
+ rx_data[8].eq(rx_bus[8]), # (not used in fabric, would indicate K or disparity error)
130
+ rx_data[9].eq(rx_bus[9]), # (not used in fabric)
131
+ rx_data[10:18].eq(rx_bus[10:18]), # upper 8 data bits
132
+ rx_data[18].eq(rx_bus[18]),
133
+ rx_data[19].eq(rx_bus[19])
134
+ ]
135
+ # Feed RX data into PRBS checker
136
+ self.comb += self.rx_prbs.i.eq(rx_data)
137
+ # Feed RX data into 8b/10b decoders (each decoder handles one 10-bit word)
138
+ for i in range(self.nwords):
139
+ self.sync.rx += self.decoders[i].input.eq(rx_data[10*i:10*(i+1)])
140
+ # ** Reset and Initialization Sequencing **
141
+ pll_reset_cycles = int((30000 * sys_clk_freq) // 1e9) # ~30 µs at sys_clk_freq
142
+ if pll_reset_cycles < 1: pll_reset_cycles = 1
143
+ reset_counter = Signal(max=pll_reset_cycles+1, reset=0)
144
+ cdr_lock_time = int((sys_clk_freq * 50e3) // linerate) # ~50,000 UI (bit periods) at sys_clk
145
+ if cdr_lock_time < 1: cdr_lock_time = 1
146
+ cdr_lock_counter = Signal(max=int(cdr_lock_time)+1, reset=0)
147
+ cdr_locked = Signal(reset=0)
148
+ # System clock domain FSM for resets
149
+ self.sync += [
150
+ # ADPLL reset release after `pll_reset_cycles` ticks
151
+ If(reset_counter < pll_reset_cycles,
152
+ reset_counter.eq(reset_counter + 1),
153
+ adpll_reset.eq(1)
154
+ ).Else(
155
+ adpll_reset.eq(0)
156
+ ),
157
+ # CDR lock timer (starts when RX reset is not asserted and PLL is running)
158
+ If(rx_reset | adpll_reset,
159
+ cdr_locked.eq(0),
160
+ cdr_lock_counter.eq(0)
161
+ ).Elif(cdr_lock_counter < cdr_lock_time,
162
+ cdr_lock_counter.eq(cdr_lock_counter + 1)
163
+ ).Else(
164
+ cdr_locked.eq(1)
165
+ )
166
+ ]
167
+ self.comb += [
168
+ self.rx_ready.eq(cdr_locked),
169
+ self.tx_ready.eq(tx_reset_done & cdr_locked)
170
+ ]
171
+ self.specials += AsyncResetSynchronizer(self.cd_rx, ~cdr_locked)
172
+ self.specials += AsyncResetSynchronizer(self.cd_tx, ~tx_reset_done)
173
+
174
+ # Select ADPLL parameters for the given reference clock frequency
175
+ adpll_config = {
176
+ 100e6: {'fcntrl': 0x0A, 'main_divsel': 0x1B, 'out_divsel': 3}, # for 100 MHz ref
177
+ 125e6: {'fcntrl': 0x1A, 'main_divsel': 0x1A, 'out_divsel': 3} # for 125 MHz ref
178
+ }
179
+ assert refclk_freq in adpll_config, "Unsupported refclk_freq (use 100e6 or 125e6)."
180
+ cfg = adpll_config[refclk_freq]
181
+
182
+ serdes_params = dict(
183
+ # Global SERDES configuration
184
+ p_SERDES_ENABLE = 1,
185
+ p_SERDES_AUTO_INIT = 0,
186
+ p_SERDES_TESTMODE = 1,
187
+ # ADPLL (PLL) configuration
188
+ p_PLL_EN_ADPLL_CTRL = 1,
189
+ p_PLL_CONFIG_SEL = 1, #0 :internal, 1: regfile
190
+ p_PLL_REF_SEL = 1, # 1 = LVDS reference (expects diff ref clock, or internal calibration if none)
191
+ p_PLL_REF_BYPASS = 0,
192
+ p_PLL_REF_RTERM = 1,
193
+ p_PLL_FCNTRL = cfg['fcntrl'],
194
+ p_PLL_MAIN_DIVSEL = cfg['main_divsel'],
195
+ p_PLL_OUT_DIVSEL = cfg['out_divsel'],
196
+ p_PLL_CI = 3,
197
+ p_PLL_CP = 80,
198
+ p_PLL_AO = 0,
199
+ p_PLL_SCAP = 0,
200
+ p_PLL_FILTER_SHIFT = 2,
201
+ p_PLL_SAR_LIMIT = 2,
202
+ p_PLL_FT = 512,
203
+ p_PLL_OPEN_LOOP = 0,
204
+ p_PLL_SCAP_AUTO_CAL = 1,
205
+ p_PLL_SET_OP_LOCK = 0,
206
+ p_PLL_ENFORCE_LOCK = 0,
207
+ p_PLL_DISABLE_LOCK = 0,
208
+ p_PLL_LOCK_WINDOW = 1,
209
+ p_PLL_FAST_LOCK = 1,
210
+ p_PLL_SYNC_BYPASS = 0,
211
+ p_PLL_PFD_SELECT = 0,
212
+ p_PLL_REF_RTERM = 1,
213
+ #TX
214
+ p_TX_SEL_PRE = 0,
215
+ p_TX_SEL_POST = 0,
216
+ p_TX_AMP = 0XF,
217
+
218
+ p_TX_BRANCH_EN_PRE = 0,
219
+ p_TX_BRANCH_EN_MAIN = 0x3F,
220
+ p_TX_BRANCH_EN_POST = 0,
221
+ p_TX_TAIL_CASCODE = 0x4,
222
+ p_TX_DC_ENABLE = 0x3F,
223
+ p_TX_DC_OFFSET = 0x8, # note: set to 8
224
+ p_TX_CM_RAISE = 0x0,
225
+ p_TX_CM_THRESHOLD_0 = 0xE,
226
+ p_TX_CM_THRESHOLD_1 = 0x10,
227
+ p_TX_SEL_PRE_EI = 0x0,
228
+ p_TX_SEL_POST_EI = 0x0,
229
+ p_TX_AMP_EI = 0xF,
230
+ p_TX_BRANCH_EN_PRE_EI = 0x0,
231
+ p_TX_BRANCH_EN_MAIN_EI = 0x3F,
232
+ p_TX_BRANCH_EN_POST_EI = 0x0,
233
+ p_TX_TAIL_CASCODE_EI = 0x4,
234
+ p_TX_DC_ENABLE_EI = 0x3F,
235
+ p_TX_DC_OFFSET_EI = 0x0,
236
+ p_TX_CM_RAISE_EI = 0x0,
237
+ p_TX_CM_THRESHOLD_0_EI = 0xE,
238
+ p_TX_CM_THRESHOLD_1_EI = 0x10,
239
+ p_TX_SEL_PRE_RXDET = 0x0,
240
+ p_TX_SEL_POST_RXDET = 0x0,
241
+ p_TX_AMP_RXDET = 0xF,
242
+ p_TX_BRANCH_EN_PRE_RXDET = 0x0,
243
+ p_TX_BRANCH_EN_MAIN_RXDET = 0x3F,
244
+ p_TX_BRANCH_EN_POST_RXDET = 0x0,
245
+ p_TX_TAIL_CASCODE_RXDET = 0x4,
246
+ p_TX_DC_ENABLE_RXDET =0x3F,
247
+ p_TX_DC_OFFSET_RXDET = 0x0,
248
+ p_TX_CM_RAISE_RXDET = 0x0,
249
+ p_TX_CM_THRESHOLD_0_RXDET = 0xE,
250
+ p_TX_CM_THRESHOLD_1_RXDET = 0x10,
251
+ p_TX_CALIB_EN = 0x0,
252
+ p_TX_CALIB_OVR = 0x0,
253
+ p_TX_CALIB_VAL = 0x0,
254
+ p_TX_CM_REG_KI = 0x80,
255
+ p_TX_CM_SAR_EN = 0x0,
256
+ p_TX_CM_REG_EN = 0x1,
257
+
258
+ p_TX_PCS_RESET_OVR=0x0,
259
+ p_TX_PCS_RESET=0x0,
260
+ p_TX_PMA_RESET_OVR=0x0,
261
+ p_TX_PMA_RESET=0x0,
262
+ p_TX_RESET_OVR=0x0,
263
+ p_TX_RESET=0x0,
264
+ p_TX_LOOPBACK_OVR=0x0,
265
+ p_TX_DETECT_RX_OVR=0x0,
266
+ p_TX_DETECT_RX=0x0,
267
+ p_TX_DATA_OVR=0x0,
268
+ p_TX_DATA_CNT=0x0,
269
+ p_TX_DATA_VALID=0x0,
270
+ # ADPLL BISC (Background calibration for PLL)
271
+ p_PLL_BISC_MODE = 5,
272
+ p_PLL_BISC_TIMER_MAX = 15,
273
+ p_PLL_BISC_OPT_DET_IND = 0,
274
+ p_PLL_BISC_PFD_SEL = 0,
275
+ p_PLL_BISC_DLY_DIR = 0,
276
+ p_PLL_BISC_COR_DLY = 1,
277
+ p_PLL_BISC_CAL_SIGN = 0,
278
+ p_PLL_BISC_CAL_AUTO = 1,
279
+ p_PLL_BISC_CP_MIN = 6,
280
+ p_PLL_BISC_CP_MAX = 30,
281
+ p_PLL_BISC_CP_START = 6,
282
+ p_PLL_BISC_DLY_PFD_MON_REF = 0,
283
+ p_PLL_BISC_DLY_PFD_MON_DIV = 2,
284
+ # 8b/10b settings (bypass internal encoder/decoder)
285
+ p_TX_8B10B_EN_OVR = 0, p_TX_8B10B_EN = 0,
286
+ p_RX_8B10B_EN_OVR = 0, p_RX_8B10B_EN = 0,
287
+ p_RX_8B10B_BYPASS = 0x00,
288
+ # Data path width selection: 0 = 20-bit (1:2 gearbox)
289
+ p_TX_DATAPATH_SEL = 0,
290
+ p_RX_DATAPATH_SEL = 0,
291
+ # Reset timings
292
+ p_TX_PMA_RESET_TIME = 3, p_TX_PCS_RESET_TIME = 3,
293
+ p_RX_PMA_RESET_TIME = 3, p_RX_PCS_RESET_TIME = 3,
294
+ p_RX_RESET_TIMER_PRESC = 0, p_RX_RESET_DONE_GATE = 0,
295
+ # Electrical idle / power-down (TX/RX always on in this test)
296
+ p_TX_POWER_DOWN_OVR = 0, p_TX_POWER_DOWN_N = 1,
297
+ p_RX_POWER_DOWN_OVR = 0, p_RX_POWER_DOWN_N = 1,
298
+ p_TX_ELEC_IDLE_OVR = 0, p_TX_ELEC_IDLE = 0,
299
+ # Polarity control
300
+ p_TX_POLARITY_OVR = 0, p_TX_POLARITY = 0,
301
+ p_RX_POLARITY_OVR = 0, p_RX_POLARITY = 0,
302
+ # Comma alignment
303
+ p_RX_COMMA_DETECT_EN_OVR = 0,
304
+ p_RX_COMMA_DETECT_EN = 0,
305
+ p_RX_ALIGN_COMMA_WORD = 3,
306
+ p_RX_ALIGN_COMMA_ENABLE = 0x3FF,
307
+ p_RX_ALIGN_MCOMMA_VALUE = 0x283,
308
+ p_RX_ALIGN_PCOMMA_VALUE = 0x17C,
309
+ p_RX_MCOMMA_ALIGN_OVR = 0, p_RX_MCOMMA_ALIGN = 0,
310
+ p_RX_PCOMMA_ALIGN_OVR = 0, p_RX_PCOMMA_ALIGN = 0,
311
+ p_RX_SLIDE_MODE = 0, p_RX_SLIDE = 0,
312
+ p_RX_BYTE_REALIGN = 1,
313
+ # Clock correction
314
+ p_RX_CLKCOR_USE = 0,
315
+ p_RX_CLKCOR_MIN_LAT= 32, p_RX_CLKCOR_MAX_LAT = 39,
316
+ p_RX_CLKCOR_SEQ_1_0= 0x1F7, p_RX_CLKCOR_SEQ_1_1=0x1F7,
317
+ p_RX_CLKCOR_SEQ_1_2= 0x1F7, p_RX_CLKCOR_SEQ_1_3=0x1F7,
318
+ # CDR configuration
319
+ p_RX_WAIT_CDR_LOCK = 0,
320
+ p_RX_CDR_FORCE_LOCK= 1,
321
+ p_RX_CDR_RESET_TIME= 3,
322
+ p_RX_CDR_CKP = 0xF8,
323
+ p_RX_CDR_CKI = 0x00,
324
+ p_RX_CDR_TRANS_TH = 128,
325
+ p_RX_CDR_LOCK_CFG = 0x0B,
326
+ p_RX_CDR_FREQ_ACC = 0,
327
+ p_RX_CDR_PHASE_ACC = 0,
328
+ p_RX_CDR_SET_ACC_CONFIG = 0,
329
+ p_RX_CDR_RESET_OVR = 0, p_RX_CDR_RESET = 0,
330
+ # RX Equalizer
331
+ p_RX_EN_EI_DETECTOR_OVR = 0, p_RX_EN_EI_DETECTOR = 0,
332
+ p_RX_EI_BIAS = 4, p_RX_EI_BW_SEL = 4,
333
+ p_RX_AFE_PEAK = 0xF, p_RX_AFE_GAIN = 0x8, p_RX_AFE_VCMSEL = 0x4,
334
+ p_RX_CALIB_EN = 1, p_RX_CALIB_OVR = 0, p_RX_CALIB_VAL = 0,
335
+ p_RX_RTERM_VCMSEL = 4, p_RX_RTERM_PD = 0,
336
+ p_RX_EQA_RESET_TIME = 3, p_RX_EQA_RESET_OVR = 0, p_RX_EQA_RESET = 0,
337
+ p_RX_EQA_CKP_LF = 0xA3, p_RX_EQA_CKP_HF = 0xA3,
338
+ p_RX_EQA_CKP_OFFSET = 0x01,
339
+ p_RX_EN_EQA = 0, p_RX_EQA_LOCK_CFG = 0,
340
+ p_RX_TH_MON1 = 8, p_RX_TH_MON2 = 8,
341
+ p_RX_TAPW = 8, p_RX_AFE_OFFSET = 8,
342
+ p_RX_EQA_CONFIG = 0x01C0, p_RX_MON_PH_OFFSET = 0,
343
+ # PRBS
344
+ p_TX_PRBS_OVR = 0, p_TX_PRBS_SEL = 0, p_TX_PRBS_FORCE_ERR = 0,
345
+ p_RX_PRBS_OVR = 0, p_RX_PRBS_SEL = 0, p_RX_PRBS_CNT_RESET = 0,
346
+ # Loopback configuration
347
+ p_TX_PMA_LOOPBACK = 0, p_TX_PCS_LOOPBACK = 0,
348
+ p_RX_PMA_LOOPBACK = 0, p_RX_PCS_LOOPBACK = 0,
349
+ p_RX_BUF_RESET_TIME = 0x3,
350
+ p_RX_EN_EQA_EXT_VALUE = 0x0,
351
+ p_RX_EYE_MEAS_EN =0x0,
352
+ p_RX_EYE_MEAS_CFG = 0,
353
+ p_RX_DATA_SEL = 0x0,
354
+ p_RX_BUF_BYPASS = 0x0,
355
+ p_RX_LOOPBACK_OVR= 0x0,
356
+ p_RX_RESET_OVR= 0x0,
357
+ p_RX_RESET= 0x0,
358
+ p_RX_PMA_RESET_OVR= 0x0,
359
+ p_RX_PMA_RESET= 0x0,
360
+ p_RX_PCS_RESET_OVR=0x0,
361
+ p_RX_PCS_RESET= 0x0,
362
+ p_RX_BUF_RESET_OVR= 0x0,
363
+ p_RX_BUF_RESET= 0x0,
364
+ )
365
+ # SERDES I/O port connections
366
+ serdes_params.update(
367
+ # Clocks & loopback
368
+ i_TX_CLK_I = ClockSignal("tx_half"),
369
+ i_RX_CLK_I = ClockSignal("rx"),
370
+ o_PLL_CLK_O = self.txoutclk,
371
+ o_RX_CLK_O = self.rxoutclk,
372
+ i_LOOPBACK_I = 0b010 if internal_loopback else 0b000,
373
+
374
+ # Resets
375
+ i_TX_RESET_I = tx_reset,
376
+ i_RX_RESET_I = rx_reset,
377
+ i_RX_PMA_RESET_I = 0,
378
+ i_RX_EQA_RESET_I = 0,
379
+ i_RX_CDR_RESET_I = 0,
380
+ i_RX_PCS_RESET_I = 0,
381
+ i_RX_BUF_RESET_I = 0,
382
+ i_TX_PCS_RESET_I = 0,
383
+ i_TX_PMA_RESET_I = 0,
384
+ i_PLL_RESET_I = pll_reset,
385
+
386
+ # TX data & controls
387
+ i_TX_DATA_I = Cat(tx_bus[0:8], tx_bus[10:18]),
388
+ i_TX_CHAR_IS_K_I = 0,
389
+ i_TX_CHAR_DISPMODE_I = Cat(tx_bus[9], tx_bus[23]),
390
+ i_TX_CHAR_DISPVAL_I = Cat(tx_bus[8], tx_bus[22]),
391
+ i_TX_POWER_DOWN_N_I = 1,
392
+ i_TX_POLARITY_I = tx_polarity,
393
+ i_TX_ELEC_IDLE_I = 0,
394
+ i_TX_DETECT_RX_I = 1,
395
+ i_TX_PRBS_SEL_I = _tx_prbs_config,
396
+ i_TX_PRBS_FORCE_ERR_I = _tx_prbs_force_err,
397
+
398
+ o_TX_RESET_DONE_O = tx_reset_done,
399
+ o_TX_BUF_ERR_O = tx_buf_err,
400
+ o_TX_DETECT_RX_DONE_O = tx_detect_rx_done,
401
+ o_TX_DETECT_RX_PRESENT_O = tx_detect_rx_present,
402
+
403
+ # RX data & controls
404
+ i_RX_POWER_DOWN_N_I = 1,
405
+ i_RX_POLARITY_I = rx_polarity,
406
+ i_RX_EN_EI_DETECTOR_I = 0,
407
+ i_RX_COMMA_DETECT_EN_I = rx_comma_detect_en,
408
+ i_RX_SLIDE_I = 0,
409
+ i_RX_MCOMMA_ALIGN_I = rx_comma_detect_en,
410
+ i_RX_PCOMMA_ALIGN_I = rx_comma_detect_en,
411
+ i_RX_PRBS_SEL_I = _rx_prbs_config,
412
+ i_RX_PRBS_CNT_RESET_I = _rx_prbs_pause,
413
+
414
+ o_RX_DATA_O = Cat(rx_bus[0:8], rx_bus[10:18]),
415
+ o_RX_PRBS_ERR_O = rx_prbs_err,
416
+ o_RX_BUF_ERR_O = rx_buf_err,
417
+ o_RX_RESET_DONE_O = rx_reset_done,
418
+
419
+ # register file
420
+ i_REGFILE_CLK_I = 0,
421
+ i_REGFILE_WE_I = 0,
422
+ i_REGFILE_EN_I = 0,
423
+ i_REGFILE_ADDR_I = 0,
424
+ i_REGFILE_DI_I = 0,
425
+ i_REGFILE_MASK_I = 0,
426
+ o_REGFILE_DO_O = regfile_do,
427
+ o_REGFILE_RDY_O = regfile_rdy,
428
+ )
429
+
430
+ # Connect SERDES to physical I/O pads if provided
431
+ if tx_pads is not None and hasattr(tx_pads, "p"):
432
+ serdes_params.update({o_TXP: tx_pads.p, o_TXN: tx_pads.n})
433
+ if rx_pads is not None and hasattr(rx_pads, "p"):
434
+ serdes_params.update({i_RXP: rx_pads.p, i_RXN: rx_pads.n})
435
+ # Instantiate the CC_SERDES primitive with all parameters
436
+ self.specials += Instance("CC_SERDES", **serdes_params)
437
+ def add_stream_endpoints(self):
438
+
439
+ # Create stream endpoints for data (each with nwords*8 data bits and nwords control bits for K)
440
+ self.sink = stream.Endpoint([("data", 8*self.nwords), ("ctrl", self.nwords)])
441
+ self.source = stream.Endpoint([("data", 8*self.nwords), ("ctrl", self.nwords)])
442
+
443
+ self.comb += self.sink.ready.eq(1)
444
+ self.comb += self.source.valid.eq(1)
445
+ for i in range(self.nwords):
446
+ self.comb += [
447
+ self.encoder.d[i].eq(self.sink.data[8*i:8*(i+1)]),
448
+ self.encoder.k[i].eq(self.sink.ctrl[i])
449
+ ]
450
+ self.sync.rx += [
451
+ self.source.data[8*i:8*(i+1)].eq(self.decoders[i].d),
452
+ self.source.ctrl[i].eq(self.decoders[i].k)
453
+ ]
454
+ def add_controls(self, auto_enable=True):
455
+ self._tx_enable = CSRStorage(fields=[CSRField("enable", size=1, reset=int(auto_enable), description="TX Enable")])
456
+ self._rx_enable = CSRStorage(fields=[CSRField("enable", size=1, reset=int(auto_enable), description="RX Enable")])
457
+ self._tx_ready = CSRStatus(fields=[CSRField("ready", size=1, description="TX Ready (PLL/SerDes locked)")])
458
+ self._rx_ready = CSRStatus(fields=[CSRField("ready", size=1, description="RX Ready (CDR locked)")])
459
+ self._tx_prbs_config = CSRStorage(size=2, description="TX PRBS Configuration (0: PRBS off)")
460
+ self._rx_prbs_config = CSRStorage(size=2, description="RX PRBS Configuration (must match TX)")
461
+ self._rx_prbs_pause = CSRStorage(size=1, description="Pause RX PRBS Checker")
462
+ self._rx_prbs_errors = CSRStatus(32, description="RX PRBS Error Count")
463
+ self.comb += [
464
+ self.tx_enable.eq(self._tx_enable.fields.enable),
465
+ self.rx_enable.eq(self._rx_enable.fields.enable),
466
+ self._tx_ready.fields.ready.eq(self.tx_ready),
467
+ self._rx_ready.fields.ready.eq(self.rx_ready),
468
+ self.tx_prbs_config.eq(self._tx_prbs_config.storage),
469
+ self.rx_prbs_config.eq(self._rx_prbs_config.storage),
470
+ self.rx_prbs_pause.eq(self._rx_prbs_pause.storage),
471
+ self._rx_prbs_errors.status.eq(self.rx_prbs_errors)
472
+ ]
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/4.migen/litex/litex-boards/litex_boards/platforms/colognechip_gatemate_evb.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of LiteX-Boards.
3
+ #
4
+ # Copyright (c) 2023 Gwenhael Goavec-merou<gwenhael.goavec-merou@trabucayre.com>
5
+ # SPDX-License-Identifier: BSD-2-Clause
6
+
7
+ # Board documentation/schematics:
8
+ # https://colognechip.com/docs/ds1003-gatemate1-evalboard-3v1-latest.pdf
9
+
10
+ from litex.build.generic_platform import *
11
+ from litex.build.colognechip.platform import CologneChipPlatform
12
+ from litex.build.openfpgaloader import OpenFPGALoader
13
+
14
+ # IOs ----------------------------------------------------------------------------------------------
15
+
16
+ _io = [
17
+ # Clk / Rst
18
+ ("clk10", 0, Pins("IO_SB_A8"), Misc("SCHMITT_TRIGGER=true")),
19
+
20
+ # Leds
21
+ ("user_led_n", 0, Pins("IO_EB_B1")),
22
+ ("user_led_n", 1, Pins("IO_EB_B2")),
23
+ ("user_led_n", 2, Pins("IO_EB_B3")),
24
+ ("user_led_n", 3, Pins("IO_EB_B4")),
25
+ ("user_led_n", 4, Pins("IO_EB_B5")),
26
+ ("user_led_n", 5, Pins("IO_EB_B6")),
27
+ ("user_led_n", 6, Pins("IO_EB_B7")),
28
+ ("user_led_n", 7, Pins("IO_EB_B8")),
29
+
30
+ # Button
31
+ ("user_btn_n", 0, Pins("IO_EB_B0")),
32
+
33
+ # SPIFlash
34
+ ("spiflash", 0,
35
+ Subsignal("cs_n", Pins("IO_WA_A8")),
36
+ Subsignal("clk", Pins("IO_WA_B8")),
37
+ Subsignal("miso", Pins("IO_WA_B7")),
38
+ Subsignal("mosi", Pins("IO_WA_A7")),
39
+ Subsignal("wp", Pins("IO_WA_B6")),
40
+ Subsignal("hold", Pins("IO_WA_B6")),
41
+ ),
42
+ ("spiflash4x", 0,
43
+ Subsignal("cs_n", Pins("IO_WA_A8")),
44
+ Subsignal("clk", Pins("IO_WA_B8")),
45
+ Subsignal("dq", Pins("IO_WA_B7 IO_WA_A7 IO_WA_B6 IO_WA_B6")),
46
+ ),
47
+
48
+ # HyperRAM
49
+ ("hyperram", 0,
50
+ Subsignal("dq", Pins("IO_WB_A5 IO_WB_B5 IO_WB_A6 IO_WB_B6 IO_WB_A7 IO_WB_B7 IO_WB_A8 IO_WB_B8")),
51
+ Subsignal("rwds", Pins("IO_WB_B4")),
52
+ Subsignal("cs_n", Pins("IO_WB_B0")),
53
+ Subsignal("rst_n", Pins("IO_WB_A2")),
54
+ Subsignal("clk_p", Pins("IO_WB_A3")),
55
+ Subsignal("clk_n", Pins("IO_WB_B3")),
56
+ ),
57
+ ]
58
+
59
+ # Connectors ---------------------------------------------------------------------------------------
60
+
61
+ _connectors = [
62
+ ("PMODA", "IO_NB_A0 IO_NB_A1 IO_NB_A2 IO_NB_A3 IO_NB_B0 IO_NB_B1 IO_NB_B2 IO_NB_B3"),
63
+ ("PMODB", "IO_NB_A4 IO_NB_A5 IO_NB_A6 IO_NB_A7 IO_NB_B4 IO_NB_B5 IO_NB_B6 IO_NB_B7"),
64
+ ("io_na", "IO_NA_A0 IO_NA_B0",
65
+ "IO_NA_A1 IO_NA_B1",
66
+ "IO_NA_A2 IO_NA_B2",
67
+ "IO_NA_A3 IO_NA_B3",
68
+ "IO_NA_A4 IO_NA_B4",
69
+ "IO_NA_A5 IO_NA_B5",
70
+ "IO_NA_A6 IO_NA_B6",
71
+ "IO_NA_A7 IO_NA_B7",
72
+ "IO_NA_A8 IO_NA_B8"),
73
+ ("io_nb", "IO_NB_A4 IO_NB_A5",
74
+ "IO_NB_A6 IO_NB_A7",
75
+ "IO_NB_B4 IO_NB_B5",
76
+ "IO_NB_B6 IO_NB_B7"),
77
+ ("io_ea", "IO_EA_A0 IO_EA_B0",
78
+ "IO_EA_A1 IO_EA_B1",
79
+ "IO_EA_A2 IO_EA_B2",
80
+ "IO_EA_A3 IO_EA_B3",
81
+ "IO_EA_A4 IO_EA_B4",
82
+ "IO_EA_A5 IO_EA_B5",
83
+ "IO_EA_A6 IO_EA_B6",
84
+ "IO_EA_A7 IO_EA_B7",
85
+ "IO_EA_A8 IO_EA_B8"),
86
+ ("io_sa", "IO_SA_A0 IO_SA_B0",
87
+ "IO_SA_A1 IO_SA_B1",
88
+ "IO_SA_A2 IO_SA_B2",
89
+ "IO_SA_A3 IO_SA_B3",
90
+ "IO_SA_A4 IO_SA_B4",
91
+ "IO_SA_A5 IO_SA_B5",
92
+ "IO_SA_A6 IO_SA_B6",
93
+ "IO_SA_A7 IO_SA_B7",
94
+ "IO_SA_A8 IO_SA_B8"),
95
+ ("io_sb", "IO_SB_A0 IO_SB_B0",
96
+ "IO_SB_A1 IO_SB_B1",
97
+ "IO_SB_A2 IO_SB_B2",
98
+ "IO_SB_A3 IO_SB_B3",
99
+ "IO_SB_A4 IO_SB_B4",
100
+ "IO_SB_A5 IO_SB_B5",
101
+ "IO_SB_A6 IO_SB_B6",
102
+ "IO_SB_A7 IO_SB_B7",
103
+ "IO_SB_A8 IO_SB_B8"),
104
+
105
+ ("io_wc", "IO_WC_A0 IO_WC_B0",
106
+ "IO_WC_A1 IO_WC_B1",
107
+ "IO_WC_A2 IO_WC_B2",
108
+ "IO_WC_A3 IO_WC_B3",
109
+ "IO_WC_A4 IO_WC_B4",
110
+ "IO_WC_A5 IO_WC_B5",
111
+ "IO_WC_A6 IO_WC_B6",
112
+ "IO_WC_A7 IO_WC_B7",
113
+ "IO_WC_A8 IO_WC_B8"),
114
+ ]
115
+
116
+ # PMODS --------------------------------------------------------------------------------------------
117
+
118
+ def usb_pmod_io(pmod):
119
+ return [
120
+ # USB-UART PMOD: https://store.digilentinc.com/pmod-usbuart-usb-to-uart-interface/
121
+ ("usb_uart", 0,
122
+ Subsignal("tx", Pins(f"{pmod}:1")),
123
+ Subsignal("rx", Pins(f"{pmod}:2")),
124
+ ),
125
+ ]
126
+
127
+ # Platform -----------------------------------------------------------------------------------------
128
+
129
+ class Platform(CologneChipPlatform):
130
+ default_clk_name = "clk10"
131
+ default_clk_period = 1e9/10e6
132
+
133
+ def __init__(self, toolchain="colognechip"):
134
+ CologneChipPlatform.__init__(self, "CCGM1A1", _io, _connectors, toolchain=toolchain)
135
+
136
+ def create_programmer(self):
137
+ return OpenFPGALoader("gatemate_evb_jtag")
138
+
139
+ def do_finalize(self, fragment):
140
+ CologneChipPlatform.do_finalize(self, fragment)
141
+ self.add_period_constraint(self.lookup_request("clk10", loose=True), 1e9/10e6)
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/4.migen/litex/litex-boards/litex_boards/targets/colognechip_gatemate_evb.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ #
4
+ # This file is part of LiteX-Boards.
5
+ #
6
+ # Copyright (c) 2023 Gwenhael Goavec-merou<gwenhael.goavec-merou@trabucayre.com>
7
+ # SPDX-License-Identifier: BSD-2-Clause
8
+
9
+ from migen import *
10
+
11
+ from litex.gen import *
12
+
13
+ from litex_boards.platforms import colognechip_gatemate_evb
14
+
15
+ from litex.build.io import CRG
16
+
17
+ from litex.soc.cores.clock.colognechip import GateMatePLL
18
+ from litex.soc.integration.soc_core import *
19
+ from litex.soc.integration.builder import *
20
+
21
+ from litex.build.generic_platform import Pins
22
+
23
+ from litex.soc.cores.led import LedChaser
24
+
25
+ # CRG ----------------------------------------------------------------------------------------------
26
+
27
+ class _CRG(LiteXModule):
28
+ def __init__(self, platform, sys_clk_freq):
29
+ self.rst = Signal()
30
+ rst_n = Signal()
31
+ self.cd_sys = ClockDomain()
32
+
33
+ # # #
34
+
35
+ # Clk / Rst
36
+ clk10 = platform.request("clk10")
37
+ self.rst = ~platform.request("user_btn_n", 0)
38
+
39
+ self.specials += Instance("CC_USR_RSTN", o_USR_RSTN = rst_n)
40
+
41
+ # PLL
42
+ self.pll = pll = GateMatePLL(perf_mode="economy")
43
+ self.comb += pll.reset.eq(~rst_n | self.rst)
44
+ pll.register_clkin(clk10, 10e6)
45
+ pll.create_clkout(self.cd_sys, sys_clk_freq)
46
+
47
+ # BaseSoC ------------------------------------------------------------------------------------------
48
+
49
+ class BaseSoC(SoCCore):
50
+ def __init__(self, sys_clk_freq=48e6,
51
+ # with_led_chaser = False,
52
+ with_serdes=False,
53
+ **kwargs):
54
+ platform = colognechip_gatemate_evb.Platform()
55
+
56
+ # USBUART PMOD as Serial--------------------------------------------------------------------
57
+ platform.add_extension(colognechip_gatemate_evb.usb_pmod_io("PMODB"))
58
+ kwargs["uart_name"] = "usb_uart"
59
+
60
+ # CRG --------------------------------------------------------------------------------------
61
+ self.crg = _CRG(platform, sys_clk_freq)
62
+
63
+ # SoCCore ----------------------------------------------------------------------------------
64
+ SoCCore.__init__(self, platform, sys_clk_freq, ident="LiteX SoC on GateMate EVB", **kwargs)
65
+
66
+ # Leds -------------------------------------------------------------------------------------
67
+ # if with_led_chaser:
68
+ # self.leds = LedChaser(
69
+ # pads = platform.request_all("user_led_n"),
70
+ # sys_clk_freq = sys_clk_freq)
71
+
72
+ if with_serdes:
73
+ from liteiclink.serdes.serdes_gm import SerDesGM
74
+ serdes = SerDesGM(sys_clk_freq=sys_clk_freq,
75
+ refclk_freq=125e6,
76
+ linerate=1.25e9,
77
+ internal_loopback=False)
78
+ self.submodules += serdes
79
+ serdes.add_stream_endpoints()
80
+ serdes.add_controls()
81
+ leds = platform.request_all("user_led_n")
82
+ self.comb += [
83
+ leds[0].eq(serdes.rx_reset_done_n), # LED0 ← RX_RESET_DONE_O_N
84
+ leds[1].eq(serdes.tx_reset_done_n), # LED1 ← TX_RESET_DONE_O_N
85
+ leds[2].eq(serdes.tx_detect_rx_done_n), # LED2 ← TX_DETECT_RX_DONE_O_N
86
+ leds[3].eq(serdes.tx_detect_rx_present_n), # LED3 ← TX_DETECT_RX_PRESENT_O_N
87
+ leds[4].eq(serdes.rx_prbs_err_n), # LED4 ← RX_PRBS_ERR_O_N
88
+ leds[5].eq(serdes.rx_buf_err_n), # LED5 ← RX_BUF_ERR_O_N
89
+ leds[6].eq(serdes.tx_buf_err_n), # LED6 ← TX_BUF_ERR_O_N
90
+ leds[7].eq(~serdes.tx_ready) # LED7 ← “ADPLL locked” indicator
91
+ ]
92
+
93
+
94
+ # Build --------------------------------------------------------------------------------------------
95
+
96
+ def main():
97
+ from litex.build.parser import LiteXArgumentParser
98
+ parser = LiteXArgumentParser(platform=colognechip_gatemate_evb.Platform, description="LiteX SoC on Gatemate EVB")
99
+ parser.add_target_argument("--sys-clk-freq", default=24e6, type=float, help="System clock frequency.")
100
+ parser.add_target_argument("--flash", action="store_true", help="Flash bitstream.")
101
+ parser.add_target_argument("--with-serdes", action="store_true", help="Enable SERDES (1.25 Gbps transceiver loopback test).")
102
+ args = parser.parse_args()
103
+
104
+
105
+ soc = BaseSoC(
106
+ sys_clk_freq = args.sys_clk_freq,
107
+ with_serdes = args.with_serdes,
108
+ **parser.soc_argdict)
109
+ builder = Builder(soc, **parser.builder_argdict)
110
+ if args.build:
111
+ builder.build(**parser.toolchain_argdict)
112
+
113
+ if args.load:
114
+ prog = soc.platform.create_programmer()
115
+ prog.load_bitstream(builder.get_bitstream_filename(mode="sram"))
116
+
117
+ if args.flash:
118
+ from litex.build.openfpgaloader import OpenFPGALoader
119
+ prog = OpenFPGALoader("gatemate_evb_spi")
120
+ prog.flash(0, builder.get_bitstream_filename(mode="flash"))
121
+
122
+ if __name__ == "__main__":
123
+ main()
chili-chips-ba_openCologne/7.SerDes/2.liteiclink/README.md ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lite IC Link
2
+ ## Block Diagram
3
+
4
+ ```
5
+ ┌────────────────────────────────────────────────────────────────────────────┐
6
+ │ sys_clk Domain │
7
+ │────────────────────────────────────────────────────────────────────────────│
8
+ │ • Inputs: │
9
+ │ – sys_clk │
10
+ │ – CSR writes: _tx_enable(1), _rx_enable(1), │
11
+ │ _tx_prbs_config(2), _rx_prbs_config(2), _rx_prbs_pause(1) │
12
+ │ • CSRStatus reads: _tx_ready(1), _rx_ready(1), _rx_prbs_errors(32) │
13
+ │ • MultiReg synchronizers → “tx” and “rx” clock domains │
14
+ │ • Reset & Lock FSM: │
15
+ │ - reset_cnt → adpll_reset │
16
+ │ - lock_cnt → cdr_locked │
17
+ │ - drives tx_reset_done → tx_ready, rx_reset_done → rx_ready │
18
+ └──────────────────────────────────┬─────────────────────────────────────────┘
19
+ |
20
+ ┌───────────────────────────┐ | ┌───────────────────────────┐
21
+ │ Clock Buffering | | │ Clock Buffering |
22
+ │───────────────────────────| | │───────────────────────────|
23
+ │ • Instance CC_BUFG: |◀────────┘───────────────▶│ • Instance CC_BUFG: |
24
+ | - txoutclk → cd_tx.clk │ | - rxoutclk → cd_rx.clk │
25
+ └────────────┬──────────────┘ └─────────────┬─────────────┘
26
+ | |
27
+ ┌───────────────────────────────────▼──────────────────────┐ ┌────────────────────────────▼─────────────────────────────┐
28
+ │ cd_tx Domain | │ cd_rx Domain |
29
+ │──────────────────────────────────────────────────────────| │──────────────────────────────────────────────────────────|
30
+ │ 1) 8b/10b Encoder (ClockDomainsRenamer “tx”) | │ 1) Bus Unpacking │
31
+ │ – Inputs: sink.data[8·nbytes], sink.ctrl[nbytes] │ │ – rx_data[8*i:8*(i+1)] ← rx_bus[8*i:8*(i+1)] |
32
+ │ – Outputs: encoder.output (10-bit symbols + K flags) │ │ – disp_flags (K bits) |
33
+ │ │ │ │
34
+ │ 2) PRBSTX │ │ 2) PRBSRX │
35
+ │ – i ← encoder.output │ │ – i ← rx_data │
36
+ │ – config ← synced tx_prbs_config │ │ – config ← synced rx_prbs_config │
37
+ │ – o → PRBS bit-stream │ │ – errors → MultiReg → sys_clk (rx_prbs_errors) │
38
+ │ │ │ │
39
+ │ 3) Datapath MUX │ │ 3) 8b/10b Decoders │
40
+ │ – If prbs_config ≠ 0: tx_data ← PRBS.o │ │ – d,i ← rx_data, disp_flags │
41
+ │ Else: tx_data ← encoder.output | │ – outputs: decoder.d → source.data, |
42
+ | | | decoder.k → source.ctrl │
43
+ | │ │ 4) source.valid = 1 │
44
+ │ 4) Bus Packin │ └─────────────────────────┬────────────────────────────────┘
45
+ │ – tx_bus[8*i:8*(i+1)] ← tx_data[8*i:8*(i+1) │ |
46
+ │ │ |
47
+ │ 5) sink.ready = 1 | |
48
+ └─────────────────────────┬────────────────────────────────┘ |
49
+ | |
50
+ | |
51
+ | |
52
+ | |
53
+ ┌───────────▼────────────────────────────────────────────────────────────────▼───────────────┐
54
+ │ CC_SERDES Primitive │
55
+ │────────────────────────────────────────────────────────────────────────────────────────────│
56
+ │ • Params p_PLL_…, p_TX_…, p_RX_…, loopback, 8b/10b enable, comma align… │
57
+ │ │
58
+ │ • Clocks & resets: │
59
+ │ – i_TX_CLK_I = cd_tx.clk │
60
+ │ – i_TX_RESET_I = tx_reset (from FSM) │
61
+ │ – o_TX_RESET_DONE_O → tx_reset_done │
62
+ │ – o_PLL_CLK_O → txoutclk │
63
+ │ – i_RX_CLK_I = cd_rx.clk │
64
+ │ – i_RX_RESET_I = rx_reset │
65
+ │ – o_RX_RESET_DONE_O → rx_reset_done │
66
+ │ – o_RX_CLK_O → rxoutclk │
67
+ │ │
68
+ │ • Data I/O: │
69
+ │ – i_TX_DATA_I = tx_bus │
70
+ │ – o_RX_DATA_O = rx_bus │
71
+ │ – i_LOOPBACK_I = internal_loopback ? 0b010 : 0b000 │
72
+ │ │
73
+ │ • Physical pads (optional): │
74
+ │ – o_TXP/o_TXN │
75
+ │ – i_RXP/i_RXN │
76
+ └────────────────────────────────────────────────────────────────────────────────────────────┘
77
+
78
+
79
+ ┌─────────────────────────────────────────────────────────────────────────────────────────────────────────┐
80
+ │ Stream Interface │
81
+ │─────────────────────────────────────────────────────────────────────────────────────────────────────────│
82
+ │ • sink Endpoint (sys_clk): │
83
+ │ – data[8·nbytes] → cd_tx.encoder.d │
84
+ │ – ctrl[nbytes] → cd_tx.encoder.k │
85
+ │ – ready = 1 │
86
+ │ • source Endpoint (cd_rx): │
87
+ │ – data[8·nbytes] ← cd_rx.decoder.d │
88
+ │ – ctrl[nbytes] ← cd_rx.decoder.k │
89
+ │ – valid = 1 │
90
+ └─────────────────────────────────────────────────────────────────────────────────────────────────────────┘
91
+
92
+ ```
93
+
94
+
95
+ ## Workflow Overview
96
+ First, let’s dive into the 2.liteiclink folder and walk through its structure so you can see how each component fits together and how the overall build process comes together
97
+
98
+ ### 2.sw
99
+
100
+ In the [2.sw](https://github.com/chili-chips-ba/openCologne/tree/main/7.SerDes/2.liteiclink/2.sw) is a modified version of the [LiteX Demo Application](https://github.com/enjoy-digital/litex/tree/master/litex/soc/software/demo) that will include generated CSR from the migen target file in the `main.c` function. There lie the control function for the datapath in the bare-metal C.
101
+ The UART console is built upon the official demo application.
102
+
103
+ ### 3.build
104
+
105
+ Here in the [3.build](https://github.com/chili-chips-ba/openCologne/tree/main/7.SerDes/2.liteiclink/3.build) folder we have the [Makefile](https://github.com/chili-chips-ba/openCologne/blob/main/7.SerDes/2.liteiclink/3.build/Makefile) that divides the LiteX workflow into different parts. Running `make help` gives self-exmplanatory commands:
106
+
107
+ ```
108
+ $ make help
109
+ Usage:
110
+ make open-target file=<name>
111
+ make open-example file=<proj>
112
+ make build-board [FREQ=..] [OPTIONS='..']
113
+ make load [FREQ=..] [OPTIONS='..']
114
+ make term [PORT=..]
115
+ make build-sw [DEMO_FLAGS='..']
116
+ make sim
117
+ make view-sim
118
+ make clean-sim
119
+ make setup-ethernet [ETH_IFACE=..] [STATIC_IP=..]
120
+ make start-server
121
+ make stop-server
122
+ make litescope
123
+ make clean
124
+ make copy-migen
125
+ ```
126
+
127
+ The most important ones are:
128
+
129
+ * `make build-board` which runs the build process using Vivado (openXC7 might also be used later on). The command has parameters `FREQ` and `OPTIONS` which can be overloaded.
130
+
131
+ * `make build-sw` which compiles the bare-metal C application. The imporant note to add is to run the command after the build finishes because the compiler depends of the generated files in the `3.build/build` folder.
132
+
133
+ * `make load` simply loads the bitstream onto the FPGA via the JTAG programmer
134
+
135
+ * `make term` opens up the serial console in the terminal to control the datapth signals. The default port is `/dev/ttyUSB0` while that can be simply changed with `PORT`.
136
+
137
+ **NOTE**: Run `make term` in a seperate terminal before running `make load`
138
+
139
+ ### 4.migen
140
+ The [4.migen](https://github.com/chili-chips-ba/openCologne/tree/main/7.SerDes/2.liteiclink/4.migen) folder contains two subfolders:
141
+
142
+ * [liteiclink](https://github.com/chili-chips-ba/openCologne/tree/main/7.SerDes/2.liteiclink/4.migen/liteiclink/serdes) which has the file that should be copied in the liteiclink litex folder
143
+
144
+ * [litex_boards](https://github.com/chili-chips-ba/openCologne/tree/main/7.SerDes/2.liteiclink/4.migen/litex/litex-boards/litex_boards) which has:
145
+ [platforms](https://github.com/chili-chips-ba/openCologne/tree/main/7.SerDes/2.liteiclink/4.migen/litex/litex-boards/litex_boards/platforms) which has the specific platform file that specifies the pins of the board
146
+ [targets](https://github.com/chili-chips-ba/openCologne/tree/main/7.SerDes/2.liteiclink/4.migen/litex/litex-boards/litex_boards/targets) has the target file that specifies all of the important parts of the CPU design and instantiates the SoC.
147
+
148
+ **NOTE**: Right now you need to copy these subfolders with the files manually in your LiteX installation folder in `litex/litex_board/litex-boards`.
chili-chips-ba_openCologne/7.SerDes/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SerDes App for GateMate
2
+
3
+ Design a high-speed serial, **memory-mapped Chip-to-Chip (C2C) Interconnect**. The goal of such IP is to set the stage for creating compute clusters and Hyper Cubes made of GateMate FPGAs, all physically interconnected with SerDes, with this C2C on top of it, serving as logical and transport layer.
4
+
5
+ ## References:
6
+ - CologneChip [SerDes example design](https://github.com/pu-cc/gm_serdes_lb) and latest [datasheet](https://colognechip.com/docs/ds1001-gatemate1-datasheet-latest.pdf)
7
+ - Xilinx PG046 - [Aurora 8B/10B](https://docs.amd.com/r/en-US/pg046-aurora-8b10b/Introduction?tocId=Tqe8wtK9r1zAUq13hUnVEw)
8
+ - Xilinx SP002 - [Aurora 8B/10B Protocol Spec](https://docs.amd.com/v/u/en-US/aurora_8b10b_protocol_spec_sp002)
9
+ - BerkeleyLab [ChitChat](https://berkeleylab.github.io/Bedrock/_gen_md/serial_io/chitchat/README_md.html) protocol
10
+ - LiteX [IC Link](https://github.com/enjoy-digital/liteiclink)
11
+ - [MesaBusProtocol](https://github.com/blackmesalabs/MesaBusProtocol)
12
+ - [Transputer](http://www.bitsavers.org/components/inmos/transputer/C011_Link_Adaptor.pdf)
13
+ - [LiteX 1000basex](https://github.com/pu-cc/liteeth/tree/gatemate1000basex)
14
+ - [Seding Data Structures from chip to chip](https://www.reddit.com/r/FPGA/comments/1m8gl5o/how_to_send_a_struct_from_one_dev_board_to_another)
15
+
16
+ - Timing-aware/better PNR for this high-speed design:
17
+ - [Project Peppercorn](https://github.com/YosysHQ/prjpeppercorn)
18
+ - [nextpnr for GateMate](https://github.com/YosysHQ/nextpnr/tree/gatemate)
19
+
20
+ - Primer on [Eye Diagrams](https://incompliancemag.com/eye-diagram-part1) and [Equivalent Time Sampling](https://www.tek.com/en/documents/application-note/real-time-versus-equivalent-time-sampling) (vs. real-time)
21
+
22
+ <p align="center" width="100%">
23
+ <img width="65%" src="0.doc/Eye-Diagrams.png">
24
+ </p>
25
+
26
+ - Gowin primer on SerDes Signal Integrity ([SI](https://www.gowinsemi.com/en/market/market_detail/48)) measurements
27
+
28
+ - Altera [Serial Link Analyzer](https://www.altera.com/products/development-tools/quartus-prime/advanced-link-analyzer)
29
+
30
+ - Xilinx UG908 - In-System [IBERT](https://docs.amd.com/r/en-US/ug908-vivado-programming-debugging/Using-Vivado-Serial-I/O-Analyzer-to-Debug-the-Design)
31
+
32
+
33
+ ## Plan of Record
34
+ Having thoroughly studied all options, the developers presented them in a project meeting on _July 11, 2025_, where team unanimously decided for the GateMate Chip2Chip SerDes:
35
+ - not to mimic the semi-proprietary _Xilinx/AMD Aurora_
36
+ - not to be based on _BerkeleyLab ChitChat_
37
+ - not to be based on _MesaBusProtocol_
38
+ - not to invent _our own scheme_ (which was the original plan of Chili.CHIPS*ba developers)
39
+ - but rather to port `LiteX IC Link`, thus honoring CologneChip guidance and strong preference **<== WINNER!**
40
+
41
+ The _IC Link_ comes with a worked out interface to the CPU. Its interface to SerDes will leverage from Patrick's _1000basex Ethernet MAC_ project. The best part of the _IC Link_ is that it opens the full power of LiteX integration, making it available for CologneChip customers almosts instantly, and so with minimal coding burden. As such, the _IC Link_ is the Chip2Chip interconnect that CologneChip would benefit the most from for their SerDes.
42
+
43
+ Given that GateMate proprietary (aka "legacy") PnR is rather unreliable and insensitive to timing constraints, while the new opensource PnR (Project Peppercorn) has already saved the day for our WP9-[BetrustedSOC](https://github.com/chili-chips-ba/openCologne/tree/main/9.BetrustedSOC), the _Chip2Chip SerDes_ will be delivered solely and exclusively for the _nextpnr_.
44
+
45
+
46
+ For details on the work completed so far and the planned next steps, please refer to the [4.liteiclink](https://github.com/chili-chips-ba/openCologne/tree/main/7.SerDes/4.liteiclink) section of the repository.
47
+
48
+ ## Implementation
49
+ We strongly recommend to start with standalone [SerDes loopback test](1.serdestool_by_gm/README.md) to get used to the hardware platform, SerDes settings, cabling and work with RF-class signaling in general.
50
+
51
+ Then move onto our [Lite IC Link](2.liteiclink/README.md) port for GateMate SerDes. You will find more detail in the respective project folders.
52
+
53
+ ### Public Announcements
54
+ - [2025-08-10](https://www.linkedin.com/feed/update/urn:li:activity:7359764905572376577?commentUrn=urn%3Ali%3Acomment%3A%28activity%3A7359764905572376577%2C7360217016948985856%29&dashCommentUrn=urn%3Ali%3Afsd_comment%3A%287360217016948985856%2Curn%3Ali%3Aactivity%3A7359764905572376577%29)
55
+ - [2025-02-21](https://www.linkedin.com/posts/patrick-urban-086177251_gatemate-fpga-colognechip-activity-7298662301677551616-4sw0?utm_source=share&utm_medium=member_desktop&rcm=ACoAAAJv-TcBSi_5ff0VNMrInrT-xg44YF3jnyU)
56
+
57
+ ### End of Document
chili-chips-ba_openCologne/8.StressTest/0.doc/Gowin-Arora/README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ## Gowin Documentation
2
+
3
+ This directory contains documentation for the Gowin-Arora family of FPGAs. They are direct competitors of the GateMate FPGAs.
4
+ First you may want to read this [Introductory User Guide by Mouser](https://device.report/manual/4181959).
chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/README.md ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CORESCORE - how many Servs can a FPGA serv?
2
+ ## * WORK IN PROGRESS * UNDER CONSTRUCTION *
3
+ > WHILE THIS NOTICE IS PRESENT, DON'T EXPECT DESIGN, SIM, OR ANY OTHER FILE IN HERE 2BE DOIN' WHAT IT'S SAYIN'
4
+
5
+ This is a popular metric, determining FPGA's logic capacity, routing algortihm and architectural ability to use all of the FPGA. We were able to achieve **54** cores with Fmax of **22.93 MHz**, when using `-tm 3` PnR "worst" timing setting. For comparison GW2AR-18C C8/I7 (20K LUT4) implemented **50** cores at **58 MHz** for worst timing PnR settings, bare in mind that this is a higher speed grade chip **C8/I7**.
6
+
7
+ ## Results and analysis
8
+ ### Tools disclosure
9
+ Obviously, comparing results obtained pushing the test sources through open-source yosys and propriatary synth isn't an apples to apples comparison. In an attempt to address this difference, and find the real potential of the GateMate's architecture, we conducted a reference yosys benchmark. Results of yosys synthesis are then compared to the "golden standard" propriatary syntehsis tool (Gowin). Later, all results can potentially be adjusted to account for the defficiencies in yosys. We didn't test the PnR tools since usually there are no alternatives.
10
+ Through testing, we obtained utilization figures for `1 <= core_count <= 50` for the **Gowin GW2AR-18C FPGA (20k LUT4)**.
11
+
12
+ Graphs are indicating a melting lead of propriatary tools, especially percentage-wise, but they still remain superior. The number of DFFs though, is steadily favoring the propriatary synthesis. Coming to an understanding of these results is possible only when we consider also the number of LUTRAM elements used in both implementations. Proprietary synthesis tools optimize resource usage by leveraging LUTRAM, reducing DFF consumption at the cost of additional LUTs. In contrast, Yosys relies on a basic approach using DFFs and LUTs exclusively. This results in higher LUT and DFF utilization in Yosys, as it emulates LUTRAM behavior with standard logic elements. The number of block RAMs remains unchanged and is therefore not shown. In relative perspective, yosys is far worse off for small designs, but the playing field evens out at higher utilization numbers.
13
+
14
+ ### Takeaway - not so obvious
15
+ Propriatary Gowin PnR topped out at 50 cores, utilizing only <td>11930 / 15750</td> of avaliable DFFs before reporting "fail to place 64 REGs". Taking this into account, yosys-based design would fail at 41 cores, or even earlier since the LUT usage is also increased.
16
+
17
+ Here we face a tough decision, **how to take yosys into account?** On one hand it's just 5% more LUTs and 18% more DFFs, but on the other hand it's prone to failing PnR with 20% less total logic instatiated. Since we're dealing with GateMate in our analysis, whose PnR isn't directly yosys netlist [compatible](https://github.com/chili-chips-ba/openCologne/issues/28#issuecomment-2353907213), from now on we use a 25% correction when assessing results. That would bring 41 yosys cores to 50 propriatary in Gowin.
18
+
19
+ ![figure1](absutil.png)
20
+ ![figure1](relutil.png)
21
+ ### Test results
22
+ These tests have been verified on the real system.
23
+ ```
24
+ Utilization Report
25
+
26
+ CPEs 20037 / 20480 ( 97.8 %)
27
+ -----------------------------------------------
28
+ CPE Registers 13921 / 40960 ( 34.0 %)
29
+ Flip-flops 13921
30
+ Latches 0
31
+
32
+ GPIOs 3 / 144 ( 2.1 %)
33
+ -----------------------------------------------
34
+ Single-ended 3 / 144 ( 2.1 %)
35
+ IBF 2
36
+ OBF 1
37
+ TOBF 0
38
+ IOBF 0
39
+
40
+
41
+ Block RAMs 26.0 / 32 ( 81.3 %)
42
+ -----------------------------------------------
43
+ BRAM_20K 1 / 64 ( 1.6 %)
44
+ BRAM_40K 25 / 32 ( 78.1 %)
45
+ FIFO_40K 0 / 32 ( 0.0 %)
46
+
47
+ PLLs 1 / 4 ( 25.0 %)
48
+ GLBs 1 / 4 ( 25.0 %)
49
+ SerDes 0 / 1 ( 0.0 %)
50
+ ```
51
+
52
+ Considering that only 34% of sequential logic is utilized, but all Cologne Programmable Elements (CPEs) are fully utilized, it can be concluded that nearly all combinatorial elements are consumed. This positions the 20.5k CPE CologneChip GateMate FPGA alongside other FPGAs with similar capacities.
53
+
54
+
55
+ Notably, the GateMate's architecture, with 20.5k CPEs, effectively provides 41k LUT4 equivalents, as each CPE comprises an 8-input LUT-tree, which can be configured as two 4-input L2T4 primitives. Due to the reduced number of configuration bits required by this architecture, we can compute the normalized metric of **configuration bits per core** (the lower, the better). Throughput is computed by this formula: `core_count/technology`
56
+
57
+ | FPGA Model | Core Count | Configuration Bits per Core | LUT4 Count | Technology | Throughput |
58
+ |--------------------|-----------|-----------------------------|------------|------------|-------------|
59
+ | 10CL025YU256C8G | 60 | 6666 | 25k | LP 20nm | 3 |
60
+ | CCGM1A1-BGA324 | 54 | 9102 | 41k | LP 28nm | 1.964 |
61
+ | LFE5U-25F-6BG256C | 61 | 7069 | 24.3k | LP 40nm | 1.525 |
62
+ | EP4CE10F17I7N | 54 | 5770 | 22k | 60nm | 0.9 |
63
+ | GW2AR-18C C8/I7 | 50 | 6635 | 20.7k | 55nm HS | 0.9 |
64
+
65
+
66
+ This indicates that the CCGM1A1 has a lower effective logic density per area unit, as measured by configuration bits per core. Conversely, CCGM1A1 shines in throughput per dollar, holding strong against the competition.
67
+
68
+ ## Build steps
69
+ Put Yosys and GateMate p_r in PATH, and make sure you have FuseSoC installed:
70
+ ```
71
+ pip install fusesoc
72
+ ```
73
+ Navigate to 1.corescore_cc
74
+ ```
75
+ cd 8.StressTest/1.corescore_cc/
76
+ ```
77
+ Build FuseSoC target cc_gatemate
78
+ ```
79
+ fusesoc run --target=cc_gatemate corescore
80
+ ```
81
+
82
+ At this point your design should've successfully generated a bitstream. Uploading the bitstream to your board:
83
+ ```
84
+ cd 8.StressTest/1.corescore_cc/
85
+ make program
86
+ ```
87
+ Listen to serial port at **57600 baud rate 8b no parity, 1 stop bit**, your output should be something like this, with xx ranging from `00` to `number_of_cores-1`:
88
+ ```
89
+ core xx says hello
90
+ ```
91
+
92
+ If for any reason you want to change the number of cores instantated, simply go to `fusesoc_libraries/corescore/corescore.core`, under targets find `cc_gatemate`, and change the count in the following line to a desired number of cores
93
+ ```
94
+ generate: [corescorecore: {count: 55}]
95
+ ```
96
+ **RTL functional simulation**:
97
+ If for any reason you need debugging, there's a `sim` target provided, requiring Verilator. Waveform visualisation is left to the user.
98
+
chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/corescore_0.eda.yml ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 0.2.1
2
+ name: corescore_0
3
+ toplevel: corescore_gatemate
4
+ dependencies:
5
+ ::serv:1.0.2: []
6
+ ::verilog-axis:0-r3: []
7
+ ::serving:1.0.2:
8
+ - ::serv:1.0.2
9
+ ::corescore:0:
10
+ - ::serv:1.0.2
11
+ - ::serving:1.0.2
12
+ - ::verilog-axis:0-r3
13
+ - ::corescore-corescorecore:0
14
+ ::corescore-corescorecore:0: []
15
+ parameters:
16
+ RISCV_FORMAL:
17
+ datatype: bool
18
+ paramtype: vlogdefine
19
+ SERV_CLEAR_RAM:
20
+ datatype: bool
21
+ paramtype: vlogdefine
22
+ tool_options:
23
+ gatemate:
24
+ device: CCGM1A1
25
+ yosys_synth_options:
26
+ - -nomx8
27
+ p_r_options:
28
+ - -cCP
29
+ - --verbose
30
+ - -tm 1
31
+ filters: []
32
+ flow_options: {}
33
+ hooks: {}
34
+ files:
35
+ - file_type: verilogSource
36
+ is_include_file: true
37
+ name: src/serv_1.0.2/rtl/serv_params.vh
38
+ core: ::serv:1.0.2
39
+ - file_type: verilogSource
40
+ name: src/serv_1.0.2/rtl/serv_shift.v
41
+ core: ::serv:1.0.2
42
+ - file_type: verilogSource
43
+ name: src/serv_1.0.2/rtl/serv_bufreg.v
44
+ core: ::serv:1.0.2
45
+ - file_type: verilogSource
46
+ name: src/serv_1.0.2/rtl/serv_alu.v
47
+ core: ::serv:1.0.2
48
+ - file_type: verilogSource
49
+ name: src/serv_1.0.2/rtl/serv_csr.v
50
+ core: ::serv:1.0.2
51
+ - file_type: verilogSource
52
+ name: src/serv_1.0.2/rtl/serv_ctrl.v
53
+ core: ::serv:1.0.2
54
+ - file_type: verilogSource
55
+ name: src/serv_1.0.2/rtl/serv_decode.v
56
+ core: ::serv:1.0.2
57
+ - file_type: verilogSource
58
+ name: src/serv_1.0.2/rtl/serv_mem_if.v
59
+ core: ::serv:1.0.2
60
+ - file_type: verilogSource
61
+ name: src/serv_1.0.2/rtl/serv_rf_if.v
62
+ core: ::serv:1.0.2
63
+ - file_type: verilogSource
64
+ name: src/serv_1.0.2/rtl/serv_rf_ram_if.v
65
+ core: ::serv:1.0.2
66
+ - file_type: verilogSource
67
+ name: src/serv_1.0.2/rtl/serv_rf_ram.v
68
+ core: ::serv:1.0.2
69
+ - file_type: verilogSource
70
+ name: src/serv_1.0.2/rtl/serv_state.v
71
+ core: ::serv:1.0.2
72
+ - file_type: verilogSource
73
+ name: src/serv_1.0.2/rtl/serv_top.v
74
+ core: ::serv:1.0.2
75
+ - file_type: verilogSource
76
+ name: src/serv_1.0.2/rtl/serv_rf_top.v
77
+ core: ::serv:1.0.2
78
+ - file_type: verilogSource
79
+ name: src/verilog-axis_0-r3/rtl/arbiter.v
80
+ core: ::verilog-axis:0-r3
81
+ - file_type: verilogSource
82
+ name: src/verilog-axis_0-r3/rtl/priority_encoder.v
83
+ core: ::verilog-axis:0-r3
84
+ - file_type: verilogSource
85
+ name: src/verilog-axis_0-r3/rtl/axis_arb_mux.v
86
+ core: ::verilog-axis:0-r3
87
+ - file_type: verilogSource
88
+ name: src/verilog-axis_0-r3/rtl/axis_async_fifo.v
89
+ core: ::verilog-axis:0-r3
90
+ - file_type: verilogSource
91
+ name: src/serving_1.0.2/serving/serving_arbiter.v
92
+ core: ::serving:1.0.2
93
+ - file_type: verilogSource
94
+ name: src/serving_1.0.2/serving/serving_mux.v
95
+ core: ::serving:1.0.2
96
+ - file_type: verilogSource
97
+ name: src/serving_1.0.2/serving/serving_ram.v
98
+ core: ::serving:1.0.2
99
+ - file_type: verilogSource
100
+ name: src/serving_1.0.2/serving/serving.v
101
+ core: ::serving:1.0.2
102
+ - file_type: verilogSource
103
+ name: src/corescore_0/rtl/wb2axis.v
104
+ core: ::corescore:0
105
+ - file_type: verilogSource
106
+ name: src/corescore_0/rtl/base.v
107
+ core: ::corescore:0
108
+ - file_type: verilogSource
109
+ name: src/corescore_0/rtl/emitter_uart.v
110
+ core: ::corescore:0
111
+ - file_type: CCF
112
+ name: src/corescore_0/data/cc_gatemate.ccf
113
+ core: ::corescore:0
114
+ - file_type: verilogSource
115
+ name: src/corescore_0/rtl/cc_gatemate_clock_gen.v
116
+ core: ::corescore:0
117
+ - file_type: verilogSource
118
+ name: src/corescore_0/rtl/corescore_gatemate.v
119
+ core: ::corescore:0
120
+ - file_type: verilogSource
121
+ name: src/corescore-corescorecore_0/corescorecore.v
122
+ core: ::corescore-corescorecore:0
123
+ - file_type: user
124
+ name: core_0.hex
125
+ core: ::corescore-corescorecore:0
126
+ - file_type: user
127
+ name: core_1.hex
128
+ core: ::corescore-corescorecore:0
129
+ - file_type: user
130
+ name: core_2.hex
131
+ core: ::corescore-corescorecore:0
132
+ - file_type: user
133
+ name: core_3.hex
134
+ core: ::corescore-corescorecore:0
135
+ - file_type: user
136
+ name: core_4.hex
137
+ core: ::corescore-corescorecore:0
138
+ vpi: []
chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/corescore_0_00.v ADDED
The diff for this file is too large to render. See raw diff
 
chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/corescore_0_synth.v ADDED
The diff for this file is too large to render. See raw diff
 
chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/edalize_yosys_procs.tcl ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ proc read_files {} {
2
+ read_verilog {src/serv_1.0.2/rtl/serv_shift.v}
3
+ read_verilog {src/serv_1.0.2/rtl/serv_bufreg.v}
4
+ read_verilog {src/serv_1.0.2/rtl/serv_alu.v}
5
+ read_verilog {src/serv_1.0.2/rtl/serv_csr.v}
6
+ read_verilog {src/serv_1.0.2/rtl/serv_ctrl.v}
7
+ read_verilog {src/serv_1.0.2/rtl/serv_decode.v}
8
+ read_verilog {src/serv_1.0.2/rtl/serv_mem_if.v}
9
+ read_verilog {src/serv_1.0.2/rtl/serv_rf_if.v}
10
+ read_verilog {src/serv_1.0.2/rtl/serv_rf_ram_if.v}
11
+ read_verilog {src/serv_1.0.2/rtl/serv_rf_ram.v}
12
+ read_verilog {src/serv_1.0.2/rtl/serv_state.v}
13
+ read_verilog {src/serv_1.0.2/rtl/serv_top.v}
14
+ read_verilog {src/serv_1.0.2/rtl/serv_rf_top.v}
15
+ read_verilog {src/verilog-axis_0-r3/rtl/arbiter.v}
16
+ read_verilog {src/verilog-axis_0-r3/rtl/priority_encoder.v}
17
+ read_verilog {src/verilog-axis_0-r3/rtl/axis_arb_mux.v}
18
+ read_verilog {src/verilog-axis_0-r3/rtl/axis_async_fifo.v}
19
+ read_verilog {src/serving_1.0.2/serving/serving_arbiter.v}
20
+ read_verilog {src/serving_1.0.2/serving/serving_mux.v}
21
+ read_verilog {src/serving_1.0.2/serving/serving_ram.v}
22
+ read_verilog {src/serving_1.0.2/serving/serving.v}
23
+ read_verilog {src/corescore_0/rtl/wb2axis.v}
24
+ read_verilog {src/corescore_0/rtl/base.v}
25
+ read_verilog {src/corescore_0/rtl/emitter_uart.v}
26
+ read_verilog {src/corescore_0/rtl/cc_gatemate_clock_gen.v}
27
+ read_verilog {src/corescore_0/rtl/corescore_gatemate.v}
28
+ read_verilog {src/corescore-corescorecore_0/corescorecore.v}
29
+ }
30
+
31
+ proc set_defines {} {
32
+ set defines {{CCGM 1}}
33
+
34
+ foreach d ${defines} {
35
+ set key [lindex $d 0]
36
+ set val [lindex $d 1]
37
+ verilog_defines "-D$key=$val"
38
+ }}
39
+
40
+ proc set_incdirs {} {
41
+ verilog_defaults -add -Isrc/serv_1.0.2/rtl}
42
+
43
+ proc set_params {} {
44
+ }
45
+
46
+ proc synth {top} {
47
+ synth_gatemate -nomx8 -top $top
48
+ }
49
+
50
+ set top corescore_gatemate
51
+ set name corescore_0
chili-chips-ba_openCologne/8.StressTest/1.corescore_cc/build/corescore_0/cc_gatemate-gatemate/generator_cache/corescore-corescorecore_0-74191c27a08ab212740fbebfd133ec752b0d1793bbf6f7c086d8a99a1c975264/corescorecore.v ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // THIS FILE IS AUTOGENERATED BY corescorecore_gen
2
+ // ANY MANUAL CHANGES WILL BE LOST
3
+ `default_nettype none
4
+ module corescorecore
5
+ (input wire i_clk,
6
+ input wire i_rst,
7
+ output wire [7:0] o_tdata,
8
+ output wire o_tlast,
9
+ output wire o_tvalid,
10
+ input wire i_tready);
11
+
12
+ wire [39:0] tdata;
13
+ wire [4:0] tlast;
14
+ wire [4:0] tvalid;
15
+ wire [4:0] tready;
16
+
17
+ base
18
+ #(.memfile ("core_0.hex"),
19
+ .memsize (256))
20
+ core_0
21
+ (.i_clk (i_clk),
22
+ .i_rst (i_rst),
23
+ .o_tdata (tdata[7:0]),
24
+ .o_tlast (tlast[0]),
25
+ .o_tvalid (tvalid[0]),
26
+ .i_tready (tready[0]));
27
+
28
+ base
29
+ #(.memfile ("core_1.hex"),
30
+ .memsize (256))
31
+ core_1
32
+ (.i_clk (i_clk),
33
+ .i_rst (i_rst),
34
+ .o_tdata (tdata[15:8]),
35
+ .o_tlast (tlast[1]),
36
+ .o_tvalid (tvalid[1]),
37
+ .i_tready (tready[1]));
38
+
39
+ base
40
+ #(.memfile ("core_2.hex"),
41
+ .memsize (256))
42
+ core_2
43
+ (.i_clk (i_clk),
44
+ .i_rst (i_rst),
45
+ .o_tdata (tdata[23:16]),
46
+ .o_tlast (tlast[2]),
47
+ .o_tvalid (tvalid[2]),
48
+ .i_tready (tready[2]));
49
+
50
+ base
51
+ #(.memfile ("core_3.hex"),
52
+ .memsize (256))
53
+ core_3
54
+ (.i_clk (i_clk),
55
+ .i_rst (i_rst),
56
+ .o_tdata (tdata[31:24]),
57
+ .o_tlast (tlast[3]),
58
+ .o_tvalid (tvalid[3]),
59
+ .i_tready (tready[3]));
60
+
61
+ base
62
+ #(.memfile ("core_4.hex"),
63
+ .memsize (256))
64
+ core_4
65
+ (.i_clk (i_clk),
66
+ .i_rst (i_rst),
67
+ .o_tdata (tdata[39:32]),
68
+ .o_tlast (tlast[4]),
69
+ .o_tvalid (tvalid[4]),
70
+ .i_tready (tready[4]));
71
+
72
+ axis_arb_mux
73
+ #(.S_COUNT (5),
74
+ .DATA_WIDTH (8),
75
+ .KEEP_ENABLE (0),
76
+ .KEEP_WIDTH (1),
77
+ .ID_ENABLE (0),
78
+ .ID_WIDTH (8),
79
+ .DEST_ENABLE (0),
80
+ .DEST_WIDTH (8),
81
+ .USER_ENABLE (0),
82
+ .USER_WIDTH (1),
83
+ .ARB_TYPE ("ROUND_ROBIN"),
84
+ .LSB_PRIORITY ("HIGH"))
85
+ axis_mux
86
+ (.clk (i_clk),
87
+ .rst (i_rst),
88
+ .s_axis_tdata (tdata),
89
+ .s_axis_tkeep (5'd0),
90
+ .s_axis_tvalid (tvalid),
91
+ .s_axis_tready (tready),
92
+ .s_axis_tlast (tlast),
93
+ .s_axis_tid (40'd0),
94
+ .s_axis_tdest (40'd0),
95
+ .s_axis_tuser (5'd0),
96
+ .m_axis_tdata (o_tdata),
97
+ .m_axis_tkeep (),
98
+ .m_axis_tvalid (o_tvalid),
99
+ .m_axis_tready (i_tready),
100
+ .m_axis_tlast (o_tlast),
101
+ .m_axis_tid (),
102
+ .m_axis_tdest (),
103
+ .m_axis_tuser ());
104
+
105
+ endmodule