forked from nand2mario/z386
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathz386.sv
More file actions
3327 lines (3024 loc) · 144 KB
/
Copy pathz386.sv
File metadata and controls
3327 lines (3024 loc) · 144 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// z386 - An 80386 core driven by the original 386 microcode
// nand2mario, April 2026
//
// Functional units:
// 1. Bus Interface Unit
// 2. Instruction Decode Unit (3-level instruction queue)
// 3. Prefetch Unit (16-byte prefetch queue)
// 4. Segmentation Unit
// 5. Paging Unit (including TLB)
// 6. Protection Test Unit
// 7. Control Unit (microcode sequencer)
// 8. Data Unit (ALU, register file, barrel shifter)
//
module z386
import z386_pkg::*;
(
input clk,
input reset_n,
// 32-bit bus interface (ready/valid handshake)
output [31:2] addr, // Physical address [31:2]
output [3:0] be, // Byte enables
input [31:0] din, // Data input
output [31:0] dout, // Data output
output valid, // Request valid (held until ready)
input ready, // Handshake: transfer on valid && ready
output write, // 1=write, 0=read (stable while valid)
output io, // I/O vs memory (1=I/O, 0=memory)
input resp_valid, // Read data valid (1-cycle pulse)
// Interrupts
input intr, // Maskable interrupt request
input nmi, // Non-maskable interrupt
output inta, // Interrupt acknowledge
// VIPT cache: early lookup handshake (from paging unit, 1 cycle before BIU)
output cache_lookup,
output [31:0] cache_lookup_addr,
output cache_lookup_write,
output cache_lookup_cancel,
input cache_lookup_ready,
// Debug/test control
input single_step, // Halt after each instruction (for single-step tests)
output [15:0] dbg_CS,
output [31:0] dbg_EIP,
output [31:0] dbg_CS_base,
output dbg_pe,
output dbg_vm
);
localparam bit TRACE_DEBUG_EN = 1'b0;
localparam bit TRACE_GATE_EN = 1'b0;
localparam bit TRACE_MODE_EN = 1'b0;
localparam bit TRACE_PAGING_EN = 1'b0;
localparam bit TRACE_POST8_EN = 1'b0;
localparam bit TRACE_PROT_EN = 1'b0;
localparam bit TRACE_UCODE_EN = 1'b0;
reg dbg_first_done; // Debug: first instruction finished execution
reg halted; // Tracks when the core is halted
reg [31:0] debug_ip; // Debug: IP at instruction completion
wire [31:0] dbg_addr = {addr, 2'b0}; // Debug: full 32-bit address
reg [31:0] CR0, CR2, CR3;
reg [31:0] DR6, DR7;
reg [31:0] EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI;
reg [31:0] EIP = 32'h0000FFF0; // Architectural IP (next instruction) - reset vector
wire [15:0] AX = EAX[15:0];
wire [7:0] AL = EAX[7:0];
wire [7:0] AH = EAX[15:8];
wire [15:0] CX = ECX[15:0];
wire [15:0] DX = EDX[15:0];
wire [15:0] BX = EBX[15:0];
wire [15:0] SP = ESP[15:0];
wire [15:0] BP = EBP[15:0];
wire [15:0] SI = ESI[15:0];
wire [15:0] DI = EDI[15:0];
seg_desc_t cs_seg_desc;
assign cs_seg_desc = seg_cache[SEG_CS];
wire D = cs_seg_desc.D_B; // Default operand size (0=16-bit in real mode, 1=32-bit)
// Bits: 31..22 21 20 19 18 17 16 15..14 13..12 11 10 9 8 7 6 5 4 3 2 1 0
// Rsvd ID VIP VIF AC VM RF Rsvd IOPL OF DF IF TF SF ZF 0 AF 0 PF 1 CF
reg [31:0] EFLAGS;
reg [31:0] uc_flags; // Internal ALU flags for microcode conditionals
wire DF = EFLAGS[10]; // Direction Flag (used for string ops)
reg [31:0] TMPB, TMPC, TMPD, TMPE, TMPF;
reg [31:0] TMPG, TMPH, PROTUN, CSOPCD, FSVeIP, OPROFF;
reg [31:0] SIGMA; // ALU result
reg [31:0] FLAGSB; // FLAGS backup for INT
reg [1:0] op_size; // Runtime operand size: 0=byte, 1=word, 2=dword (modifiable by BITS8/16/32)
reg [1:0] op_size_decode; // Decoded operand size (saved at i_pop, restored by BITSDE)
reg [1:0] srcreg_size; // Same as op_size most of the time, different for MOVZX/MOVSX and etc
reg [1:0] srcreg_size_decode; // Decoded srcreg_size (saved at i_pop, restored by BITSDE)
wire is_dword = (op_size == 2'd2); // Runtime dword flag
wire is_word = (op_size == 2'd1); // Runtime word flag
// ALU signals (35-bit for MUL/DIV iteration support)
reg [31:0] alu_dst, alu_src; // ALU inputs this cycle
reg [4:0] alu_op5; // ALU operation this cycle
reg [31:0] alu_src_r; // Registered alu_src for jumps (32-bit)
wire [31:0] alu_result;
// Shifter
wire [63:0] shift_result;
// ALU source data for operand access
wire [31:0] alu_src_data = read_uc_alu_source(uc_alu_src);
reg [15:0] ES = 16'h0000;
reg [15:0] CS = 16'hF000; // Reset value
reg [15:0] SS = 16'h0000;
reg [15:0] DS = 16'h0000;
reg [15:0] FS = 16'h0000;
reg [15:0] GS = 16'h0000;
reg [15:0] LDTR, TR; // Task Register
reg [31:0] SLCTR; // Selector temp used by protected-mode descriptor microcode (32-bit: LAR/LSL store full descriptor hi DWORD)
// Forward SLCTR from dest_value when being written in the same cycle
wire slctr_fwd_en = uc_exec && (uc_dest == DEST_SLCTR || uc_dest == DEST_TMP_TR) && !prot_is_ptovrr;
wire [31:0] slctr_fwd = slctr_fwd_en ? dest_value : SLCTR;
reg [31:0] desc_raw_hi; // raw high DWORD saved at TSTDES time (before barrel-shift modifies PROTUN)
reg [5:0] prot_saved_test_const; // Protection test: PTSAV saves test constant for later PTOVRR to use
seg_desc_t seg_cache [0:10]; // Indexed by SEG_* constants
wire [31:0] CS_base = seg_cache[SEG_CS].base;
wire pe = CR0[0]; // Protected mode enable
wire vm = EFLAGS[17]; // Virtual 8086 mode
assign dbg_CS = CS;
assign dbg_EIP = EIP;
assign dbg_CS_base = CS_base;
assign dbg_pe = pe;
assign dbg_vm = vm;
wire [1:0] cpl = vm ? 2'd3 : !pe ? 2'd0 : CS[1:0]; // CPL: 3 in V86, 0 in real mode
wire pg_enable = CR0[31]; // Paging enabled
wire wp_enable = CR0[16]; // Write protect
wire [31:0] page_dir_base = CR3 & 32'hFFFFF000; // Page directory base
reg [2:0] latched_pf_code; // Latched page fault error code (for LPCR microcode access)
reg [31:0] latched_pf_addr; // Latched faulting linear address (for LPCR microcode access)
wire [7:0] q_bus; // 8-bit output to decoder
wire [31:0] q_window; // 4-byte aligned window at queue head
wire pf_full;
wire pf_empty;
wire [4:0] pf_count; // Prefetch bytes currently buffered
wire [2:0] q_pop_bytes; // Pop 1/2/4 bytes from queue
wire q_flush; // Flush queue (branch/jump) - combinational for i.immediate gating
wire pe_mode_toggle_now; // CR0.PE changed this cycle: re-decode next bytes in new mode
assign pe_mode_toggle_now = uc_exec && (uc_dest == DEST_CR0) && (dest_value[0] != CR0[0]);
assign q_flush = (uc_exec && uc_buscode == BUSOP_PREF && !uc_cond_jump_taken_prev) || pe_mode_toggle_now;
wire page_fault; // Page fault (declared fully at paging unit instantiation)
wire [1:0] prot_cpl; // CPL for protection unit (declared fully near protection logic)
reg [1:0] arpl_rpl_latch; // ARPL RPL latch (declared fully near ARPL logic)
// Memory requests
wire mem_servicing; // memory request in flight
wire mem_accepted; // memory request accepted (ready pulse)
wire mem_complete_now; // combinational, request completing THIS cycle
// Prefetch ↔ paging unit toggle signals
wire pf_req_toggle;
wire [31:0] pf_linear_addr;
wire pf_ack_toggle;
wire [31:0] pf_rdata;
wire pf_fault;
//
// Microcode Sequencer State
//
// After a jump, the next micro-op still executes (delay slot) before jump takes effect.
reg [11:0] uaddr_now; // Next address, launched early to the ucode ROM
reg [11:0] uaddr; // Address being fetched in the current ucode pipeline
wire [44:0] uc; // Current microcode word + pre-computed bits (37-44)
reg [11:0] uc_addr; // Address of current uc (for debug)
// Instruction Life cycle: entry -> pop -> first -> RNI -> RNI delay slot -> inactive
wire i_entry; // Load entry point into uaddr, set init_cycle (queue NOT popped yet)
wire i_pop; // Actually pop from instruction queue (during init_cycle)
reg i_first; // First ucode execution cycle after i_pop
wire i_rni; // RNI detected in this cycle (combinational from uc bits)
reg i_rni_delay; // RNI delay slot - RNI has been executed. this is last instruction cycle
reg init_cycle; // Cycle or cycles after i_entry - uc is being latched, not yet valid
reg uc_active; // Tracks when instruction execution has begun
reg fault_suppress_delay_slot; // Fault handling: suppress delay slot after fault triggers
// i_entry: load entry point into uaddr (e.g. when RNI), set init_cycle (queue NOT popped yet)
wire i_entry_raw = (i_rni || i_rni_delay || ~uc_active) && ~halted && !stall && !decq_empty && !q_flush && !init_cycle &&
!fault_suppress_delay_slot && !interrupt_entry;
assign i_entry = i_entry_raw && !any_fault;
// i_pop: actually pop the instruction queue
wire interrupt_at_boundary = i_rni_delay && interrupt_pending && !single_step;
assign i_pop = init_cycle && !stall && !page_fault && !interrupt_at_boundary;
// Stall: hold pipeline when bus is busy AND current word needs bus/DLY, or
// WIO is waiting for interrupt.
wire stall_mem = ((mem_req_r || (mem_servicing && !mem_complete_now)) && uc_bus_or_dly);
wire stall_wio = (uc_is_wio && !interrupt_pending && !single_step);
wire stall = stall_mem || stall_wio;
wire stall_mem_uc_exec = ((mem_req_r || (mem_servicing && !mem_complete_now)) && uc_bus_or_dly);
wire stall_uc_exec = stall_mem_uc_exec || stall_wio;
// Repeat
wire prot_result_now = prot_result_valid && prot_test_inflight;
wire repeat_active = uc_is_rpt && (COUNTR[4:0] != 0 || prot_test_inflight) && !prot_result_now
&& !(uc_is_wio && interrupt_pending);
// uc_exec: master enable for microcode execution
wire uc_exec = !stall_uc_exec && !halted && uc_active && !fault_suppress_delay_slot && !interrupt_entry;
wire uc_exec_writeback = uc_exec; // local copies for reducing fanout
wire uc_exec_mul_start = uc_exec;
wire uc_exec_result = uc_exec;
wire uc_exec_shift = uc_exec;
// seg_cmd_valid: seg_unit should commit the current seg_cmd this cycle
assign seg_cmd_valid = i_pop || uc_exec;
dec_entry_t i_bus; // Decoded instruction from decoder module
wire decq_empty; // Decoder instruction queue empty
wire decq_full; // Decoder instruction queue full
// The microcode ROM contains 2560 entries of 37-bit ucode + 8-bit predecode
wire microcode_rom_ce = !stall && !repeat_active;
wire [44:0] uc_rom_q;
wire [5:0] uc_source_shift;
wire [5:0] uc_alu_src_shift;
wire [6:0] uc_aluop_shift;
assign uc = reset_n ? uc_rom_q : 45'h0;
ucode_rom microcode_rom (
.clk(clk),
.ce(microcode_rom_ce),
.addr(uaddr_now),
.q(uc_rom_q),
.q_shift_source(uc_source_shift),
.q_shift_alu_src(uc_alu_src_shift),
.q_shift_aluop(uc_aluop_shift)
);
// ROM1 decoder for instruction layout decoding
`include "pla_control.svh"
// Decoder23 PLA: Opcode → Microcode Entry Point
`include "pla_entry.svh"
wire [15:0] ea_regs_16 = decode_base_register_16(i_bus.modrm);
//=============================================================================
// Prefetch queue and Bus Interface Unit
//=============================================================================
// Forward declarations to avoid implicit wire inference in synthesis
wire [31:0] pf_flush_addr; // Prefetch flush address
wire [5:0] uc_buscode; // Bus operation code from microcode
wire [6:0] uc_dest; // Destination field from microcode
wire [5:0] uc_source; // Source field from microcode
wire [31:0] dest_value; // Destination value for writes
wire gp_fault_trigger; // GP fault trigger
wire div_overflow; // Division overflow
wire [31:0] OPR_R; // Read operand register
// stack_init_pending and OPR_W are regs, declared later
wire [11:0] prot_jump_addr; // Microcode jump address from protection unit
wire prot_jump_valid; // jump_addr is a redirect (non-zero)
wire prot_set_accessed; // N flag: Set accessed bit
wire prot_validation_ok; // M flag: Descriptor validated
wire prot_limit_check; // L flag: Perform limit check
wire prot_stack_op; // K flag: Stack operation/CPL update
wire prot_result_valid; // Pipelined result is valid (2 cycles after test)
wire prot_is_checking_test; // Result is from a "checking" test (not PTGEN)
wire pg_req_valid;
wire [31:0] pg_req_phys_addr;
wire pg_req_write;
wire [3:0] pg_req_be;
wire [31:0] pg_req_wdata;
wire pg_req_is_io;
wire pg_req_is_inta;
wire pg_req_accepted;
wire pg_req_complete;
wire [31:0] biu_rdata;
wire pg_rd_ind_active;
// BIU: thin external bus driver
biu biu_inst (
.clk(clk),
.reset_n(reset_n),
// External bus (ready/valid)
.bus_addr(addr),
.bus_be(be),
.bus_din(din),
.bus_dout(dout),
.bus_valid(valid),
.bus_write(write),
.bus_io(io),
.bus_ready(ready),
.bus_resp_valid(resp_valid),
.bus_inta(inta),
// Single request port from paging unit
.req_valid(pg_req_valid),
.req_phys_addr(pg_req_phys_addr),
.req_write(pg_req_write),
.req_be(pg_req_be),
.req_wdata(pg_req_wdata),
.req_is_io(pg_req_is_io),
.req_is_inta(pg_req_is_inta),
.req_accepted(pg_req_accepted),
.req_complete(pg_req_complete),
.rdata(biu_rdata)
);
// Prefetch Unit: 16-byte circular buffer
prefetch prefetch_inst (
.clk(clk),
.reset_n(reset_n),
// Queue output to decoder
.q_bus(q_bus),
.q_window(q_window),
.q_full(pf_full),
.q_empty(pf_empty),
.pf_count(pf_count),
.q_pop_bytes(q_pop_bytes),
// Flush
.q_flush(q_flush),
.pf_flush_addr(pf_flush_addr),
// Toggle interface to paging unit
.pf_req_toggle(pf_req_toggle),
.pf_linear_addr(pf_linear_addr),
.pf_ack_toggle(pf_ack_toggle),
.pf_rdata(pf_rdata),
.pf_fault(pf_fault),
// Control
.pf_suspend(page_fault)
);
//=============================================================================
// Instruction Decode Unit
//=============================================================================
decoder decoder_inst (
.clk (clk),
.reset_n (reset_n),
// Prefetch queue interface
.q_bus (q_bus),
.q_window (q_window),
.pf_count (pf_count),
.pf_empty (pf_empty),
.q_pop_bytes(q_pop_bytes),
// Mode signals
.D (D),
.mode_32 (pe & ~vm), // Unused by decoder, kept for port compatibility
.pe_enable (pe & ~vm), // Native protected mode: PE=1 and VM=0 (V86 uses real-mode entry points)
// Control signals
.q_flush (q_flush),
.i_pop (i_pop),
.halted (halted),
.stall (stall),
// Decoded instruction output
.i_bus (i_bus),
.decq_empty (decq_empty),
.decq_full (decq_full)
);
//=============================================================================
// Segmentation Unit
//=============================================================================
wire [3:0] mem_seg_sel;
wire descsw_mode;
wire mem_is_dtable;
wire stack_push_mode;
wire tss_access_flag;
wire [31:0] mem_linear_addr;
wire [31:0] seg_lar_result, seg_llim_result, seg_lbas_result;
// Internalized: addr_size, mem_seg_base_r, pm_seg_limit_r, mem_seg_base, mem_ea
// Segmentation unit command encoder
reg [3:0] seg_cmd;
reg [3:0] seg_cmd_target;
reg [31:0] seg_cmd_data;
wire seg_cmd_valid; // 1 when seg_cmd should execute (i_pop or uc_exec)
// Decoded instruction register (all fields from decoder, latched at i_pop)
dec_entry_t i;
wire [7:0] i_modrm = i.modrm;
wire [7:0] i_sib = i.sib;
wire i_has_modrm = i.has_modrm;
wire i_has_sib = i.has_sib;
wire [31:0] i_reg_immediate = i.immediate;
wire [31:0] i_reg_displacement = i.displacement;
wire i_reg_addr32 = i.addr32;
wire [2:0] i_seg = i.seg;
wire [2:0] i_reg_dst_reg_sel = i.dst_reg_sel;
wire [2:0] i_reg_src_reg_sel = i.src_reg_sel;
// Segmentation unit command encoder: translates raw microcode fields to commands
// Resolved modrm-based segment for DES_OS/DES_SR (used by encoder)
wire [3:0] modrm_resolved_seg = apply_seg_override_type(
calc_default_seg_type(i_modrm, i_sib, i_has_sib, i_reg_addr32), i_seg);
// Pre-computed default segment for new instruction (combinational, used by INIT_SEG)
wire [3:0] init_default_seg = i_bus.stack_op ? SEG_SS :
i_bus.has_moffs ? SEG_DS :
i_bus.has_modrm ? calc_default_seg_type(i_bus.modrm, i_bus.sib, i_bus.has_sib, i_bus.addr32) :
SEG_DS;
wire [3:0] init_final_seg = i_bus.stack_op ? init_default_seg :
apply_seg_override_type(init_default_seg, i_bus.seg);
// Pre-computed access size for limit check (replaces op_size + is_dword in seg unit)
wire [1:0] gp_access_adj = (op_size == 2'd0) ? 2'd0 : is_dword ? 2'd3 : 2'd1;
wire [31:0] ind_effective;
wire mem_op_eligible, gp_fault_mem_op, gp_fault_wr_op, ss_segment_fault;
reg copy_stack_dpl_s2, conform_dpl_s2;
reg [1:0] copy_dpl_s2;
segmentation_unit seg_unit (
.clk (clk),
.reset_n (reset_n),
// Command interface — descriptor cache manipulation
.seg_cmd_valid (seg_cmd_valid),
.seg_cmd (seg_cmd),
.seg_target (seg_cmd_target),
.seg_data (seg_cmd_data),
.desc_lo (TMPC),
.desc_hi (desc_raw_hi),
.slctr (SLCTR[15:0]),
.copy_stack_dpl_s2(copy_stack_dpl_s2),
.copy_dpl_s2 (copy_dpl_s2),
.conform_dpl_s2 (conform_dpl_s2),
.seg_cache (seg_cache),
.lar_result (seg_lar_result),
.llim_result (seg_llim_result),
.lbas_result (seg_lbas_result),
// Segment state
.seg_sel (mem_seg_sel),
.is_dtable (mem_is_dtable),
.descsw_mode (descsw_mode),
.stack_push_mode (stack_push_mode),
.tss_access_flag (tss_access_flag),
// Address translation
.pe (pe),
.vm (vm),
.cpl (cpl),
.offset (ind_effective),
.access_size (gp_access_adj),
.check_en (mem_op_eligible),
.is_mem_op (gp_fault_mem_op),
.is_write (gp_fault_wr_op),
.linear_addr (mem_linear_addr),
.seg_fault (gp_fault_trigger),
.is_stack_fault (ss_segment_fault)
);
always_comb begin
seg_cmd = SEG_CMD_NONE;
seg_cmd_target = SEG_NONE;
seg_cmd_data = dest_value;
if (init_cycle) begin
seg_cmd_target = init_final_seg;
seg_cmd_data = {30'd0, i_bus.stack_op, i_bus.addr32};
end else if ((uc_buscode == BUSOP_IND_PLUS_ALU || uc_buscode == BUSOP_IND_SRC)
&& (uc_dest == DEST_DES_OS || uc_dest == DEST_DES_SR)) begin
seg_cmd_target = modrm_resolved_seg;
end else begin
seg_cmd_target = resolve_seg_target(uc_dest, seg_reg_sel, COUNTR[5:0]);
end
if (init_cycle) begin
seg_cmd = SEG_CMD_INIT_SEG;
end else if (uc_dest == DEST_DESCSW) begin
seg_cmd = SEG_CMD_DESCSW;
end else if (uc_aluop == ALUJMP_STSSAF) begin
seg_cmd = SEG_CMD_STSSAF;
end else if (uc_aluop == ALUJMP_CTSSAF) begin
seg_cmd = SEG_CMD_CTSSAF;
end else begin
case (uc_buscode)
BUSOP_IND_PLUS_ALU,
BUSOP_IND_SRC: begin
seg_cmd = SEG_CMD_UPDATE_SEG;
// DESSTK: set clear_descsw flag in seg_data[0]
if (uc_dest == DEST_DESSTK)
seg_cmd_data = {31'd0, 1'b1};
else
seg_cmd_data = 32'd0;
end
BUSOP_SBRM: begin
if (!pe || vm)
seg_cmd = SEG_CMD_SBRM;
end
BUSOP_SAR: begin
seg_cmd = SEG_CMD_SAR;
end
BUSOP_SLIM: begin
seg_cmd = (uc_dest == DEST_DESPTR) ? SEG_CMD_SLIM_TABLE : SEG_CMD_SLIM;
end
BUSOP_SBAS: begin
if (uc_dest == DEST_DESPTR)
seg_cmd = SEG_CMD_SBAS;
end
BUSOP_SDEH: begin
if (pe && !gate_detect_cond) // use cond, not _now (uc_exec already in valid)
seg_cmd = SEG_CMD_SDEH;
end
BUSOP_SDES: begin
if (pe && !gate_detect_cond) begin
seg_cmd = SEG_CMD_SDES;
seg_cmd_data = alu_src_data;
end
end
BUSOP_SDEL: begin
if (pe && !gate_detect_cond) begin
seg_cmd = SEG_CMD_SDEL;
// SDEL's descriptor-low operand is encoded in the ALU source
// field. Most sites use TMPC, but cross-privilege CALL uses TMPD.
seg_cmd_data = alu_src_data;
end
end
BUSOP_SPCR: begin
seg_cmd = SEG_CMD_SPCR;
end
default: ;
endcase
end
end // always_comb
//=============================================================================
// Paging Unit
//=============================================================================
// Memory operation detection — pre-computed in ROM bits 39-43
wire pg_mem_busop = uc_is_mem_busop;
wire pg_is_write = uc_is_write;
wire pg_is_check_write = uc_is_check_write;
wire pg_is_word_op = uc_is_word_op;
wire pg_is_dword_op = uc_is_dword_op;
// MOV m,Sreg (8C) always writes 16 bits to memory regardless of operand size
wire seg_store_force_word = pg_is_word_op && instr_is_mov_sreg;
wire [1:0] mem_eff_size = seg_store_force_word ? 2'd1 :
pg_is_word_op ? (is_dword ? 2'd2 : 2'd1) :
pg_is_dword_op ? 2'd2 : op_size;
wire [31:0] mem_wdata = (uc_buscode == BUSOP_WR_OPR) ? OPR_R :
pg_is_word_op ? read_uc_source(uc_source) :
(uc_dest == DEST_OPR_W) ? (stack_init_pending ? read_uc_source(uc_source) : dest_value) :
OPR_W;
wire any_fault = gp_fault_trigger || div_overflow || page_fault;
reg any_fault_r; // Registered any_fault: used for deferred SIGMA/TMPeSP writes
always_ff @(posedge clk) any_fault_r <= any_fault;
wire [2:0] pg_fault_code; // Page fault error code
wire [31:0] pg_cr2_out; // Faulting address for CR2
// CR3 write detection for TLB flush
wire cr3_write = uc_exec && uc_buscode == BUSOP_IND_SRC && uc_dest == DEST_DESABS;
// IO request detection
wire io_busop_rd = (uc_buscode == BUSOP_RD_BW || uc_buscode == BUSOP_RD) && (mem_seg_sel == SEG_IO);
wire io_busop_wr = (uc_buscode == BUSOP_WR || uc_buscode == BUSOP_WR_OPR) && (mem_seg_sel == SEG_IO);
// IACK bus operation (interrupt acknowledge)
wire iack_busop = (uc_buscode == BUSOP_IACK);
// Interrupt pending: NMI has priority over INTR
wire interrupt_pending = nmi_pending || (intr_pending && EFLAGS[9]);
// STI shadow: real 386 suppresses interrupt recognition for one instruction after STI.
reg inhibit_interrupts;
// Common gate for memory/IO operations: executing and bus is free
assign mem_op_eligible = uc_exec && !mem_servicing && !mem_req_r;
wire mem_req_upcoming = mem_op_eligible && (
(pg_mem_busop && (mem_seg_sel != SEG_IO)) ||
(io_busop_rd || io_busop_wr) ||
iack_busop
);
wire mem_is_io = (mem_seg_sel == SEG_IO);
// Implicit supervisor access: descriptor table and TSS reads, cross-privilege
// stack writes use CPL=0 for paging regardless of current CPL.
wire implicit_supervisor = mem_is_dtable || (mem_seg_sel == SEG_TR) ||
descsw_mode || (vm && CS[1:0] == 2'b00);
wire [1:0] pg_cpl = implicit_supervisor ? 2'b00 : cpl;
// Registered paging unit inputs
reg mem_req_r;
reg gp_fault_r;
reg ss_fault_r;
reg [31:0] mem_linear_addr_r;
reg [1:0] mem_eff_size_r;
reg mem_write_r;
reg [31:0] mem_wdata_r;
reg mem_rd_ind_r;
reg mem_is_write_access_r;
reg mem_check_only_r;
reg [1:0] mem_cpl_r;
reg mem_is_io_r;
reg mem_is_inta_r;
reg [3:0] mem_be_r;
// Paging unit instantiation
paging_unit paging_inst (
.clk (clk),
.reset_n (reset_n),
.cr0 (CR0),
.cr3 (CR3),
.cr3_write (cr3_write),
// Memory/IO request (registered pipeline — one cycle after mem_req_upcoming)
// gp_fault_r cancels faulting requests (registered in parallel with mem_req_r)
.mem_req (mem_req_r), // valid: held until mem_accepted pulses
.mem_req_upcoming (mem_req_upcoming), // suppresses prefetch start to minimize contention
.mem_accepted (mem_accepted), // ready: request accepted this cycle
.mem_servicing (mem_servicing),
.mem_complete_now (mem_complete_now), // combinational: bus op completing this cycle
.linear_addr (mem_linear_addr_r),
.mem_op_size (mem_eff_size_r),
.mem_write (mem_write_r),
.mem_wdata (mem_wdata_r),
.mem_rd_ind (mem_rd_ind_r),
.is_write_access (mem_is_write_access_r),
.mem_check_only (mem_check_only_r),
.cpl (mem_cpl_r),
.mem_is_io (mem_is_io_r),
.mem_is_inta (mem_is_inta_r),
.mem_be (mem_be_r),
// Prefetch (toggle protocol)
.pf_req_toggle (pf_req_toggle),
.pf_ack_toggle (pf_ack_toggle),
.pf_linear_addr (pf_linear_addr),
.pf_rdata (pf_rdata),
.pf_fault (pf_fault),
// BIU interface
.biu_req_valid (pg_req_valid),
.biu_req_phys_addr (pg_req_phys_addr),
.biu_req_write (pg_req_write),
.biu_req_be (pg_req_be),
.biu_req_wdata (pg_req_wdata),
.biu_req_is_io (pg_req_is_io),
.biu_req_is_inta (pg_req_is_inta),
.biu_req_accepted (pg_req_accepted),
.biu_req_complete (pg_req_complete),
.biu_rdata (biu_rdata),
// OPR_R
.OPR_R (OPR_R),
// Status
.page_fault (page_fault),
.fault_code (pg_fault_code),
.cr2_out (pg_cr2_out),
.rd_ind_active (pg_rd_ind_active),
.cache_lookup (cache_lookup),
.cache_lookup_addr (cache_lookup_addr),
.cache_lookup_write (cache_lookup_write),
.cache_lookup_cancel(cache_lookup_cancel),
.cache_lookup_ready (cache_lookup_ready)
);
always_ff @(posedge clk) begin
if (!reset_n) begin
mem_req_r <= 1'b0;
gp_fault_r <= 1'b0;
ss_fault_r <= 1'b0;
end else begin
gp_fault_r <= gp_fault_trigger;
ss_fault_r <= ss_segment_fault;
// Don't assert mem_req_r if GP fault fires same cycle
if (mem_req_upcoming && !gp_fault_trigger)
mem_req_r <= 1'b1;
// Clear when paging unit accepts (ready pulse) or GP fault cancels
if (mem_req_r && (mem_accepted || gp_fault_r))
mem_req_r <= 1'b0;
end
if (mem_req_upcoming) begin
mem_linear_addr_r <= iack_busop ? IND : mem_linear_addr;
mem_eff_size_r <= mem_eff_size;
mem_write_r <= pg_is_write || (io_busop_wr && mem_is_io);
mem_wdata_r <= mem_wdata;
mem_rd_ind_r <= (uc_buscode == BUSOP_RD_IND);
mem_is_write_access_r <= pg_is_write || pg_is_check_write;
mem_check_only_r <= pg_is_check_write;
mem_cpl_r <= pg_cpl;
mem_is_io_r <= mem_is_io;
mem_is_inta_r <= iack_busop;
mem_be_r <= iack_busop ? 4'b1111 :
calc_be(mem_eff_size, mem_linear_addr[1:0]);
end
end
// CR3 register update
always_ff @(posedge clk) begin
if (!reset_n)
CR3 <= 32'h0;
else if (cr3_write) begin
CR3 <= alu_dst;
end
end
//=============================================================================
// Protection Unit (PLA4)
//=============================================================================
// Pipeline enable: advance PLA4 pipeline in sync with microcode.
wire prot_pipe_en = !stall;
// Protection test enable and constant routing
// aluop 0x6? range: bit3=0 is PTSAV (save only), bit3=1 fires test
wire prot_is_6x = (uc_aluop[6:4] == 3'b110);
wire prot_is_ptsav = prot_is_6x && !uc_aluop[3]; // PTSAV1(0x61), PTSAV3(0x63), PTSAV7(0x67)
wire prot_is_ptovrr = (uc_aluop == ALUJMP_PTOVRR); // 0x68: uses saved test constant
wire [5:0] prot_test_const = prot_is_ptovrr ? prot_saved_test_const : uc_alu_src[5:0];
// FPU tests (test_const 0x34, 0x38-0x3F) must fire even in real mode
wire is_fpu_prot_test = prot_test_const[5] && prot_test_const[4] && (prot_test_const[3] || prot_test_const[2]);
wire prot_test_en = uc_exec && prot_is_6x && !prot_is_ptsav && (pe || is_fpu_prot_test);
wire selector_null_wire = (slctr_fwd[15:3] == 13'b0) && !slctr_fwd[2]; // Null selector: Index=0, TI=0
wire [15:0] selector_desc_end = {slctr_fwd[15:3], 3'b111}; // Last byte offset of 8-byte descriptor
wire selector_oob_wire = slctr_fwd[2] ?
({12'h0, seg_cache[SEG_LDT].limit} < {4'h0, selector_desc_end}) : // LDT: compare against LDTR limit
(seg_cache[SEG_GDT].limit[15:0] < selector_desc_end); // GDT: compare against GDTR limit
// PROTUN forwarding
wire protun_writing = uc_exec && (uc_dest == DEST_PROTUN);
wire tstdes_set_accessed = pe && uc_exec && (uc_aluop == ALUJMP_PTOVRR);
wire [31:0] protun_write_value = read_protun_source_fast(uc_source);
wire [31:0] protun_next = (tstdes_set_accessed && protun_write_value[12]) ? (protun_write_value | 32'h100) :
protun_write_value;
wire [31:0] protun_fwd = protun_writing ? protun_next : PROTUN;
wire [31:0] prot_desc_value = prot_is_ptovrr ? OPR_R :
(uc_alu_src[5:0] == TST_DES_GRANUL) ? desc_raw_hi : protun_fwd;
wire prot_desc_g = prot_desc_value[23];
wire prot_desc_p = prot_desc_value[15];
wire [1:0] prot_desc_dpl = prot_desc_value[14:13];
wire prot_desc_s = prot_desc_value[12];
wire [3:0] prot_desc_type = prot_desc_value[11:8];
wire [1:0] prot_desc_rpl = prot_desc_value[1:0];
wire prot_desc_low16_nonzero = |prot_desc_value[15:0];
protection_unit protection_unit_inst (
.clk (clk),
.reset_n (reset_n),
.pipe_en (prot_pipe_en),
// Descriptor state: narrowed attribute bundle with forwarding for same-cycle writes
.descriptor_g (prot_desc_g),
.descriptor_p (prot_desc_p),
.descriptor_dpl (prot_desc_dpl),
.descriptor_s (prot_desc_s),
.descriptor_type (prot_desc_type),
.descriptor_rpl (prot_desc_rpl),
.descriptor_low16_nonzero(prot_desc_low16_nonzero),
.selector_rpl (slctr_fwd[1:0]), // RPL from selector (forwarded)
.selector_ti (slctr_fwd[2]), // Table indicator (forwarded)
.selector_null (selector_null_wire), // Null selector (Index=0, TI=0)
.selector_oob (selector_oob_wire), // Selector exceeds GDT/LDT limit
// Processor state
.cpl (prot_cpl), // CPL (pending after WRITE_RPL, else CS[1:0])
.pe_mode (pe), // Protected mode active
// CR0 flags for FPU tests
.cr0_et (CR0[4]), // Extension type (287 vs 387)
.cr0_ts (CR0[3]), // Task switched
.cr0_em (CR0[2]), // Emulation
.cr0_mp (CR0[1]), // Monitor coprocessor
// ARPL support
.arpl_rpl (arpl_rpl_latch), // Latched source RPL from READ_RPL
// Test control (from microcode)
// PTSAV? (aluop 0x6?, bit3=0): saves test constant for later PTOVRR, does NOT fire test
// PTOVRR (0x68): fires test using saved test constant from PTSAV
// PTSELE (0x6E) and others (bit3=1): fires test with inline test constant
.test_const (prot_test_const),
.aluop_type (uc_aluop[3:0]), // Lower 4 bits of aluop (controls Tiny PLA mux)
.test_en (prot_test_en),
// Test mode (disabled in normal operation)
.test_mode (1'b0),
.test_state_vector(10'h000),
// Outputs
.jump_addr (prot_jump_addr),
.jump_valid (prot_jump_valid),
.set_accessed (prot_set_accessed),
.validation_ok (prot_validation_ok),
.limit_check (prot_limit_check),
.stack_op (prot_stack_op),
.result_valid (prot_result_valid),
.is_checking_test (prot_is_checking_test)
);
// PROTUN register
always_ff @(posedge clk) begin
if (!reset_n) begin
PROTUN <= 32'h0;
end else if (uc_exec && (uc_dest == DEST_PROTUN)) begin
PROTUN <= protun_next;
end else if (uc_exec && arpl_m_flag_s2 && prot_validation_ok) begin
PROTUN[1:0] <= arpl_rpl_latch;
end
end
// Protection test state
always_ff @(posedge clk) begin
if (!reset_n) begin
prot_saved_test_const <= 6'h0;
desc_raw_hi <= 32'h0;
prot_test_inflight <= 1'b0;
prot_redirect_prev <= 1'b0;
end else if (uc_exec_writeback) begin
casez (uc_aluop)
7'h6?: if (pe) begin
if (prot_is_ptsav)
prot_saved_test_const <= uc_alu_src[5:0];
if (uc_aluop == ALUJMP_PTOVRR) begin
desc_raw_hi <= OPR_R;
end
end
default: ;
endcase
if (prot_test_en)
prot_test_inflight <= 1'b1;
else if (prot_result_now)
prot_test_inflight <= 1'b0;
prot_redirect_prev <= 1'b0;
if (prot_redirect_taken)
prot_redirect_prev <= 1'b1;
end
end
//=============================================================================
// Control Unit (Microcode Sequencer)
//=============================================================================
wire [5:0] uc_alu_src = uc[36:31]; // ABCDEF: ALU source / jump offset
assign uc_dest = uc[30:24]; // GHIJKLM: destination
assign uc_source = uc[23:18]; // NOPQRS: source
wire [6:0] uc_aluop = uc[17:11]; // TUVWXYZ: ALU operation / jump condition
wire [2:0] uc_opcode = uc[10:8]; // 012: opcode (RNI, RPT, etc.)
wire [1:0] uc_subcode = uc[7:6]; // 34: subcode (DLY, etc.)
assign uc_buscode = uc[5:0]; // 56789&: bus operation code
reg [11:0] microcode_return_stack [0:3]; // 4-entry return address stack
reg [1:0] microcode_sp; // Stack pointer (0-3)
reg uc_jump_taken_prev; // Jump taken last cycle (for RNi: terminate only in delay slot)
reg uc_cond_jump_taken_prev; // Conditional jump taken last cycle (for PREF suppression)
// RNI/RnI terminate unless we're in a delay slot of a taken jump (loop continues)
// RNi only terminates when in delay slot (after a jump)
assign i_rni = ((uc_is_rni || uc_is_rni_inhibit) && !uc_jump_taken_prev) ||
(uc_is_rni_lc && uc_jump_taken_prev);
reg instr_is_shift; // Instruction is a shift operation
reg instr_is_shxd; // Instruction is a SHxD operation
reg instr_cf; // CF bit at start of instruction
reg instr_is_cmp;
reg instr_ind_is_ea;
reg [4:0] alu_grp_op; // Pre-decoded ALU op for ALUJMP_ALU/INCDEC (from i_bus at i_pop)
reg instr_is_loop; // E0/E1: LOOPNE/LOOPE (eliminates 7-bit compare from jump path)
reg instr_is_mov_sreg; // 8C: MOV m,Sreg (eliminates 8-bit compare from mem size path)
reg [1:0] instr_bt_sel; // BT operation selector (eliminates 8-bit compare from ALU path)
reg [4:0] instr_szext_op; // Pre-decoded MOVZX/MOVSX/CBW ALU op
reg stack_init_pending; // Cycle after i_pop for stack op - ALU computes new SP
reg prot_test_inflight; // Protection test is in pipeline (waiting for result)
reg prot_redirect_prev; // Protection redirect fired last cycle (suppresses LJUMP + relative jumps in delay slot)
reg [31:0] OPR_W; // Bus operation data registers
reg [31:0] IND; // Internal address register
wire [31:0] ea_comb = calc_ea(ea_base_sel, ea_index_sel, ea_scale, ea_disp,
ea_has_base, ea_has_index, ea_has_disp, ea_is_16bit, ea_scale_to_base);
reg [31:0] ea_r; // Registered EA for ALU path
assign ind_effective = (i_first && instr_ind_is_ea) ? ea_comb : IND;
reg [2:0] seg_reg_sel; // Segment register index (0=ES,1=CS,2=SS,3=DS,4=FS,5=GS)
// EA Two-Stage Calculation: pre-decoded EA components (latched at i_pop)
reg [7:0] ea_base_sel; // One-hot: which base register (EAX=0,ECX=1,...,EDI=7)
reg [7:0] ea_index_sel; // One-hot: which index register (0=none)
reg [1:0] ea_scale; // Scale factor: 00=*1, 01=*2, 10=*4, 11=*8
reg [31:0] ea_disp; // Displacement value
reg ea_has_base; // Include base register
reg ea_has_index; // Include index register
reg ea_has_disp; // Include i.displacement
reg ea_is_16bit; // 16-bit addressing mode
reg ea_scale_to_base; // Special case: scale applies to base (SIB with no index)
reg [31:0] COUNTR; // Counter register
wire [4:0] CNT = COUNTR[4:0];
wire [31:0] countr_masked = i.addr32 ? COUNTR : {16'h0, COUNTR[15:0]};
reg [31:0] TMPeIP; // Saved EIP for RPTI (repeat instruction)
reg [31:0] TMPeSP; // Saved ESP for fault handling
reg flags_backup_active; // Set at i_pop/FLGSBA, cleared on interrupt_entry - guards FLAGSB writes
reg clear_if_pending; // Set by {-2E-}, used by {-2F-} to clear IF during INT
reg misc1_flag; // Set by SMISC1 {-33-}, tested by JMISC1 {-53-}
reg misc2_flag; // Set by SMISC2 {-35-}, tested by JMISC2 {-55-}
reg error_code_flag; // Set by SERRCF {-36-}, tested by JNERRC {-56-}
reg interrupt_hw; // Set for hardware interrupts, tested by JINTSW {-52-}
reg intr_pending; // Latched INTR request (level-sampled, cleared by CINTLA)
reg intr_latch_inhibit; // Suppress re-latching after CINTLA until intr deasserts
reg nmi_pending; // Latched NMI request (edge-detected, cleared on NMI entry)
reg nmi_blocked; // NMI service in progress (set by SETNMI, cleared by CLRNMI)
reg nmi_prev; // Previous NMI value for edge detection
reg interrupt_entry; // Interrupt handler being entered (suppress i_entry/i_pop)
reg jcc_active; // Currently executing a Jcc instruction (for alu_src_r in BUSOP_IND_PLUS_ALU)
reg instr_eip_written; // EIP was written during instruction (RPTI restart)
reg gate_in_progress; // Prevent second LDTST (at 5C3) from re-triggering gate detection
// Prefetch restart address (used by BUSOP_PREF / q_flush)
wire pref_writes_ip = (uc_dest == DEST_EIP || uc_dest == DEST_eIP || uc_dest == DEST_IP);
wire [31:0] pref_ip_raw = pref_writes_ip ? alu_result : ind_effective;
wire [31:0] pf_flush_ip =
(uc_dest == DEST_EIP) ? (D ? pref_ip_raw : {16'h0, pref_ip_raw[15:0]}) :
(uc_dest == DEST_eIP) ? (is_dword ? pref_ip_raw : {16'h0, pref_ip_raw[15:0]}) :
(uc_dest == DEST_IP) ? {16'h0, pref_ip_raw[15:0]} :
(op_size[1] ? ind_effective : {16'h0, ind_effective[15:0]});
assign pf_flush_addr = pe_mode_toggle_now ? (CS_base + EIP) : (CS_base + pf_flush_ip);
wire delay_slot_writes_esp = i_rni_delay && (uc_dest == DEST_eSP || uc_dest == DEST_ESP ||
(uc_dest == DEST_DSTREG && i.dst_reg_sel == 4 && op_size != 2'd0) ||
(uc_dest == DEST_SRCREG && i.src_reg_sel == 4 && op_size != 2'd0));
wire [31:0] forwarded_esp = delay_slot_writes_esp ? dest_value : ESP;
// RNI variants (opcode field):
// 000 = RNI : Run Next Instruction (normal termination)
// 001 = RNi : RNI only if in delay slot (lowercase i)
// 010 = RnI : RNI with interrupt inhibit for next instruction
wire uc_is_rni = (uc_opcode == 3'b000);
wire uc_is_rni_lc = (uc_opcode == 3'b001);
wire uc_is_rni_inhibit = (uc_opcode == 3'b010);
wire uc_is_dly = (uc_subcode == 2'b00); // DLY: stall until bus operation completes
wire uc_is_wio = (uc_subcode == 2'b10) && uc_is_rpt; // WIO: wait for interrupt/IO (HLT, only with RPT)
wire uc_is_rpt = (uc_opcode == 3'b110);
// LOOP/REP Condition Logic
wire loop_zf_sense = instr_is_loop ? i.opcode[0] : i.rep_lock[0]; // ZF sense for branch
wire countr_will_be_nonzero = instr_is_loop ? (countr_masked != 32'h1) : (countr_masked != 32'h0);
wire zf_check = instr_is_loop ? (loop_zf_sense == EFLAGS[6]) : (loop_zf_sense != EFLAGS[6]);
wire loopne_condition = instr_is_loop ? (countr_will_be_nonzero && zf_check)
: (!countr_will_be_nonzero || zf_check);
// GP Fault Detection — handled by segmentation_unit
assign gp_fault_mem_op = pg_mem_busop && (uc_buscode != BUSOP_RD_D);
assign gp_fault_wr_op = pg_is_write || pg_is_check_write;
// DIV/IDIV Overflow Detection
wire [31:0] div_upper_dividend = div_mask_to_size(SIGMA, op_size);
wire [31:0] div_divisor = div_mask_to_size(TMPB, op_size);
// IDIV2 overflow: check if quotient magnitude fits in signed range
wire [31:0] idiv_quotient = div_mask_to_size(RESULT, op_size);
wire [31:0] idiv_signed_max = (op_size == 2'd0) ? 32'h80 :
(op_size == 2'd1) ? 32'h8000 : 32'h80000000;
wire idiv_signs_differ = idiv_dividend_neg ^ idiv_divisor_neg;
wire idiv2_overflow = uc_exec && (uc_aluop == ALUJMP_IDIV2) &&
(idiv_signs_differ ? (idiv_quotient > idiv_signed_max) : (idiv_quotient >= idiv_signed_max));
assign div_overflow = (div_first_cycle && uc_exec && (
// DIV: unsigned overflow check at first DIV7
(uc_aluop == ALUJMP_DIV7 && (div_divisor == 32'h0 || div_upper_dividend >= div_divisor)) ||
// IDIV: early signed overflow check at PREDIV (uses absolute values)
(uc_aluop == ALUJMP_PREDIV && (div_divisor_abs == 32'h0 || prediv_r_in >= div_divisor_abs))
)) || idiv2_overflow;
// Relative jump condition evaluator: returns true when relative jump should be taken
function automatic logic is_reljump_taken(input [6:0] aluop);
case (aluop)
ALUJMP_JNcond: is_reljump_taken = !check_condition(i.opcode[3:0]);
ALUJMP_JCNTZ: is_reljump_taken = (countr_masked == 32'h0);
ALUJMP_JCNTNZ: is_reljump_taken = (countr_masked != 32'h0);
ALUJMP_JCT4N1: is_reljump_taken = (countr_masked[3:0] != 4'h1);
ALUJMP_JCNZNI: is_reljump_taken = (countr_masked != 32'h0);
ALUJMP_JCNTN1: is_reljump_taken = (countr_masked != 32'h1);
ALUJMP_JCNT1: is_reljump_taken = (countr_masked == 32'h1);
ALUJMP_LOOPnE: is_reljump_taken = instr_is_loop ? !loopne_condition : loopne_condition;