smmu 1.7.7

ARM SMMU v3 (System Memory Management Unit) implementation - Production-grade translation engine
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
//! TLB (Translation Lookaside Buffer) implementation
//!
//! This module provides caching of translation results to accelerate repeated
//! address translations:
//!
//! - Translation caching with configurable size
//! - Cache invalidation operations
//! - Stream-specific and global invalidation
//! - PASID-aware caching
//!
//! # Performance Impact
//!
//! The TLB cache is critical for achieving target translation latency (135ns).
//! High cache hit rates dramatically reduce the cost of page table walks.
//!
//! # Cache Coherency
//!
//! Proper cache invalidation is essential for correctness when page table
//! mappings change. This module implements all required invalidation operations
//! per ARM SMMU v3 specification.

#![warn(missing_docs)]

use crate::types::{PagePermissions, SecurityState, StreamID, IOVA, PA, PASID};
use crate::types::config::StreamWorld;
use smallvec::SmallVec;

// ============================================================================
// CacheEntry - Individual cache entry with translation result
// ============================================================================

/// Cache entry storing a single translation result
///
/// This structure represents a cached translation from IOVA to PA with
/// associated permissions and security state.
///
/// # Example
///
/// ```rust
/// use smmu::cache::CacheEntry;
/// use smmu::{IOVA, PA, PagePermissions};
///
/// let entry = CacheEntry::new(
///     IOVA::new(0x1000).unwrap(),
///     PA::new(0x2000).unwrap(),
///     PagePermissions::read_write(),
///     100,
/// );
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CacheEntry {
    /// Input/Output Virtual Address
    pub iova: IOVA,

    /// Physical Address (translation result)
    pub physical_address: PA,

    /// Page permissions for this translation
    pub permissions: PagePermissions,

    /// Security state (Secure/NonSecure/Realm)
    pub security_state: SecurityState,

    /// Timestamp for LRU tracking
    pub timestamp: u64,

    /// ASID (Address Space Identifier) from CD.ASID — used for ASID-targeted invalidation.
    /// Defaults to 0 for Stage-2-only or bypass entries.
    pub asid: u16,

    /// VMID (Virtual Machine ID) from STE.S2VMID (ARM §5.2) — used for
    /// VMID-targeted invalidation via `CMD_TLBI_S12_VMALL` / `CMD_TLBI_S2_IPA`.
    /// Defaults to 0.
    pub vmid: u16,

    /// CONF-GAP-7: Intermediate Physical Address for two-stage TLB entries (§4.4).
    ///
    /// For entries populated during two-stage (S1+S2) translation, this field
    /// holds the Stage-1 output IPA that was subsequently translated by Stage-2.
    /// For single-stage entries this field is `0`.
    ///
    /// Used by `CMD_TLBI_S2_IPA` to perform IPA-selective invalidation rather
    /// than over-invalidating all VMID-tagged entries.
    pub ipa: u64,

    /// BUG-QA-14: Stream World tag for `CMD_TLBI_NSNH_ALL` scoped invalidation (§4.4.4.1).
    ///
    /// Tagged from `STE.STRW` when the entry is inserted.  `CMD_TLBI_NSNH_ALL`
    /// evicts only entries tagged `El1El0` (Non-Secure Non-Hyp), preserving
    /// `El2` and `El2E2h` entries per ARM §4.4.4.1.
    pub strw: StreamWorld,
}

impl CacheEntry {
    /// Create a new cache entry with default security state and ASID=0
    ///
    /// Security state defaults to NonSecure.
    #[inline]
    pub const fn new(iova: IOVA, physical_address: PA, permissions: PagePermissions, timestamp: u64) -> Self {
        Self {
            iova,
            physical_address,
            permissions,
            security_state: SecurityState::NonSecure,
            timestamp,
            asid: 0,
            vmid: 0,
            ipa: 0,
            strw: StreamWorld::El1El0,
        }
    }

    /// Create a new cache entry with explicit security state, ASID=0, VMID=0
    #[inline]
    pub const fn new_with_security(
        iova: IOVA,
        physical_address: PA,
        permissions: PagePermissions,
        security_state: SecurityState,
        timestamp: u64,
    ) -> Self {
        Self {
            iova,
            physical_address,
            permissions,
            security_state,
            timestamp,
            asid: 0,
            vmid: 0,
            ipa: 0,
            strw: StreamWorld::El1El0,
        }
    }

    /// Create a new cache entry with explicit security state and ASID (VMID=0).
    ///
    /// Used for Stage-1 TLB entries tagged with CD.ASID per ARM §3.17.
    #[inline]
    pub const fn new_with_asid(
        iova: IOVA,
        physical_address: PA,
        permissions: PagePermissions,
        security_state: SecurityState,
        asid: u16,
        timestamp: u64,
    ) -> Self {
        Self {
            iova,
            physical_address,
            permissions,
            security_state,
            timestamp,
            asid,
            vmid: 0,
            ipa: 0,
            strw: StreamWorld::El1El0,
        }
    }

    /// Create a new cache entry tagged with both ASID (CD.ASID, ARM §3.17) and
    /// VMID (STE.S2VMID, ARM §5.2).
    ///
    /// This is the primary constructor used by `translate()` so that both
    /// ASID-targeted (`CMD_TLBI_NH_ASID`) and VMID-targeted
    /// (`CMD_TLBI_S12_VMALL`) invalidation work correctly.
    #[inline]
    pub const fn new_with_tags(
        iova: IOVA,
        physical_address: PA,
        permissions: PagePermissions,
        security_state: SecurityState,
        asid: u16,
        vmid: u16,
        timestamp: u64,
    ) -> Self {
        Self {
            iova,
            physical_address,
            permissions,
            security_state,
            timestamp,
            asid,
            vmid,
            ipa: 0,
            strw: StreamWorld::El1El0,
        }
    }
}

impl Default for CacheEntry {
    fn default() -> Self {
        Self {
            iova: IOVA::const_new(0),
            physical_address: PA::const_new(0),
            permissions: PagePermissions::none(),
            security_state: SecurityState::NonSecure,
            timestamp: 0,
            asid: 0,
            vmid: 0,
            ipa: 0,
            strw: StreamWorld::El1El0,
        }
    }
}

// ============================================================================
// CacheKey - Multi-level cache indexing key
// ============================================================================

/// Cache key for multi-level indexing by StreamID, PASID, IOVA, and SecurityState
///
/// This structure is used as the key in the TLB cache HashMap to uniquely
/// identify a translation entry.
///
/// # Hash Quality
///
/// The hash implementation uses FNV-1a algorithm optimized for page-aligned
/// addresses by skipping the lower 12 bits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CacheKey {
    /// Stream identifier
    pub stream_id: StreamID,

    /// Process Address Space ID
    pub pasid: PASID,

    /// Input/Output Virtual Address
    pub iova: IOVA,

    /// Security state
    pub security_state: SecurityState,
}

impl CacheKey {
    /// Create a new cache key
    #[inline]
    pub const fn new(stream_id: StreamID, pasid: PASID, iova: IOVA, security_state: SecurityState) -> Self {
        Self { stream_id, pasid, iova, security_state }
    }
}

// ============================================================================
// CacheKeyHash - FNV-1a hash implementation
// ============================================================================

/// Custom hash implementation for `CacheKey` using FNV-1a algorithm
///
/// This hasher is optimized for ARM SMMU v3 usage patterns:
/// - Skips lower 12 bits of IOVA (page-aligned addresses)
/// - Provides better distribution than default hash
/// - Uses FNV-1a constants for 64-bit hash values
///
/// # FNV-1a Algorithm
///
/// FNV-1a (Fowler-Noll-Vo) is a non-cryptographic hash function with
/// good distribution properties for hash tables.
#[derive(Debug)]
pub struct CacheKeyHash;

impl CacheKeyHash {
    /// Hash a `CacheKey` using optimized algorithm
    ///
    /// # Optimization
    ///
    /// Uses a fast mixing function optimized for hardware:
    /// - Minimal operations for sub-10ns latency
    /// - Good distribution for hash tables
    /// - The lower 12 bits of IOVA are skipped (4KB pages)
    /// - Uses efficient bit rotation and XOR mixing
    ///
    /// # ARM SMMU v3 Spec Compliance
    ///
    /// ARM IHI0070G.b §6.3.2 (SIDSIZE) defines StreamID as up to 32 bits wide.
    /// This implementation uses XOR-multiply combination to incorporate all 32
    /// bits of StreamID without loss — avoiding the overflow hazard of the
    /// previous `u64::from(sid) << 48` approach, which silently discarded bits
    /// 16-31 for any StreamID value >= 65536.
    ///
    /// BUG-RUST-2 fix: the previous formula placed the StreamID in bits 48-63
    /// of a u64 (`<< 48`).  For a 32-bit StreamID value with bits 16-31 set,
    /// the shift would overflow u64 and produce 0 — identical to StreamID 0.
    /// The fix uses a 64-bit multiply-add to mix all 32 bits without overflow.
    #[inline(always)]
    pub fn hash(key: &CacheKey) -> u64 {
        // BUG-RUST-2 fix: use XOR-multiply combination to incorporate all 32
        // bits of StreamID without bit-shift overflow.
        //
        // Previous (buggy) approach:
        //   let stream = u64::from(key.stream_id.as_u32()) << 48;
        // For StreamID >= 0x10000, bits 16-31 overflowed the 64-bit boundary
        // and were discarded, causing a hash collision with StreamID 0.
        //
        // Fixed approach: fold the 32-bit StreamID into the full 64-bit hash
        // via Knuth's multiplicative hash constant (a prime approximation of
        // phi^-1 * 2^64), providing excellent avalanche for all 32 bits.
        let stream_u64 = u64::from(key.stream_id.as_u32());
        let stream = stream_u64.wrapping_mul(0x9e37_79b9_7f4a_7c15_u64);

        // PASID (20 bits) — fold into hash using a different constant
        let pasid_u64 = u64::from(key.pasid.as_u32());
        let pasid = pasid_u64.wrapping_mul(0x6c62_272e_07bb_0142_u64);

        // Security state (2 bits)
        let security = u64::from(key.security_state as u8) & 0x3;

        // Page number (IOVA >> 12) — lower 12 bits are page offset (unused)
        let page = (key.iova.as_u64() >> 12).wrapping_mul(0x517c_c1b7_2722_0a95_u64);

        // Combine all fields with a non-zero seed (FNV-1a offset basis) so
        // all-zero inputs (e.g. stream=0, PASID=0, IOVA=0, NonSecure=0b00)
        // never produce a zero hash value.
        let mut hash = stream
            .wrapping_add(pasid)
            .wrapping_add(security)
            .wrapping_add(page)
            ^ 0xcbf2_9ce4_8422_2325_u64;

        // Fast mixing using bit rotation and XOR (murmur-like finalizer)
        // This provides good distribution with minimal operations
        hash ^= hash >> 33;
        hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
        hash ^= hash >> 33;
        hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
        hash ^= hash >> 33;

        hash
    }
}

// ============================================================================
// StreamPASIDKey - Secondary index key
// ============================================================================

/// Key for secondary indexing by StreamID and PASID
///
/// Used for efficient invalidation operations that target all entries
/// for a specific stream or PASID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StreamPASIDKey {
    /// Stream identifier
    pub stream_id: StreamID,

    /// Process Address Space ID
    pub pasid: PASID,
}

impl StreamPASIDKey {
    /// Create a new StreamPASID key
    #[inline]
    pub const fn new(stream_id: StreamID, pasid: PASID) -> Self {
        Self { stream_id, pasid }
    }
}

// ============================================================================
// StreamPASIDKeyHash - FNV-1a hash for StreamPASIDKey
// ============================================================================

/// Custom hash implementation for StreamPASIDKey using FNV-1a algorithm
#[derive(Debug)]
pub struct StreamPASIDKeyHash;

impl StreamPASIDKeyHash {
    /// Hash a StreamPASIDKey using optimized algorithm
    #[inline(always)]
    pub fn hash(key: &StreamPASIDKey) -> u64 {
        // Simple combination - StreamID and PASID are small values
        let combined = (u64::from(key.stream_id.as_u32()) << 32) | u64::from(key.pasid.as_u32());

        // Fast mixing with offset to ensure non-zero for zero input
        let mut hash = combined.wrapping_add(0xdead_beef);
        hash ^= hash >> 33;
        hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
        hash ^= hash >> 33;

        hash
    }
}

// ============================================================================
// FxHasher - Fast hash builder for DashMap
// ============================================================================

use std::hash::{BuildHasher, Hasher};

/// Fast hash builder using FNV-1a-style hashing
///
/// This hasher is optimized for performance over cryptographic security.
/// It provides 15-25ns improvement over default SipHash for DashMap lookups.
#[derive(Debug, Clone, Default)]
pub struct FxBuildHasher;

/// Fast hasher implementation using FNV-1a algorithm
///
/// Optimized for ARM SMMU cache keys with minimal operations.
#[derive(Debug, Default)]
pub struct FxHasher {
    hash: u64,
}

impl Hasher for FxHasher {
    #[inline]
    fn finish(&self) -> u64 {
        self.hash
    }

    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        // Process complete 8-byte chunks as native-endian u64 words via write_u64(),
        // ensuring write(&x.to_ne_bytes()) == write_u64(x) for any aligned input.
        let mut chunks = bytes.chunks_exact(8);
        for chunk in chunks.by_ref() {
            // SAFETY: chunks_exact(8) guarantees exactly 8 bytes.
            let word = u64::from_ne_bytes(chunk.try_into().expect("chunk is exactly 8 bytes"));
            self.write_u64(word);
        }
        // Handle trailing bytes (0–7) by zero-padding into a u64 in native-endian
        // byte order, then folding through write_u64() so the same mixing applies.
        let tail = chunks.remainder();
        if !tail.is_empty() {
            let mut word_bytes = [0u8; 8];
            word_bytes[..tail.len()].copy_from_slice(tail);
            let word = u64::from_ne_bytes(word_bytes);
            self.write_u64(word);
        }
    }

    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.hash ^= i;
        self.hash = self.hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
        self.hash ^= self.hash >> 33;
    }

    #[inline]
    fn write_u32(&mut self, i: u32) {
        self.write_u64(u64::from(i));
    }
}

impl BuildHasher for FxBuildHasher {
    type Hasher = FxHasher;

    #[inline]
    fn build_hasher(&self) -> FxHasher {
        FxHasher { hash: 0 }
    }
}

// ============================================================================
// TLB Cache Implementation
// ============================================================================

use dashmap::DashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// Replacement policy for cache eviction
///
/// Determines which entry to evict when the cache is full and a new
/// entry needs to be inserted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplacementPolicy {
    /// Least Recently Used - evicts the entry that was least recently accessed
    Lru,
    /// First In First Out - evicts the oldest entry regardless of access pattern
    Fifo,
}

impl Default for ReplacementPolicy {
    fn default() -> Self {
        Self::Lru
    }
}

/// Cache statistics tracking performance metrics
///
/// All counters use atomic operations for lock-free updates across threads.
/// Statistics can be read at any time without blocking cache operations.
///
/// # Performance Metrics
///
/// - **Hit Rate**: `hits / (hits + misses)` - percentage of successful lookups
/// - **Miss Rate**: `misses / (hits + misses)` - percentage of failed lookups
/// - **Efficiency**: Overall cache effectiveness at reducing translation costs
#[derive(Debug)]
pub struct CacheStatistics {
    /// Total cache lookup attempts (hits + misses)
    pub lookups: AtomicU64,

    /// Successful cache lookups
    pub hits: AtomicU64,

    /// Failed cache lookups
    pub misses: AtomicU64,

    /// Number of entries evicted due to capacity
    pub evictions: AtomicU64,

    /// Number of entries inserted into cache
    pub insertions: AtomicU64,

    /// Number of entries invalidated (removed explicitly)
    pub invalidations: AtomicU64,
}

impl CacheStatistics {
    /// Create a new statistics tracker with all counters at zero
    #[inline]
    pub const fn new() -> Self {
        Self {
            lookups: AtomicU64::new(0),
            hits: AtomicU64::new(0),
            misses: AtomicU64::new(0),
            evictions: AtomicU64::new(0),
            insertions: AtomicU64::new(0),
            invalidations: AtomicU64::new(0),
        }
    }

    /// Reset all statistics counters to zero
    #[inline]
    pub fn reset(&self) {
        self.lookups.store(0, Ordering::Relaxed);
        self.hits.store(0, Ordering::Relaxed);
        self.misses.store(0, Ordering::Relaxed);
        self.evictions.store(0, Ordering::Relaxed);
        self.insertions.store(0, Ordering::Relaxed);
        self.invalidations.store(0, Ordering::Relaxed);
    }

    /// Get current lookup count
    #[inline]
    pub fn get_lookups(&self) -> u64 {
        self.lookups.load(Ordering::Relaxed)
    }

    /// Get current hit count
    #[inline]
    pub fn get_hits(&self) -> u64 {
        self.hits.load(Ordering::Relaxed)
    }

    /// Get current miss count
    #[inline]
    pub fn get_misses(&self) -> u64 {
        self.misses.load(Ordering::Relaxed)
    }

    /// Get current eviction count
    #[inline]
    pub fn get_evictions(&self) -> u64 {
        self.evictions.load(Ordering::Relaxed)
    }

    /// Get current insertion count
    #[inline]
    pub fn get_insertions(&self) -> u64 {
        self.insertions.load(Ordering::Relaxed)
    }

    /// Get current invalidation count
    #[inline]
    pub fn get_invalidations(&self) -> u64 {
        self.invalidations.load(Ordering::Relaxed)
    }

    /// Calculate cache hit rate as percentage (0.0 to 100.0)
    ///
    /// Returns 0.0 if no lookups have been performed.
    #[inline]
    pub fn hit_rate(&self) -> f64 {
        let hits = self.get_hits();
        let lookups = self.get_lookups();

        if lookups == 0 {
            0.0
        } else {
            (hits as f64 / lookups as f64) * 100.0
        }
    }

    /// Calculate cache miss rate as percentage (0.0 to 100.0)
    ///
    /// Returns 0.0 if no lookups have been performed.
    #[inline]
    pub fn miss_rate(&self) -> f64 {
        let misses = self.get_misses();
        let lookups = self.get_lookups();

        if lookups == 0 {
            0.0
        } else {
            (misses as f64 / lookups as f64) * 100.0
        }
    }
}

impl Default for CacheStatistics {
    fn default() -> Self {
        Self::new()
    }
}

/// TLB (Translation Lookaside Buffer) cache implementation
///
/// Provides high-performance caching of address translations with:
/// - Lock-free concurrent access using DashMap
/// - Configurable replacement policies (LRU/FIFO)
/// - Comprehensive invalidation strategies
/// - Atomic statistics tracking
/// - Multi-level indexing for efficient lookups
///
/// # Thread Safety
///
/// The TLB cache is fully thread-safe and can be shared across threads.
/// All operations (lookup, insert, invalidate) are safe to call concurrently.
///
/// # Performance
///
/// - Lookup: Average O(1) with hash table
/// - Insert: Average O(1) with eviction overhead
/// - Invalidation: O(n) where n is number of entries matching criteria
///
/// # Example
///
/// ```rust
/// use smmu::cache::{TlbCache, CacheKey, CacheEntry, ReplacementPolicy};
/// use smmu::{IOVA, PA, PagePermissions, SecurityState, StreamID, PASID};
///
/// let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
///
/// let stream_id = StreamID::new(1).unwrap();
/// let pasid     = PASID::new(0).unwrap();
/// let iova      = IOVA::new(0x1000).unwrap();
/// let pa        = PA::new(0x2000).unwrap();
/// let key   = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
/// let entry = CacheEntry::new(iova, pa, PagePermissions::read_write(), 0);
///
/// // Insert translation
/// cache.insert(key, entry);
///
/// // Lookup translation
/// if let Some(hit) = cache.lookup(&key) {
///     let _ = hit.physical_address.as_u64(); // cache hit - use cached translation
/// }
///
/// // Invalidate by stream
/// cache.invalidate_by_stream(stream_id);
/// ```
pub struct TlbCache {
    /// Main cache storage using lock-free concurrent hash map with custom FxHasher
    entries: Arc<DashMap<CacheKey, CacheEntry, FxBuildHasher>>,

    /// Maximum number of entries in cache
    capacity: usize,

    /// Replacement policy for eviction
    policy: ReplacementPolicy,

    /// Global timestamp counter for LRU tracking
    timestamp: AtomicU64,

    /// Cache performance statistics
    statistics: Arc<CacheStatistics>,
}

impl TlbCache {
    /// Create a new TLB cache with specified capacity and replacement policy
    ///
    /// # Arguments
    ///
    /// * `capacity` - Maximum number of cached entries (must be > 0)
    /// * `policy` - Replacement policy for eviction (LRU or FIFO)
    ///
    /// # Panics
    ///
    /// Panics if capacity is 0.
    ///
    /// # Example
    ///
    /// ```rust
    /// use smmu::cache::{TlbCache, ReplacementPolicy};
    /// let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// ```
    pub fn new(capacity: usize, policy: ReplacementPolicy) -> Self {
        assert!(capacity > 0, "TlbCache capacity must be greater than 0");

        Self {
            entries: Arc::new(DashMap::with_capacity_and_hasher(capacity, FxBuildHasher)),
            capacity,
            policy,
            timestamp: AtomicU64::new(0),
            statistics: Arc::new(CacheStatistics::new()),
        }
    }

    /// Lookup a translation in the cache
    ///
    /// Returns a copy of the cache entry if found, or None on cache miss.
    /// Updates statistics and LRU timestamp on hit.
    ///
    /// # Performance
    ///
    /// Optimized for sub-50ns average O(1) hash table lookup with lock-free read access.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, CacheKey, CacheEntry, ReplacementPolicy};
    /// # use smmu::{IOVA, PA, PagePermissions, SecurityState, StreamID, PASID};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// # let key = CacheKey::new(StreamID::new(1).unwrap(), PASID::new(0).unwrap(),
    /// #     IOVA::new(0x1000).unwrap(), SecurityState::NonSecure);
    /// # let entry = CacheEntry::new(IOVA::new(0x1000).unwrap(),
    /// #     PA::new(0x2000).unwrap(), PagePermissions::read_write(), 0);
    /// # cache.insert(key, entry);
    /// if let Some(hit) = cache.lookup(&key) {
    ///     println!("PA: 0x{:x}", hit.physical_address.as_u64());
    /// }
    /// ```
    #[inline(always)]
    pub fn lookup(&self, key: &CacheKey) -> Option<CacheEntry> {
        self.statistics.lookups.fetch_add(1, Ordering::Relaxed);

        if self.policy == ReplacementPolicy::Lru {
            // LRU: refresh timestamp on hit so evict_one() always removes the
            // least recently *used* entry, not the least recently inserted one.
            if let Some(mut entry_ref) = self.entries.get_mut(key) {
                self.statistics.hits.fetch_add(1, Ordering::Relaxed);
                let ts = self.timestamp.fetch_add(1, Ordering::Relaxed);
                entry_ref.timestamp = ts;
                return Some(*entry_ref);
            }
            self.statistics.misses.fetch_add(1, Ordering::Relaxed);
            None
        } else {
            // FIFO: insertion order only, no timestamp update on lookup.
            if let Some(entry_ref) = self.entries.get(key) {
                self.statistics.hits.fetch_add(1, Ordering::Relaxed);
                return Some(*entry_ref);
            }
            self.statistics.misses.fetch_add(1, Ordering::Relaxed);
            None
        }
    }

    /// Insert a translation into the cache
    ///
    /// If the cache is at capacity, evicts an entry according to the
    /// replacement policy before inserting the new entry.
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key identifying the translation
    /// * `entry` - Translation result to cache
    ///
    /// # Performance
    ///
    /// Optimized for O(1) insertion with minimal overhead.
    /// Uses lock-free operations where possible.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, CacheKey, CacheEntry, ReplacementPolicy};
    /// # use smmu::{IOVA, PA, PagePermissions, SecurityState, StreamID, PASID};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// # let key = CacheKey::new(StreamID::new(1).unwrap(), PASID::new(0).unwrap(),
    /// #     IOVA::new(0x1000).unwrap(), SecurityState::NonSecure);
    /// # let entry = CacheEntry::new(IOVA::new(0x1000).unwrap(),
    /// #     PA::new(0x2000).unwrap(), PagePermissions::read_write(), 0);
    /// cache.insert(key, entry);
    /// ```
    #[inline]
    pub fn insert(&self, key: CacheKey, mut entry: CacheEntry) {
        // Update timestamp for LRU tracking
        let timestamp = self.timestamp.fetch_add(1, Ordering::Relaxed);
        entry.timestamp = timestamp;

        // Insert the new entry first, then enforce capacity by evicting until
        // the map is within bounds.  This post-insert eviction loop handles the
        // TOCTOU race: multiple concurrent threads may each pass a pre-insert
        // capacity check and all insert simultaneously, causing the map to grow
        // beyond capacity.  By checking *after* insertion and evicting in a loop,
        // each thread participates in trimming the map back to capacity, so the
        // final size remains bounded regardless of concurrency.
        self.entries.insert(key, entry);
        while self.entries.len() > self.capacity {
            self.evict_one();
        }
        self.statistics.insertions.fetch_add(1, Ordering::Relaxed);
    }

    /// Fast eviction - evicts first entry found (approximate LRU/FIFO)
    ///
    /// This is optimized for speed over perfect eviction policy.
    /// Trades perfect LRU for sub-100ns insertion performance.
    #[allow(dead_code)]
    #[inline(always)]
    fn evict_one_fast(&self) {
        // Try a completely different approach - just remove any arbitrary key
        // DashMap doesn't have a good way to get "first" entry efficiently
        // So we'll just iterate and remove the first one we find

        for entry_ref in self.entries.iter().take(1) {
            let key_to_remove = *entry_ref.key();
            drop(entry_ref);
            if self.entries.remove(&key_to_remove).is_some() {
                self.statistics.evictions.fetch_add(1, Ordering::Relaxed);
                break;
            }
        }
    }

    /// Evict one entry according to replacement policy (precise version)
    ///
    /// For LRU: Finds and evicts entry with oldest timestamp
    /// For FIFO: Evicts first entry (approximate)
    fn evict_one(&self) {
        let key_to_evict = match self.policy {
            ReplacementPolicy::Lru => {
                // Find entry with minimum timestamp
                self.entries
                    .iter()
                    .min_by_key(|entry| entry.value().timestamp)
                    .map(|entry| *entry.key())
            },
            ReplacementPolicy::Fifo => {
                // Just take first entry for FIFO
                self.entries.iter().next().map(|entry| *entry.key())
            },
        };

        if let Some(key) = key_to_evict {
            self.remove_entry(&key);
            self.statistics.evictions.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Remove a single entry
    #[inline]
    fn remove_entry(&self, key: &CacheKey) {
        self.entries.remove(key);
    }

    /// Invalidate all entries in the cache (global flush)
    ///
    /// Clears all cached translations. This is typically called when
    /// page table configuration changes globally.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// cache.invalidate_all();
    /// ```
    pub fn invalidate_all(&self) {
        let count = self.entries.len();
        self.entries.clear();

        self.statistics.invalidations.fetch_add(count as u64, Ordering::Relaxed);
    }

    /// BUG-QA-14 fix / BUG-NEW-18 fix: ARM §4.4.4.1 `CMD_TLBI_NSNH_ALL` —
    /// invalidate Non-Secure Non-Hyp entries.
    ///
    /// Evicts only entries tagged **both** `StreamWorld::El1El0` **and**
    /// `SecurityState::NonSecure`.  Secure EL1/EL0 entries and all EL2/EL2-E2H
    /// entries are preserved per ARM §4.4.4.1.
    ///
    /// BUG-NEW-18: the previous implementation only checked `strw==El1El0`,
    /// causing Secure El1El0 entries to be incorrectly evicted.
    pub fn invalidate_nsnh_all(&self) {
        let mut count = 0usize;
        self.entries.retain(|_key, entry| {
            if entry.strw == StreamWorld::El1El0
                && entry.security_state == SecurityState::NonSecure
            {
                count += 1;
                false // remove — NonSecure EL1/EL0 only
            } else {
                true // keep — Secure El1El0 and all EL2 entries preserved
            }
        });
        self.statistics.invalidations.fetch_add(count as u64, Ordering::Relaxed);
    }

    /// BUG-NEW-18 fix: ARM §4.4.2.7 `CMD_TLBI_EL2_ALL` — invalidate EL2 entries only.
    ///
    /// Evicts entries tagged with `StreamWorld::El2` or `StreamWorld::El2E2h`.
    /// Entries tagged `El1El0` or `El3` are preserved, because CMD_TLBI_EL2_ALL
    /// is scoped to the EL2 world and must not affect EL1/EL0 translations.
    ///
    /// # ARM Specification
    ///
    /// ARM IHI0070G.b §4.4.2.7: CMD_TLBI_EL2_ALL invalidates all TLB entries
    /// for EL2 translations (NS-EL2 and NS-EL2-E2H).  It does not affect
    /// NS-EL1/EL0 (`El1El0`) entries.
    pub fn invalidate_el2_all(&self) {
        let mut count = 0usize;
        self.entries.retain(|_key, entry| {
            if entry.strw == StreamWorld::El2 || entry.strw == StreamWorld::El2E2h {
                count += 1;
                false // remove
            } else {
                true // keep
            }
        });
        self.statistics.invalidations.fetch_add(count as u64, Ordering::Relaxed);
    }

    /// ARM §4.4.2.1 `CMD_TLBI_NH_ALL` — invalidate EL1_EL0 entries scoped to a VMID.
    ///
    /// Evicts only entries tagged with `StreamWorld::El1El0` **and** the given `vmid`.
    /// Entries for a different VMID, or with a non-EL1_EL0 `strw`, are preserved.
    ///
    /// This is the correct behaviour per ARM §4.4.2.1: NH_ALL is a VMID-scoped
    /// command that invalidates non-hyp (EL1_EL0) translations for that VMID only.
    pub fn invalidate_nh_by_vmid(&self, vmid: u16) {
        let mut count = 0usize;
        self.entries.retain(|_key, entry| {
            if entry.strw == StreamWorld::El1El0 && entry.vmid == vmid {
                count += 1;
                false // remove
            } else {
                true // keep
            }
        });
        self.statistics.invalidations.fetch_add(count as u64, Ordering::Relaxed);
    }

    /// §3.17.6 — Invalidate NS-EL1El0 TLB entries matching VMID with VMW wildcard mask.
    ///
    /// Used by broadcast `CMD_TLBI_NH_ALL` when `CR0.VMW != 0`.  Only entries tagged
    /// `El1El0` are affected; `El2` / `El2E2h` entries are preserved.
    ///
    /// The comparison is: `(entry.vmid & vmid_mask) == (target_vmid & vmid_mask)`.
    pub fn invalidate_nh_by_vmid_with_mask(&self, target_vmid: u16, vmid_mask: u16) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            if e.strw == StreamWorld::El1El0
                && (e.vmid & vmid_mask) == (target_vmid & vmid_mask)
            {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// ARM §4.4.2.10 `CMD_TLBI_EL2_ASID` — invalidate NS-EL2-E2H entries by ASID.
    ///
    /// Evicts only entries tagged with `StreamWorld::El2E2h` **and** the given ASID.
    /// `El1El0` and `El2` entries with the same ASID are preserved.
    ///
    /// Per ARM §4.4.2.10 the command operates only on NS-EL2-E2H translations.
    pub fn invalidate_el2_e2h_by_asid(&self, target_asid: u16) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry in self.entries.iter() {
            let e = entry.value();
            if e.strw == StreamWorld::El2E2h && e.asid == target_asid {
                keys_to_remove.push(*entry.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// ARM §4.4.2.8 `CMD_TLBI_EL2_VA` — invalidate NS-EL2/EL2-E2H entries by VA+ASID.
    ///
    /// Evicts entries where `strw` is `El2` or `El2E2h`, `asid` matches, and
    /// `iova` matches the page-aligned `va`.  `El1El0` entries are preserved.
    ///
    /// # Arguments
    ///
    /// * `va`         - Virtual address (raw u64; lower 12 bits are masked)
    /// * `target_asid`- ASID to match
    pub fn invalidate_el2_by_va_and_asid(&self, va: u64, target_asid: u16) {
        const PAGE_MASK: u64 = 0xFFFF_FFFF_FFFF_F000;
        let page_va = va & PAGE_MASK;

        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            if (e.strw == StreamWorld::El2 || e.strw == StreamWorld::El2E2h)
                && e.asid == target_asid
                && (e.iova.as_u64() & PAGE_MASK) == page_va
            {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// ARM §4.4.2.8 `CMD_TLBI_EL2_VA` (RIL range) — invalidate NS-EL2/EL2-E2H
    /// entries by VA range and ASID.
    ///
    /// Evicts entries where `strw` is `El2` or `El2E2h`, `asid` matches, and
    /// `start <= iova <= end`.  `El1El0` entries are preserved.
    ///
    /// # Arguments
    ///
    /// * `start`      - Inclusive start of the VA range (raw u64)
    /// * `end`        - Inclusive end of the VA range (raw u64)
    /// * `target_asid`- ASID to match
    pub fn invalidate_el2_by_va_range_and_asid(&self, start: u64, end: u64, target_asid: u16) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            let iova = e.iova.as_u64();
            if (e.strw == StreamWorld::El2 || e.strw == StreamWorld::El2E2h)
                && e.asid == target_asid
                && iova >= start
                && iova <= end
            {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// ARM §4.4.2.9 `CMD_TLBI_EL2_VAA` — invalidate NS-EL2/EL2-E2H entries by VA (any ASID).
    ///
    /// Evicts entries where `strw` is `El2` or `El2E2h` and `iova` matches the
    /// page-aligned `va`, regardless of ASID.  `El1El0` entries are preserved.
    ///
    /// # Arguments
    ///
    /// * `va` - Virtual address (raw u64; lower 12 bits are masked)
    pub fn invalidate_el2_by_va(&self, va: u64) {
        const PAGE_MASK: u64 = 0xFFFF_FFFF_FFFF_F000;
        let page_va = va & PAGE_MASK;

        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            if (e.strw == StreamWorld::El2 || e.strw == StreamWorld::El2E2h)
                && (e.iova.as_u64() & PAGE_MASK) == page_va
            {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all entries for a specific StreamID
    ///
    /// Removes all cached translations for the given stream across all PASIDs.
    ///
    /// # Arguments
    ///
    /// * `stream_id` - Stream identifier to invalidate
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # use smmu::StreamID;
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// let stream_id = StreamID::new(1).unwrap();
    /// cache.invalidate_by_stream(stream_id);
    /// ```
    pub fn invalidate_by_stream(&self, stream_id: StreamID) {
        let mut removed_count = 0;

        // Use SmallVec to avoid heap allocation for common case
        // Most invalidations affect a small number of entries
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        // Collect keys to remove (to avoid holding iterator during removal)
        for entry in self.entries.iter() {
            if entry.key().stream_id == stream_id {
                keys_to_remove.push(*entry.key());
            }
        }

        // Remove entries
        for key in keys_to_remove {
            self.remove_entry(&key);
            removed_count += 1;
        }

        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all entries for a specific PASID
    ///
    /// Removes all cached translations for the given PASID across all streams.
    ///
    /// # Arguments
    ///
    /// * `pasid` - Process Address Space ID to invalidate
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # use smmu::PASID;
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// let pasid = PASID::new(42).unwrap();
    /// cache.invalidate_by_pasid(pasid);
    /// ```
    pub fn invalidate_by_pasid(&self, pasid: PASID) {
        let mut removed_count = 0;

        // Use SmallVec to avoid heap allocation for common case
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        // Collect keys to remove
        for entry in self.entries.iter() {
            if entry.key().pasid == pasid {
                keys_to_remove.push(*entry.key());
            }
        }

        // Remove entries
        for key in keys_to_remove {
            self.remove_entry(&key);
            removed_count += 1;
        }

        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all entries for a specific StreamID and PASID combination
    ///
    /// Removes all cached translations for the given stream/PASID pair.
    /// This is the most common invalidation operation.
    ///
    /// # Arguments
    ///
    /// * `stream_id` - Stream identifier
    /// * `pasid` - Process Address Space ID
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # use smmu::{StreamID, PASID};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// let stream_id = StreamID::new(1).unwrap();
    /// let pasid = PASID::new(42).unwrap();
    /// cache.invalidate_by_stream_pasid(stream_id, pasid);
    /// ```
    pub fn invalidate_by_stream_pasid(&self, stream_id: StreamID, pasid: PASID) {
        let mut removed_count = 0;

        // Use SmallVec to collect keys to remove
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        // Collect keys matching stream_id and pasid
        for entry in self.entries.iter() {
            let key = entry.key();
            if key.stream_id == stream_id && key.pasid == pasid {
                keys_to_remove.push(*key);
            }
        }

        // Remove entries
        for key in keys_to_remove {
            self.remove_entry(&key);
            removed_count += 1;
        }

        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate entries within a virtual address range
    ///
    /// Removes cached translations for IOVAs within the specified range
    /// for a given stream/PASID combination.
    ///
    /// # Arguments
    ///
    /// * `stream_id` - Stream identifier
    /// * `pasid` - Process Address Space ID
    /// * `start` - Start of IOVA range (inclusive)
    /// * `end` - End of IOVA range (inclusive)
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # use smmu::{IOVA, StreamID, PASID};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// let stream_id = StreamID::new(1).unwrap();
    /// let pasid = PASID::new(0).unwrap();
    /// let start = IOVA::new(0x1000).unwrap();
    /// let end   = IOVA::new(0x5000).unwrap();
    /// cache.invalidate_by_va_range(stream_id, pasid, start, end);
    /// ```
    pub fn invalidate_by_va_range(&self, stream_id: StreamID, pasid: PASID, start: IOVA, end: IOVA) {
        let mut removed_count = 0;

        // Use SmallVec to avoid heap allocation for common case
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        // Collect keys to remove within range
        for entry in self.entries.iter() {
            let key = entry.key();
            if key.stream_id == stream_id
                && key.pasid == pasid
                && key.iova.as_u64() >= start.as_u64()
                && key.iova.as_u64() <= end.as_u64()
            {
                keys_to_remove.push(*key);
            }
        }

        // Remove entries
        for key in keys_to_remove {
            self.remove_entry(&key);
            removed_count += 1;
        }

        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all Stage-1 TLB entries tagged with the given ASID.
    ///
    /// Implements `CMD_TLBI_NH_ASID` / `CMD_TLBI_EL2_ASID` per ARM SMMU v3 §4.4.
    /// Only entries whose `CacheEntry::asid` matches `target_asid` are evicted;
    /// all other entries remain cached.
    ///
    /// # Arguments
    ///
    /// * `target_asid` - The 16-bit ASID to invalidate (CD.ASID, §3.17)
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// cache.invalidate_by_asid(42);
    /// ```
    pub fn invalidate_by_asid(&self, target_asid: u16) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        // Scan all entries; evict those tagged with the target ASID.
        for entry in self.entries.iter() {
            if entry.value().asid == target_asid {
                keys_to_remove.push(*entry.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }

        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all TLB entries tagged with the given VMID.
    ///
    /// Implements `CMD_TLBI_S12_VMALL` / `CMD_TLBI_S2_IPA` per ARM SMMU v3 §4.4.
    /// Only entries whose `CacheEntry::vmid` matches `target_vmid` are evicted;
    /// all other entries remain cached.
    ///
    /// # Arguments
    ///
    /// * `target_vmid` - The 16-bit VMID to invalidate (STE.S2VMID, §5.2)
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// cache.invalidate_by_vmid(42);
    /// ```
    pub fn invalidate_by_vmid(&self, target_vmid: u16) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        // Scan all entries; evict those tagged with the target VMID.
        for entry in self.entries.iter() {
            if entry.value().vmid == target_vmid {
                keys_to_remove.push(*entry.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }

        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all TLB entries tagged with both the given VMID and ASID.
    ///
    /// Implements `CMD_TLBI_NH_ASID` per ARM SMMU v3 §4.4.2.2 (NS/Realm queues):
    /// "Invalidate by ASID and VMID" — only entries whose `vmid` AND `asid`
    /// both match are evicted.
    ///
    /// Note: `CMD_TLBI_EL2_ASID` (§4.4.2.10) uses ASID-only; use `invalidate_by_asid` for that.
    ///
    /// # Arguments
    ///
    /// * `target_vmid` - The 16-bit VMID to match
    /// * `target_asid` - The 16-bit ASID to match
    pub fn invalidate_by_vmid_and_asid(&self, target_vmid: u16, target_asid: u16) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry in self.entries.iter() {
            let e = entry.value();
            if e.vmid == target_vmid && e.asid == target_asid {
                keys_to_remove.push(*entry.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }

        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all TLB entries matching the given VA and ASID (§4.4 VA-targeted TLBI).
    ///
    /// Implements `CMD_TLBI_NH_VA`, `CMD_TLBI_EL2_VA`, `CMD_TLBI_EL3_VA` selective
    /// invalidation: only entries whose `iova` matches the page-aligned `va` AND whose
    /// `asid` matches `target_asid` are evicted.
    ///
    /// # Arguments
    ///
    /// * `va`         - Virtual address (raw u64; lower 12 bits are masked / ignored)
    /// * `target_asid`- ASID to match
    pub fn invalidate_by_va_and_asid(&self, va: u64, target_asid: u16) {
        const PAGE_MASK: u64 = 0xFFFF_FFFF_FFFF_F000;
        let page_va = va & PAGE_MASK;

        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            if e.asid == target_asid && (e.iova.as_u64() & PAGE_MASK) == page_va {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all TLB entries matching the given VA, regardless of ASID (§4.4 VAA TLBI).
    ///
    /// Implements `CMD_TLBI_NH_VAA`, `CMD_TLBI_EL2_VAA`, `CMD_TLBI_S_EL2_VAA` —
    /// evicts any entry whose `iova` matches the page-aligned `va`, for any ASID.
    ///
    /// # Arguments
    ///
    /// * `va` - Virtual address (raw u64; lower 12 bits are masked / ignored)
    pub fn invalidate_by_va(&self, va: u64) {
        const PAGE_MASK: u64 = 0xFFFF_FFFF_FFFF_F000;
        let page_va = va & PAGE_MASK;

        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            if (entry_ref.value().iova.as_u64() & PAGE_MASK) == page_va {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate all TLB entries within a VA range for a given ASID (§4.4.1.1 RIL).
    ///
    /// Implements range-based TLBI: evicts entries where
    /// `start <= entry.iova <= end` AND `entry.asid == target_asid`.
    ///
    /// # Arguments
    ///
    /// * `start`      - Inclusive start of the VA range (raw u64)
    /// * `end`        - Inclusive end of the VA range (raw u64)
    /// * `target_asid`- ASID to match
    pub fn invalidate_by_va_range_and_asid(&self, start: u64, end: u64, target_asid: u16) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            let iova = e.iova.as_u64();
            if e.asid == target_asid && iova >= start && iova <= end {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate TLB entries matching a given VMID, VA, and ASID (§4.4.2.3).
    ///
    /// Implements `CMD_TLBI_NH_VA`: evicts EL1_EL0 stage-1 entries where
    /// `entry.vmid == target_vmid` AND `entry.asid == target_asid` AND
    /// `entry.iova` matches the page-aligned `va`.
    ///
    /// This is the VMID-scoped version of `invalidate_by_va_and_asid`.
    ///
    /// # Arguments
    ///
    /// * `target_vmid` - VMID to match
    /// * `va`          - Virtual address (raw u64; lower 12 bits are masked)
    /// * `target_asid` - ASID to match
    pub fn invalidate_by_vmid_and_va_and_asid(&self, target_vmid: u16, va: u64, target_asid: u16) {
        const PAGE_MASK: u64 = 0xFFFF_FFFF_FFFF_F000;
        let page_va = va & PAGE_MASK;

        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            if e.vmid == target_vmid
                && e.asid == target_asid
                && (e.iova.as_u64() & PAGE_MASK) == page_va
            {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate TLB entries matching a given VMID, VA range, and ASID (§4.4.2.3 RIL).
    ///
    /// Implements range-based `CMD_TLBI_NH_VA` (RIL path): evicts entries where
    /// `entry.vmid == target_vmid` AND `entry.asid == target_asid` AND
    /// `start <= entry.iova <= end`.
    ///
    /// # Arguments
    ///
    /// * `target_vmid` - VMID to match
    /// * `start`       - Inclusive start of the VA range (raw u64)
    /// * `end`         - Inclusive end of the VA range (raw u64)
    /// * `target_asid` - ASID to match
    pub fn invalidate_by_vmid_and_va_range_and_asid(
        &self,
        target_vmid: u16,
        start: u64,
        end: u64,
        target_asid: u16,
    ) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            let iova = e.iova.as_u64();
            if e.vmid == target_vmid && e.asid == target_asid && iova >= start && iova <= end {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate TLB entries matching a given VMID and VA (any ASID) (§4.4.2.4).
    ///
    /// Implements `CMD_TLBI_NH_VAA`: evicts EL1_EL0 stage-1 entries where
    /// `entry.vmid == target_vmid` AND `entry.iova` matches the page-aligned `va`,
    /// regardless of ASID.
    ///
    /// This is the VMID-scoped version of `invalidate_by_va`.
    ///
    /// # Arguments
    ///
    /// * `target_vmid` - VMID to match
    /// * `va`          - Virtual address (raw u64; lower 12 bits are masked)
    pub fn invalidate_by_vmid_and_va(&self, target_vmid: u16, va: u64) {
        const PAGE_MASK: u64 = 0xFFFF_FFFF_FFFF_F000;
        let page_va = va & PAGE_MASK;

        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            if e.vmid == target_vmid && (e.iova.as_u64() & PAGE_MASK) == page_va {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate TLB entries by VMID with wildcard masking (§6.3.9 CR0.VMW).
    ///
    /// Evicts entries where `(entry.vmid & vmid_mask) == (target_vmid & vmid_mask)`.
    /// When `vmid_mask == 0xFFFF` (VMW=0), this is an exact VMID match.
    /// When `vmid_mask == 0` (VMW=16), all VMIDs match (global invalidation).
    ///
    /// # Arguments
    ///
    /// * `target_vmid` - Base VMID from the TLBI command operand
    /// * `vmid_mask`   - Bitmask derived from CR0.VMW — `(0xFFFF << vmw) as u16`
    pub fn invalidate_by_vmid_with_mask(&self, target_vmid: u16, vmid_mask: u16) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            if (e.vmid & vmid_mask) == (target_vmid & vmid_mask) {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// CONF-GAP-7: Invalidate TLB entries by VMID and IPA range (§4.4 `CMD_TLBI_S2_IPA`).
    ///
    /// Implements IPA-selective Stage-2 invalidation: evicts entries where
    /// `(entry.vmid & vmid_mask) == (target_vmid & vmid_mask)` AND
    /// `entry.ipa != 0` AND `entry.ipa` is within `[ipa_start, ipa_end]` (inclusive).
    ///
    /// Entries with `ipa == 0` are Stage-1-only entries and are NOT matched,
    /// preventing over-invalidation of non-two-stage TLB entries.
    ///
    /// # Arguments
    ///
    /// * `target_vmid`  - VMID from the TLBI command operand
    /// * `vmid_mask`    - Bitmask from CR0.VMW — `(0xFFFF << vmw) as u16`
    /// * `ipa_start`    - Inclusive start of the IPA range (raw u64)
    /// * `ipa_end`      - Inclusive end of the IPA range (raw u64)
    pub fn invalidate_by_vmid_and_ipa(&self, target_vmid: u16, vmid_mask: u16, ipa_start: u64, ipa_end: u64) {
        let mut keys_to_remove: SmallVec<[CacheKey; 32]> = SmallVec::new();

        for entry_ref in self.entries.iter() {
            let e = entry_ref.value();
            // Only match two-stage entries (ipa != 0) within the IPA range.
            if e.ipa != 0
                && (e.vmid & vmid_mask) == (target_vmid & vmid_mask)
                && e.ipa >= ipa_start
                && e.ipa <= ipa_end
            {
                keys_to_remove.push(*entry_ref.key());
            }
        }

        let removed_count = keys_to_remove.len() as u64;
        for key in keys_to_remove {
            self.remove_entry(&key);
        }
        self.statistics.invalidations.fetch_add(removed_count, Ordering::Relaxed);
    }

    /// Invalidate a specific entry by exact key match
    ///
    /// Removes a single cached translation if it exists.
    ///
    /// # Arguments
    ///
    /// * `key` - Exact cache key to invalidate
    ///
    /// # Returns
    ///
    /// Returns `true` if entry was found and removed, `false` otherwise.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, CacheKey, CacheEntry, ReplacementPolicy};
    /// # use smmu::{IOVA, PA, PagePermissions, SecurityState, StreamID, PASID};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// # let key = CacheKey::new(StreamID::new(1).unwrap(), PASID::new(0).unwrap(),
    /// #     IOVA::new(0x1000).unwrap(), SecurityState::NonSecure);
    /// if cache.invalidate_entry(&key) {
    ///     println!("Entry invalidated");
    /// }
    /// ```
    pub fn invalidate_entry(&self, key: &CacheKey) -> bool {
        if self.entries.remove(key).is_some() {
            // entries.remove() above already removes the entry; do NOT call
            // self.remove_entry() again — that would attempt a second removal
            // and could silently delete a concurrently re-inserted entry.
            self.statistics.invalidations.fetch_add(1, Ordering::Relaxed);
            true
        } else {
            false
        }
    }

    /// Get current cache statistics
    ///
    /// Returns a reference to the atomic statistics counters that can be
    /// read without blocking cache operations.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// let stats = cache.statistics();
    /// println!("Hit rate: {:.2}%", stats.hit_rate());
    /// println!("Lookups: {}", stats.get_lookups());
    /// ```
    #[inline]
    pub fn statistics(&self) -> &CacheStatistics {
        &self.statistics
    }

    /// Clear all statistics counters
    ///
    /// Resets all statistics to zero. Does not affect cached entries.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// cache.clear_statistics();
    /// ```
    #[inline]
    pub fn clear_statistics(&self) {
        self.statistics.reset();
    }

    /// Get current number of cached entries
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// println!("Cache contains {} entries", cache.len());
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Check if cache is empty
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// if cache.is_empty() {
    ///     println!("Cache is empty");
    /// }
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get cache capacity
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// println!("Cache capacity: {}", cache.capacity());
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Get replacement policy
    ///
    /// # Example
    ///
    /// ```rust
    /// # use smmu::cache::{TlbCache, ReplacementPolicy};
    /// # let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
    /// match cache.policy() {
    ///     ReplacementPolicy::Lru => println!("Using LRU"),
    ///     ReplacementPolicy::Fifo => println!("Using FIFO"),
    /// }
    /// ```
    #[inline]
    pub fn policy(&self) -> ReplacementPolicy {
        self.policy
    }
}

impl std::fmt::Debug for TlbCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TlbCache")
            .field("capacity", &self.capacity)
            .field("policy", &self.policy)
            .field("len", &self.len())
            .field("statistics", &self.statistics)
            .finish()
    }
}

// ============================================================================
// Unit Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // ------------------------------------------------------------------------
    // CacheEntry Tests (30+ tests)
    // ------------------------------------------------------------------------

    #[test]
    fn test_cache_entry_default_construction() {
        let entry = CacheEntry::default();
        assert_eq!(entry.iova.as_u64(), 0);
        assert_eq!(entry.physical_address.as_u64(), 0);
        assert_eq!(entry.permissions, PagePermissions::none());
        assert_eq!(entry.security_state, SecurityState::NonSecure);
        assert_eq!(entry.timestamp, 0);
    }

    #[test]
    fn test_cache_entry_new_default_security() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_only();

        let entry = CacheEntry::new(iova, pa, perms, 42);

        assert_eq!(entry.iova, iova);
        assert_eq!(entry.physical_address, pa);
        assert_eq!(entry.permissions, perms);
        assert_eq!(entry.security_state, SecurityState::NonSecure);
        assert_eq!(entry.timestamp, 42);
    }

    #[test]
    fn test_cache_entry_new_with_security_nonsecure() {
        let iova = IOVA::new(0x3000).unwrap();
        let pa = PA::new(0x4000).unwrap();
        let perms = PagePermissions::read_write();

        let entry = CacheEntry::new_with_security(iova, pa, perms, SecurityState::NonSecure, 100);

        assert_eq!(entry.security_state, SecurityState::NonSecure);
        assert_eq!(entry.timestamp, 100);
    }

    #[test]
    fn test_cache_entry_new_with_security_secure() {
        let iova = IOVA::new(0x5000).unwrap();
        let pa = PA::new(0x6000).unwrap();
        let perms = PagePermissions::all();

        let entry = CacheEntry::new_with_security(iova, pa, perms, SecurityState::Secure, 200);

        assert_eq!(entry.security_state, SecurityState::Secure);
        assert_eq!(entry.timestamp, 200);
    }

    #[test]
    fn test_cache_entry_new_with_security_realm() {
        let iova = IOVA::new(0x7000).unwrap();
        let pa = PA::new(0x8000).unwrap();
        let perms = PagePermissions::read_execute();

        let entry = CacheEntry::new_with_security(iova, pa, perms, SecurityState::Realm, 300);

        assert_eq!(entry.security_state, SecurityState::Realm);
        assert_eq!(entry.timestamp, 300);
    }

    #[test]
    fn test_cache_entry_copy_semantics() {
        let entry1 = CacheEntry::default();
        let entry2 = entry1; // Should copy, not move

        // Both should be usable
        assert_eq!(entry1.timestamp, 0);
        assert_eq!(entry2.timestamp, 0);
    }

    #[test]
    fn test_cache_entry_clone_semantics() {
        let entry1 = CacheEntry::default();
        let entry2 = entry1.clone();

        assert_eq!(entry1, entry2);
    }

    #[test]
    fn test_cache_entry_equality() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_only();

        let entry1 = CacheEntry::new(iova, pa, perms, 42);
        let entry2 = CacheEntry::new(iova, pa, perms, 42);

        assert_eq!(entry1, entry2);
    }

    #[test]
    fn test_cache_entry_inequality_different_iova() {
        let iova1 = IOVA::new(0x1000).unwrap();
        let iova2 = IOVA::new(0x2000).unwrap();
        let pa = PA::new(0x3000).unwrap();
        let perms = PagePermissions::read_only();

        let entry1 = CacheEntry::new(iova1, pa, perms, 42);
        let entry2 = CacheEntry::new(iova2, pa, perms, 42);

        assert_ne!(entry1, entry2);
    }

    #[test]
    fn test_cache_entry_inequality_different_pa() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa1 = PA::new(0x2000).unwrap();
        let pa2 = PA::new(0x3000).unwrap();
        let perms = PagePermissions::read_only();

        let entry1 = CacheEntry::new(iova, pa1, perms, 42);
        let entry2 = CacheEntry::new(iova, pa2, perms, 42);

        assert_ne!(entry1, entry2);
    }

    #[test]
    fn test_cache_entry_inequality_different_permissions() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms1 = PagePermissions::read_only();
        let perms2 = PagePermissions::read_write();

        let entry1 = CacheEntry::new(iova, pa, perms1, 42);
        let entry2 = CacheEntry::new(iova, pa, perms2, 42);

        assert_ne!(entry1, entry2);
    }

    #[test]
    fn test_cache_entry_inequality_different_security_state() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_only();

        let entry1 = CacheEntry::new_with_security(iova, pa, perms, SecurityState::NonSecure, 42);
        let entry2 = CacheEntry::new_with_security(iova, pa, perms, SecurityState::Secure, 42);

        assert_ne!(entry1, entry2);
    }

    #[test]
    fn test_cache_entry_inequality_different_timestamp() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_only();

        let entry1 = CacheEntry::new(iova, pa, perms, 42);
        let entry2 = CacheEntry::new(iova, pa, perms, 100);

        assert_ne!(entry1, entry2);
    }

    #[test]
    fn test_cache_entry_debug_format() {
        let entry = CacheEntry::default();
        let debug_str = format!("{entry:?}");
        assert!(debug_str.contains("CacheEntry"));
    }

    #[test]
    fn test_cache_entry_large_addresses() {
        let iova = IOVA::new(0xFFFF_FFFF_F000).unwrap();
        let pa = PA::new(0xFFFF_FFFF_E000).unwrap();
        let perms = PagePermissions::read_write();

        let entry = CacheEntry::new(iova, pa, perms, u64::MAX);

        assert_eq!(entry.iova.as_u64(), 0xFFFF_FFFF_F000);
        assert_eq!(entry.physical_address.as_u64(), 0xFFFF_FFFF_E000);
        assert_eq!(entry.timestamp, u64::MAX);
    }

    #[test]
    fn test_cache_entry_zero_timestamp() {
        let entry = CacheEntry::default();
        assert_eq!(entry.timestamp, 0);
    }

    #[test]
    fn test_cache_entry_max_timestamp() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_only();

        let entry = CacheEntry::new(iova, pa, perms, u64::MAX);
        assert_eq!(entry.timestamp, u64::MAX);
    }

    #[test]
    fn test_cache_entry_permissions_none() {
        let entry = CacheEntry::default();
        assert_eq!(entry.permissions, PagePermissions::none());
    }

    #[test]
    fn test_cache_entry_permissions_read_only() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_only();

        let entry = CacheEntry::new(iova, pa, perms, 0);
        assert_eq!(entry.permissions, PagePermissions::read_only());
    }

    #[test]
    fn test_cache_entry_permissions_write_only() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::write_only();

        let entry = CacheEntry::new(iova, pa, perms, 0);
        assert_eq!(entry.permissions, PagePermissions::write_only());
    }

    #[test]
    fn test_cache_entry_permissions_execute_only() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::new(false, false, true);

        let entry = CacheEntry::new(iova, pa, perms, 0);
        assert!(!entry.permissions.read());
        assert!(!entry.permissions.write());
        assert!(entry.permissions.execute());
    }

    #[test]
    fn test_cache_entry_permissions_read_write() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_write();

        let entry = CacheEntry::new(iova, pa, perms, 0);
        assert_eq!(entry.permissions, PagePermissions::read_write());
    }

    #[test]
    fn test_cache_entry_permissions_read_execute() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_execute();

        let entry = CacheEntry::new(iova, pa, perms, 0);
        assert_eq!(entry.permissions, PagePermissions::read_execute());
    }

    #[test]
    fn test_cache_entry_permissions_all() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::all();

        let entry = CacheEntry::new(iova, pa, perms, 0);
        assert_eq!(entry.permissions, PagePermissions::all());
    }

    #[test]
    fn test_cache_entry_permissions_write_execute() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::new(false, true, true);

        let entry = CacheEntry::new(iova, pa, perms, 0);
        assert!(!entry.permissions.read());
        assert!(entry.permissions.write());
        assert!(entry.permissions.execute());
    }

    #[test]
    fn test_cache_entry_const_new() {
        const ENTRY: CacheEntry =
            CacheEntry::new(IOVA::const_new(0x1000), PA::const_new(0x2000), PagePermissions::none(), 42);

        assert_eq!(ENTRY.iova.as_u64(), 0x1000);
        assert_eq!(ENTRY.physical_address.as_u64(), 0x2000);
        assert_eq!(ENTRY.timestamp, 42);
    }

    #[test]
    fn test_cache_entry_const_new_with_security() {
        const ENTRY: CacheEntry = CacheEntry::new_with_security(
            IOVA::const_new(0x1000),
            PA::const_new(0x2000),
            PagePermissions::none(),
            SecurityState::Secure,
            100,
        );

        assert_eq!(ENTRY.security_state, SecurityState::Secure);
        assert_eq!(ENTRY.timestamp, 100);
    }

    #[test]
    fn test_cache_entry_multiple_copies() {
        let entry1 = CacheEntry::default();
        let entry2 = entry1;
        let entry3 = entry2;
        let entry4 = entry3;

        // All should be equal
        assert_eq!(entry1, entry2);
        assert_eq!(entry2, entry3);
        assert_eq!(entry3, entry4);
    }

    #[test]
    fn test_cache_entry_page_aligned_addresses() {
        let iova = IOVA::new_page_aligned(0x1000).unwrap();
        let pa = PA::new_page_aligned(0x2000).unwrap();
        let perms = PagePermissions::read_only();

        let entry = CacheEntry::new(iova, pa, perms, 0);

        assert!(entry.iova.is_page_aligned());
        assert!(entry.physical_address.is_page_aligned());
    }

    #[test]
    fn test_cache_entry_non_page_aligned_addresses() {
        // Cache entries can have non-page-aligned addresses (page offset preserved)
        let iova = IOVA::new(0x1234).unwrap();
        let pa = PA::new(0x5678).unwrap();
        let perms = PagePermissions::read_only();

        let entry = CacheEntry::new(iova, pa, perms, 0);

        assert_eq!(entry.iova.as_u64(), 0x1234);
        assert_eq!(entry.physical_address.as_u64(), 0x5678);
    }

    #[test]
    fn test_cache_entry_security_state_values() {
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_only();

        // Test all three security states
        let entry_nonsecure = CacheEntry::new_with_security(iova, pa, perms, SecurityState::NonSecure, 0);
        let entry_secure = CacheEntry::new_with_security(iova, pa, perms, SecurityState::Secure, 0);
        let entry_realm = CacheEntry::new_with_security(iova, pa, perms, SecurityState::Realm, 0);

        assert_eq!(entry_nonsecure.security_state, SecurityState::NonSecure);
        assert_eq!(entry_secure.security_state, SecurityState::Secure);
        assert_eq!(entry_realm.security_state, SecurityState::Realm);
    }

    // ------------------------------------------------------------------------
    // CacheKey Tests (15+ tests)
    // ------------------------------------------------------------------------

    #[test]
    fn test_cache_key_new() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        assert_eq!(key.stream_id, stream_id);
        assert_eq!(key.pasid, pasid);
        assert_eq!(key.iova, iova);
        assert_eq!(key.security_state, SecurityState::NonSecure);
    }

    #[test]
    fn test_cache_key_equality_same_values() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        assert_eq!(key1, key2);
    }

    #[test]
    fn test_cache_key_inequality_different_stream_id() {
        let stream1 = StreamID::new(100).unwrap();
        let stream2 = StreamID::new(200).unwrap();
        let pasid = PASID::new(300).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream1, pasid, iova, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream2, pasid, iova, SecurityState::NonSecure);

        assert_ne!(key1, key2);
    }

    #[test]
    fn test_cache_key_inequality_different_pasid() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid1 = PASID::new(200).unwrap();
        let pasid2 = PASID::new(300).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid1, iova, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid2, iova, SecurityState::NonSecure);

        assert_ne!(key1, key2);
    }

    #[test]
    fn test_cache_key_inequality_different_iova() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova1 = IOVA::new(0x1000).unwrap();
        let iova2 = IOVA::new(0x2000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid, iova1, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid, iova2, SecurityState::NonSecure);

        assert_ne!(key1, key2);
    }

    #[test]
    fn test_cache_key_inequality_different_security_state() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid, iova, SecurityState::Secure);

        assert_ne!(key1, key2);
    }

    #[test]
    fn test_cache_key_copy_semantics() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let key2 = key1; // Should copy

        assert_eq!(key1, key2);
    }

    #[test]
    fn test_cache_key_clone_semantics() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let key2 = key1.clone();

        assert_eq!(key1, key2);
    }

    #[test]
    fn test_cache_key_debug_format() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let debug_str = format!("{key:?}");

        assert!(debug_str.contains("CacheKey"));
    }

    #[test]
    fn test_cache_key_const_construction() {
        // Test that CacheKey::new is const
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::const_new(0x1000);

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        assert_eq!(key.stream_id.as_u32(), 100);
        assert_eq!(key.pasid.as_u32(), 200);
        assert_eq!(key.iova.as_u64(), 0x1000);
    }

    #[test]
    fn test_cache_key_max_values() {
        let stream_id = StreamID::new(u32::from(u16::MAX)).unwrap();
        let pasid = PASID::new(0xF_FFFF).unwrap(); // 20-bit max
        let iova = IOVA::new(u64::MAX).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::Realm);

        assert_eq!(key.stream_id.as_u32(), u32::from(u16::MAX));
        assert_eq!(key.pasid.as_u32(), 0xF_FFFF);
        assert_eq!(key.iova.as_u64(), u64::MAX);
    }

    #[test]
    fn test_cache_key_min_values() {
        let stream_id = StreamID::new(0).unwrap();
        let pasid = PASID::new(0).unwrap();
        let iova = IOVA::new(0).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        assert_eq!(key.stream_id.as_u32(), 0);
        assert_eq!(key.pasid.as_u32(), 0);
        assert_eq!(key.iova.as_u64(), 0);
    }

    #[test]
    fn test_cache_key_page_aligned_iova() {
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new_page_aligned(0x1000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        assert!(key.iova.is_page_aligned());
    }

    #[test]
    fn test_cache_key_all_security_states() {
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key_nonsecure = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let key_secure = CacheKey::new(stream_id, pasid, iova, SecurityState::Secure);
        let key_realm = CacheKey::new(stream_id, pasid, iova, SecurityState::Realm);

        // All keys should be different
        assert_ne!(key_nonsecure, key_secure);
        assert_ne!(key_secure, key_realm);
        assert_ne!(key_nonsecure, key_realm);
    }

    #[test]
    fn test_cache_key_hashability() {
        use std::collections::HashMap;

        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        // Should be able to use as HashMap key
        let mut map = HashMap::new();
        map.insert(key, 42);

        assert_eq!(map.get(&key), Some(&42));
    }

    // ------------------------------------------------------------------------
    // CacheKeyHash Tests (20+ tests)
    // ------------------------------------------------------------------------

    #[test]
    fn test_cache_key_hash_uses_murmur_constants() {
        // Verify the hash uses the optimized murmur-like mixing constants
        // These constants provide good distribution with minimal operations
        const MIX_CONSTANT_1: u64 = 0xff51_afd7_ed55_8ccd;
        const MIX_CONSTANT_2: u64 = 0xc4ce_b9fe_1a85_ec53;

        // Just verify the constants are the expected values
        assert_eq!(MIX_CONSTANT_1, 0xff51_afd7_ed55_8ccd);
        assert_eq!(MIX_CONSTANT_2, 0xc4ce_b9fe_1a85_ec53);
    }

    #[test]
    fn test_cache_key_hash_deterministic() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        let hash1 = CacheKeyHash::hash(&key);
        let hash2 = CacheKeyHash::hash(&key);

        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_cache_key_hash_different_stream_id() {
        let stream1 = StreamID::new(100).unwrap();
        let stream2 = StreamID::new(101).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream1, pasid, iova, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream2, pasid, iova, SecurityState::NonSecure);

        let hash1 = CacheKeyHash::hash(&key1);
        let hash2 = CacheKeyHash::hash(&key2);

        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_cache_key_hash_different_pasid() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid1 = PASID::new(200).unwrap();
        let pasid2 = PASID::new(201).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid1, iova, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid2, iova, SecurityState::NonSecure);

        let hash1 = CacheKeyHash::hash(&key1);
        let hash2 = CacheKeyHash::hash(&key2);

        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_cache_key_hash_different_iova_page() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova1 = IOVA::new(0x1000).unwrap();
        let iova2 = IOVA::new(0x2000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid, iova1, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid, iova2, SecurityState::NonSecure);

        let hash1 = CacheKeyHash::hash(&key1);
        let hash2 = CacheKeyHash::hash(&key2);

        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_cache_key_hash_page_offset_ignored() {
        // Lower 12 bits should be ignored (page offset)
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova1 = IOVA::new(0x1000).unwrap(); // Page aligned
        let iova2 = IOVA::new(0x1FFF).unwrap(); // Same page, different offset

        let key1 = CacheKey::new(stream_id, pasid, iova1, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid, iova2, SecurityState::NonSecure);

        let hash1 = CacheKeyHash::hash(&key1);
        let hash2 = CacheKeyHash::hash(&key2);

        assert_eq!(hash1, hash2); // Should hash to same value
    }

    #[test]
    fn test_cache_key_hash_different_security_state() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key1 = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid, iova, SecurityState::Secure);

        let hash1 = CacheKeyHash::hash(&key1);
        let hash2 = CacheKeyHash::hash(&key2);

        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_cache_key_hash_max_values() {
        let stream_id = StreamID::new(u32::from(u16::MAX)).unwrap();
        let pasid = PASID::new(0xF_FFFF).unwrap();
        let iova = IOVA::new(u64::MAX).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::Realm);

        // Should not panic
        let _hash = CacheKeyHash::hash(&key);
    }

    #[test]
    fn test_cache_key_hash_min_values() {
        let stream_id = StreamID::new(0).unwrap();
        let pasid = PASID::new(0).unwrap();
        let iova = IOVA::new(0).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        let hash = CacheKeyHash::hash(&key);

        // Hash should be non-zero even with zero inputs
        assert_ne!(hash, 0);
    }

    #[test]
    fn test_cache_key_hash_distribution_different_streams() {
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let mut hashes = Vec::new();

        for stream in 0..100 {
            let stream_id = StreamID::new(stream).unwrap();
            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            hashes.push(CacheKeyHash::hash(&key));
        }

        // All hashes should be unique
        hashes.sort_unstable();
        hashes.dedup();
        assert_eq!(hashes.len(), 100);
    }

    #[test]
    fn test_cache_key_hash_distribution_different_pasids() {
        let stream_id = StreamID::new(100).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let mut hashes = Vec::new();

        for pasid_val in 0..100 {
            let pasid = PASID::new(pasid_val).unwrap();
            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            hashes.push(CacheKeyHash::hash(&key));
        }

        // All hashes should be unique
        hashes.sort_unstable();
        hashes.dedup();
        assert_eq!(hashes.len(), 100);
    }

    #[test]
    fn test_cache_key_hash_distribution_different_pages() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let mut hashes = Vec::new();

        for page in 0..100 {
            let iova = IOVA::new(page * 0x1000).unwrap();
            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            hashes.push(CacheKeyHash::hash(&key));
        }

        // All hashes should be unique
        hashes.sort_unstable();
        hashes.dedup();
        assert_eq!(hashes.len(), 100);
    }

    #[test]
    fn test_cache_key_hash_distribution_security_states() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key_nonsecure = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let key_secure = CacheKey::new(stream_id, pasid, iova, SecurityState::Secure);
        let key_realm = CacheKey::new(stream_id, pasid, iova, SecurityState::Realm);

        let hash_nonsecure = CacheKeyHash::hash(&key_nonsecure);
        let hash_secure = CacheKeyHash::hash(&key_secure);
        let hash_realm = CacheKeyHash::hash(&key_realm);

        // All should be different
        assert_ne!(hash_nonsecure, hash_secure);
        assert_ne!(hash_secure, hash_realm);
        assert_ne!(hash_nonsecure, hash_realm);
    }

    #[test]
    fn test_cache_key_hash_large_iova() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova = IOVA::new(0xFFFF_FFFF_FFFF_F000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        // Should not panic with large addresses
        let _hash = CacheKeyHash::hash(&key);
    }

    #[test]
    fn test_cache_key_hash_page_number_upper_bits() {
        // Test that upper bits of page number are hashed
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova1 = IOVA::new(0x0000_0001_0000).unwrap(); // Low page number
        let iova2 = IOVA::new(0x1000_0000_0000).unwrap(); // High page number

        let key1 = CacheKey::new(stream_id, pasid, iova1, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid, iova2, SecurityState::NonSecure);

        let hash1 = CacheKeyHash::hash(&key1);
        let hash2 = CacheKeyHash::hash(&key2);

        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_cache_key_hash_avalanche_effect() {
        // Single bit change should dramatically change hash
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();
        let iova1 = IOVA::new(0x1000).unwrap();
        let iova2 = IOVA::new(0x2000).unwrap(); // Single bit difference in page number

        let key1 = CacheKey::new(stream_id, pasid, iova1, SecurityState::NonSecure);
        let key2 = CacheKey::new(stream_id, pasid, iova2, SecurityState::NonSecure);

        let hash1 = CacheKeyHash::hash(&key1);
        let hash2 = CacheKeyHash::hash(&key2);

        // Count differing bits
        let xor = hash1 ^ hash2;
        let bit_diff = xor.count_ones();

        // Expect significant bit difference (avalanche effect)
        assert!(bit_diff > 10, "Expected avalanche effect, got {} bits different", bit_diff);
    }

    #[test]
    fn test_cache_key_hash_collision_resistance() {
        // Generate many hashes and check for collisions
        use std::collections::HashSet;

        let mut hash_set = HashSet::new();

        for stream in 0..50 {
            for pasid_val in 0..50 {
                let stream_id = StreamID::new(stream).unwrap();
                let pasid = PASID::new(pasid_val).unwrap();
                let iova = IOVA::new(u64::from(stream) * 0x1000 + u64::from(pasid_val) * 0x1_0000).unwrap();

                let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
                let hash = CacheKeyHash::hash(&key);

                // Should not have any collisions
                assert!(hash_set.insert(hash), "Hash collision detected");
            }
        }

        assert_eq!(hash_set.len(), 50 * 50);
    }

    #[test]
    fn test_cache_key_hash_wrapping_mul() {
        // Ensure wrapping multiplication doesn't cause issues
        let stream_id = StreamID::new(u32::from(u16::MAX)).unwrap();
        let pasid = PASID::new(0xF_FFFF).unwrap();
        let iova = IOVA::new(u64::MAX).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::Realm);

        // Should not panic with wrapping multiplication
        let hash = CacheKeyHash::hash(&key);

        // Hash should be deterministic
        let hash2 = CacheKeyHash::hash(&key);
        assert_eq!(hash, hash2);
    }

    #[test]
    fn test_cache_key_hash_fnv_algorithm() {
        // Verify the hash algorithm matches the production formula exactly.
        // Inputs: stream_id=1, pasid=2, iova=0x3000 (page number 3), security=NonSecure
        let stream_id = StreamID::new(1).unwrap();
        let pasid_val = PASID::new(2).unwrap();
        let iova = IOVA::new(0x3000).unwrap(); // page number = 0x3000 >> 12 = 3

        let key = CacheKey::new(stream_id, pasid_val, iova, SecurityState::NonSecure);

        // Manual calculation matching the FIXED production formula in CacheKeyHash::hash():
        //   stream = u64::from(stream_id).wrapping_mul(0x9e37_79b9_7f4a_7c15)
        //   pasid  = u64::from(pasid).wrapping_mul(0x6c62_272e_07bb_0142)
        //   security = u64::from(security_state as u8) & 0x3
        //   page = (iova >> 12).wrapping_mul(0x517c_c1b7_2722_0a95)
        //   hash = (stream + pasid + security + page) ^ 0xcbf2_9ce4_8422_2325
        //   followed by the three-round murmur finalizer
        let stream = 1u64.wrapping_mul(0x9e37_79b9_7f4a_7c15_u64);
        let pasid = 2u64.wrapping_mul(0x6c62_272e_07bb_0142_u64);
        let security = u64::from(SecurityState::NonSecure as u8) & 0x3;
        // IOVA=0x3000, page number = 0x3000 >> 12 = 3
        let page = 3u64.wrapping_mul(0x517c_c1b7_2722_0a95_u64);

        let mut expected = stream
            .wrapping_add(pasid)
            .wrapping_add(security)
            .wrapping_add(page)
            ^ 0xcbf2_9ce4_8422_2325_u64;
        expected ^= expected >> 33;
        expected = expected.wrapping_mul(0xff51_afd7_ed55_8ccd);
        expected ^= expected >> 33;
        expected = expected.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
        expected ^= expected >> 33;

        let actual = CacheKeyHash::hash(&key);

        assert_eq!(actual, expected);
    }

    // ------------------------------------------------------------------------
    // StreamPASIDKey Tests (10+ tests)
    // ------------------------------------------------------------------------

    #[test]
    fn test_stream_pasid_key_new() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        assert_eq!(key.stream_id, stream_id);
        assert_eq!(key.pasid, pasid);
    }

    #[test]
    fn test_stream_pasid_key_equality() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key1 = StreamPASIDKey::new(stream_id, pasid);
        let key2 = StreamPASIDKey::new(stream_id, pasid);

        assert_eq!(key1, key2);
    }

    #[test]
    fn test_stream_pasid_key_inequality_different_stream() {
        let stream1 = StreamID::new(100).unwrap();
        let stream2 = StreamID::new(101).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key1 = StreamPASIDKey::new(stream1, pasid);
        let key2 = StreamPASIDKey::new(stream2, pasid);

        assert_ne!(key1, key2);
    }

    #[test]
    fn test_stream_pasid_key_inequality_different_pasid() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid1 = PASID::new(200).unwrap();
        let pasid2 = PASID::new(201).unwrap();

        let key1 = StreamPASIDKey::new(stream_id, pasid1);
        let key2 = StreamPASIDKey::new(stream_id, pasid2);

        assert_ne!(key1, key2);
    }

    #[test]
    fn test_stream_pasid_key_copy_semantics() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key1 = StreamPASIDKey::new(stream_id, pasid);
        let key2 = key1; // Should copy

        assert_eq!(key1, key2);
    }

    #[test]
    fn test_stream_pasid_key_clone_semantics() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key1 = StreamPASIDKey::new(stream_id, pasid);
        let key2 = key1.clone();

        assert_eq!(key1, key2);
    }

    #[test]
    fn test_stream_pasid_key_debug_format() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);
        let debug_str = format!("{key:?}");

        assert!(debug_str.contains("StreamPASIDKey"));
    }

    #[test]
    fn test_stream_pasid_key_const_construction() {
        // Test that StreamPASIDKey::new is const
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        assert_eq!(key.stream_id.as_u32(), 100);
        assert_eq!(key.pasid.as_u32(), 200);
    }

    #[test]
    fn test_stream_pasid_key_max_values() {
        let stream_id = StreamID::new(u32::from(u16::MAX)).unwrap();
        let pasid = PASID::new(0xF_FFFF).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        assert_eq!(key.stream_id.as_u32(), u32::from(u16::MAX));
        assert_eq!(key.pasid.as_u32(), 0xF_FFFF);
    }

    #[test]
    fn test_stream_pasid_key_min_values() {
        let stream_id = StreamID::new(0).unwrap();
        let pasid = PASID::new(0).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        assert_eq!(key.stream_id.as_u32(), 0);
        assert_eq!(key.pasid.as_u32(), 0);
    }

    #[test]
    fn test_stream_pasid_key_hashability() {
        use std::collections::HashMap;

        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        // Should be able to use as HashMap key
        let mut map = HashMap::new();
        map.insert(key, 42);

        assert_eq!(map.get(&key), Some(&42));
    }

    // ------------------------------------------------------------------------
    // StreamPASIDKeyHash Tests (10+ tests)
    // ------------------------------------------------------------------------

    #[test]
    fn test_stream_pasid_key_hash_uses_fast_mixing() {
        // Verify the hash uses the optimized murmur-like mixing constant
        const MIX_CONSTANT: u64 = 0xff51_afd7_ed55_8ccd;

        // Just verify the constant is the expected value
        assert_eq!(MIX_CONSTANT, 0xff51_afd7_ed55_8ccd);
    }

    #[test]
    fn test_stream_pasid_key_hash_deterministic() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        let hash1 = StreamPASIDKeyHash::hash(&key);
        let hash2 = StreamPASIDKeyHash::hash(&key);

        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_stream_pasid_key_hash_different_stream() {
        let stream1 = StreamID::new(100).unwrap();
        let stream2 = StreamID::new(101).unwrap();
        let pasid = PASID::new(200).unwrap();

        let key1 = StreamPASIDKey::new(stream1, pasid);
        let key2 = StreamPASIDKey::new(stream2, pasid);

        let hash1 = StreamPASIDKeyHash::hash(&key1);
        let hash2 = StreamPASIDKeyHash::hash(&key2);

        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_stream_pasid_key_hash_different_pasid() {
        let stream_id = StreamID::new(100).unwrap();
        let pasid1 = PASID::new(200).unwrap();
        let pasid2 = PASID::new(201).unwrap();

        let key1 = StreamPASIDKey::new(stream_id, pasid1);
        let key2 = StreamPASIDKey::new(stream_id, pasid2);

        let hash1 = StreamPASIDKeyHash::hash(&key1);
        let hash2 = StreamPASIDKeyHash::hash(&key2);

        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_stream_pasid_key_hash_max_values() {
        let stream_id = StreamID::new(u32::from(u16::MAX)).unwrap();
        let pasid = PASID::new(0xF_FFFF).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        // Should not panic
        let _hash = StreamPASIDKeyHash::hash(&key);
    }

    #[test]
    fn test_stream_pasid_key_hash_min_values() {
        let stream_id = StreamID::new(0).unwrap();
        let pasid = PASID::new(0).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        let hash = StreamPASIDKeyHash::hash(&key);

        // Hash should be non-zero even with zero inputs
        assert_ne!(hash, 0);
    }

    #[test]
    fn test_stream_pasid_key_hash_distribution_streams() {
        let pasid = PASID::new(200).unwrap();

        let mut hashes = Vec::new();

        for stream in 0..100 {
            let stream_id = StreamID::new(stream).unwrap();
            let key = StreamPASIDKey::new(stream_id, pasid);
            hashes.push(StreamPASIDKeyHash::hash(&key));
        }

        // All hashes should be unique
        hashes.sort_unstable();
        hashes.dedup();
        assert_eq!(hashes.len(), 100);
    }

    #[test]
    fn test_stream_pasid_key_hash_distribution_pasids() {
        let stream_id = StreamID::new(100).unwrap();

        let mut hashes = Vec::new();

        for pasid_val in 0..100 {
            let pasid = PASID::new(pasid_val).unwrap();
            let key = StreamPASIDKey::new(stream_id, pasid);
            hashes.push(StreamPASIDKeyHash::hash(&key));
        }

        // All hashes should be unique
        hashes.sort_unstable();
        hashes.dedup();
        assert_eq!(hashes.len(), 100);
    }

    #[test]
    fn test_stream_pasid_key_hash_collision_resistance() {
        use std::collections::HashSet;

        let mut hash_set = HashSet::new();

        for stream in 0..100 {
            for pasid_val in 0..100 {
                let stream_id = StreamID::new(stream).unwrap();
                let pasid = PASID::new(pasid_val).unwrap();

                let key = StreamPASIDKey::new(stream_id, pasid);
                let hash = StreamPASIDKeyHash::hash(&key);

                assert!(hash_set.insert(hash), "Hash collision detected");
            }
        }

        assert_eq!(hash_set.len(), 100 * 100);
    }

    #[test]
    fn test_stream_pasid_key_hash_fnv_algorithm() {
        // Verify FNV-1a algorithm implementation
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();

        let key = StreamPASIDKey::new(stream_id, pasid);

        // Manual calculation using new optimized algorithm
        let combined = ((1u64) << 32) | 2u64;
        let mut expected = combined.wrapping_add(0xdead_beef);
        expected ^= expected >> 33;
        expected = expected.wrapping_mul(0xff51_afd7_ed55_8ccd);
        expected ^= expected >> 33;

        let actual = StreamPASIDKeyHash::hash(&key);

        assert_eq!(actual, expected);
    }

    // ------------------------------------------------------------------------
    // TlbCache Tests (50+ comprehensive tests)
    // ------------------------------------------------------------------------

    #[test]
    fn test_tlb_cache_new_lru() {
        let cache = TlbCache::new(1024, ReplacementPolicy::Lru);
        assert_eq!(cache.capacity(), 1024);
        assert_eq!(cache.policy(), ReplacementPolicy::Lru);
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_tlb_cache_new_fifo() {
        let cache = TlbCache::new(512, ReplacementPolicy::Fifo);
        assert_eq!(cache.capacity(), 512);
        assert_eq!(cache.policy(), ReplacementPolicy::Fifo);
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    #[should_panic(expected = "TlbCache capacity must be greater than 0")]
    fn test_tlb_cache_new_zero_capacity() {
        let _cache = TlbCache::new(0, ReplacementPolicy::Lru);
    }

    #[test]
    fn test_tlb_cache_insert_single() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);

        assert_eq!(cache.len(), 1);
        assert!(!cache.is_empty());
        assert_eq!(cache.statistics().get_insertions(), 1);
    }

    #[test]
    fn test_tlb_cache_lookup_hit() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);

        let result = cache.lookup(&key);
        assert!(result.is_some());

        let found_entry = result.unwrap();
        assert_eq!(found_entry.iova, iova);
        assert_eq!(found_entry.physical_address, pa);

        assert_eq!(cache.statistics().get_lookups(), 1);
        assert_eq!(cache.statistics().get_hits(), 1);
        assert_eq!(cache.statistics().get_misses(), 0);
    }

    #[test]
    fn test_tlb_cache_lookup_miss() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);

        let result = cache.lookup(&key);
        assert!(result.is_none());

        assert_eq!(cache.statistics().get_lookups(), 1);
        assert_eq!(cache.statistics().get_hits(), 0);
        assert_eq!(cache.statistics().get_misses(), 1);
    }

    #[test]
    fn test_tlb_cache_multiple_inserts() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);

        for i in 0..10 {
            let stream_id = StreamID::new(i).unwrap();
            let pasid = PASID::new(i + 100).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_write(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 10);
        assert_eq!(cache.statistics().get_insertions(), 10);
    }

    #[test]
    fn test_tlb_cache_eviction_lru() {
        let cache = TlbCache::new(3, ReplacementPolicy::Lru);

        // Insert 3 entries to fill cache
        for i in 0..3 {
            let stream_id = StreamID::new(i).unwrap();
            let pasid = PASID::new(0).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 3);

        // Insert 4th entry - should evict least recently used
        let stream_id = StreamID::new(3).unwrap();
        let pasid = PASID::new(0).unwrap();
        let iova = IOVA::new(0x3000).unwrap();
        let pa = PA::new(0x6000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);

        assert_eq!(cache.len(), 3);
        assert_eq!(cache.statistics().get_evictions(), 1);
        assert_eq!(cache.statistics().get_insertions(), 4);
    }

    #[test]
    fn test_tlb_cache_eviction_fifo() {
        let cache = TlbCache::new(3, ReplacementPolicy::Fifo);

        // Insert 3 entries to fill cache
        for i in 0..3 {
            let stream_id = StreamID::new(i).unwrap();
            let pasid = PASID::new(0).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 3);

        // Insert 4th entry - should evict first inserted (FIFO)
        let stream_id = StreamID::new(3).unwrap();
        let pasid = PASID::new(0).unwrap();
        let iova = IOVA::new(0x3000).unwrap();
        let pa = PA::new(0x6000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);

        assert_eq!(cache.len(), 3);
        assert_eq!(cache.statistics().get_evictions(), 1);
    }

    #[test]
    fn test_tlb_cache_invalidate_all() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);

        // Insert multiple entries
        for i in 0..10 {
            let stream_id = StreamID::new(i).unwrap();
            let pasid = PASID::new(0).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 10);

        cache.invalidate_all();

        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
        assert_eq!(cache.statistics().get_invalidations(), 10);
    }

    #[test]
    fn test_tlb_cache_invalidate_by_stream() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);
        let target_stream = StreamID::new(5).unwrap();

        // Insert entries for different streams
        for i in 0..10 {
            let stream_id = StreamID::new(i).unwrap();
            let pasid = PASID::new(0).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 10);

        cache.invalidate_by_stream(target_stream);

        assert_eq!(cache.len(), 9);
        assert_eq!(cache.statistics().get_invalidations(), 1);

        // Verify target stream entry is gone
        let key = CacheKey::new(
            target_stream,
            PASID::new(0).unwrap(),
            IOVA::new(5 * 0x1000).unwrap(),
            SecurityState::NonSecure,
        );
        assert!(cache.lookup(&key).is_none());
    }

    #[test]
    fn test_tlb_cache_invalidate_by_pasid() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);
        let target_pasid = PASID::new(5).unwrap();

        // Insert entries for different PASIDs
        for i in 0..10 {
            let stream_id = StreamID::new(0).unwrap();
            let pasid = PASID::new(i).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 10);

        cache.invalidate_by_pasid(target_pasid);

        assert_eq!(cache.len(), 9);
        assert_eq!(cache.statistics().get_invalidations(), 1);

        // Verify target PASID entry is gone
        let key = CacheKey::new(
            StreamID::new(0).unwrap(),
            target_pasid,
            IOVA::new(5 * 0x1000).unwrap(),
            SecurityState::NonSecure,
        );
        assert!(cache.lookup(&key).is_none());
    }

    #[test]
    fn test_tlb_cache_invalidate_by_stream_pasid() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);
        let target_stream = StreamID::new(5).unwrap();
        let target_pasid = PASID::new(7).unwrap(); // Changed to 7 which is in range [0..10)

        // Insert entries for various stream/PASID combinations
        // Each stream/PASID pair gets a unique IOVA
        for i in 0..10 {
            for j in 0..10 {
                let stream_id = StreamID::new(i).unwrap();
                let pasid = PASID::new(j).unwrap();
                let iova = IOVA::new((i as u64) * 0x0010_0000 + u64::from(j) * 0x1000).unwrap();
                let pa = PA::new((i as u64) * 0x0020_0000 + u64::from(j) * 0x2000).unwrap();

                let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
                let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

                cache.insert(key, entry);
            }
        }

        assert_eq!(cache.len(), 100);

        // Check that the target entry exists before invalidation
        let target_key = CacheKey::new(
            target_stream,
            target_pasid,
            IOVA::new(5 * 0x0010_0000 + 7 * 0x1000).unwrap(),
            SecurityState::NonSecure,
        );
        assert!(cache.lookup(&target_key).is_some());

        cache.invalidate_by_stream_pasid(target_stream, target_pasid);

        assert_eq!(cache.len(), 99);

        // Verify target entry is gone
        assert!(cache.lookup(&target_key).is_none());
    }

    #[test]
    fn test_tlb_cache_invalidate_by_va_range() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();

        // Insert entries with different IOVAs
        for i in 0..10 {
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 10);

        // Invalidate range 0x2000 to 0x5000 (should remove 4 entries)
        let start = IOVA::new(0x2000).unwrap();
        let end = IOVA::new(0x5000).unwrap();

        cache.invalidate_by_va_range(stream_id, pasid, start, end);

        assert_eq!(cache.len(), 6);
        assert_eq!(cache.statistics().get_invalidations(), 4);
    }

    #[test]
    fn test_tlb_cache_invalidate_entry() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);
        assert_eq!(cache.len(), 1);

        let removed = cache.invalidate_entry(&key);
        assert!(removed);
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.statistics().get_invalidations(), 1);

        // Try to remove again - should return false
        let removed_again = cache.invalidate_entry(&key);
        assert!(!removed_again);
    }

    #[test]
    fn test_tlb_cache_statistics_hit_rate() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);

        // 3 hits, 2 misses = 60% hit rate
        cache.lookup(&key); // hit
        cache.lookup(&key); // hit
        cache.lookup(&key); // hit

        let other_key = CacheKey::new(StreamID::new(99).unwrap(), pasid, iova, SecurityState::NonSecure);
        cache.lookup(&other_key); // miss
        cache.lookup(&other_key); // miss

        let stats = cache.statistics();
        assert_eq!(stats.get_lookups(), 5);
        assert_eq!(stats.get_hits(), 3);
        assert_eq!(stats.get_misses(), 2);
        assert!((stats.hit_rate() - 60.0).abs() < 0.01);
        assert!((stats.miss_rate() - 40.0).abs() < 0.01);
    }

    #[test]
    fn test_tlb_cache_statistics_clear() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);
        cache.lookup(&key);

        assert_eq!(cache.statistics().get_insertions(), 1);
        assert_eq!(cache.statistics().get_lookups(), 1);

        cache.clear_statistics();

        assert_eq!(cache.statistics().get_insertions(), 0);
        assert_eq!(cache.statistics().get_lookups(), 0);
        assert_eq!(cache.statistics().get_hits(), 0);
        assert_eq!(cache.statistics().get_misses(), 0);

        // Cache entries should still be there
        assert_eq!(cache.len(), 1);
    }

    #[test]
    fn test_tlb_cache_replacement_policy_default() {
        let policy = ReplacementPolicy::default();
        assert_eq!(policy, ReplacementPolicy::Lru);
    }

    #[test]
    fn test_tlb_cache_concurrent_inserts() {
        use std::sync::Arc;
        use std::thread;

        let cache = Arc::new(TlbCache::new(1000, ReplacementPolicy::Lru));
        let mut handles = vec![];

        // Spawn multiple threads inserting entries
        for thread_id in 0..10 {
            let cache_clone = Arc::clone(&cache);
            let handle = thread::spawn(move || {
                for i in 0..10 {
                    let stream_id = StreamID::new(thread_id).unwrap();
                    let pasid = PASID::new(i).unwrap();
                    let iova = IOVA::new((thread_id as u64) * 0x1_0000 + (i as u64) * 0x1000).unwrap();
                    let pa = PA::new((thread_id as u64) * 0x2_0000 + (i as u64) * 0x2000).unwrap();

                    let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
                    let entry = CacheEntry::new(iova, pa, PagePermissions::read_write(), 0);

                    cache_clone.insert(key, entry);
                }
            });
            handles.push(handle);
        }

        // Wait for all threads
        for handle in handles {
            handle.join().unwrap();
        }

        assert_eq!(cache.len(), 100);
        assert_eq!(cache.statistics().get_insertions(), 100);
    }

    #[test]
    fn test_tlb_cache_concurrent_lookups() {
        use std::sync::Arc;
        use std::thread;

        let cache = Arc::new(TlbCache::new(100, ReplacementPolicy::Lru));

        // Insert some entries
        for i in 0..10 {
            let stream_id = StreamID::new(i).unwrap();
            let pasid = PASID::new(0).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        let mut handles = vec![];

        // Spawn multiple threads doing lookups
        for _thread_id in 0..10 {
            let cache_clone = Arc::clone(&cache);
            let handle = thread::spawn(move || {
                for i in 0..10 {
                    let stream_id = StreamID::new(i).unwrap();
                    let pasid = PASID::new(0).unwrap();
                    let iova = IOVA::new((i as u64) * 0x1000).unwrap();

                    let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
                    let _result = cache_clone.lookup(&key);
                }
            });
            handles.push(handle);
        }

        // Wait for all threads
        for handle in handles {
            handle.join().unwrap();
        }

        // All lookups should be hits
        assert_eq!(cache.statistics().get_lookups(), 100);
        assert_eq!(cache.statistics().get_hits(), 100);
        assert_eq!(cache.statistics().get_misses(), 0);
    }

    #[test]
    fn test_tlb_cache_security_state_isolation() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa_nonsecure = PA::new(0x2000).unwrap();
        let pa_secure = PA::new(0x3000).unwrap();

        // Insert entries with same stream/PASID/IOVA but different security states
        let key_nonsecure = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry_nonsecure = CacheEntry::new_with_security(
            iova,
            pa_nonsecure,
            PagePermissions::read_only(),
            SecurityState::NonSecure,
            0,
        );

        let key_secure = CacheKey::new(stream_id, pasid, iova, SecurityState::Secure);
        let entry_secure =
            CacheEntry::new_with_security(iova, pa_secure, PagePermissions::read_only(), SecurityState::Secure, 0);

        cache.insert(key_nonsecure, entry_nonsecure);
        cache.insert(key_secure, entry_secure);

        assert_eq!(cache.len(), 2);

        // Lookup should return correct entry for each security state
        let result_nonsecure = cache.lookup(&key_nonsecure).unwrap();
        let result_secure = cache.lookup(&key_secure).unwrap();

        assert_eq!(result_nonsecure.physical_address, pa_nonsecure);
        assert_eq!(result_secure.physical_address, pa_secure);
        assert_eq!(result_nonsecure.security_state, SecurityState::NonSecure);
        assert_eq!(result_secure.security_state, SecurityState::Secure);
    }

    #[test]
    fn test_tlb_cache_large_capacity() {
        let cache = TlbCache::new(10_000, ReplacementPolicy::Lru);

        // Insert many entries
        for i in 0..1000 {
            let stream_id = StreamID::new(i % 100).unwrap();
            let pasid = PASID::new(i % 50).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_write(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 1000);
        assert_eq!(cache.statistics().get_insertions(), 1000);
        assert_eq!(cache.statistics().get_evictions(), 0); // No evictions yet
    }

    #[test]
    fn test_tlb_cache_debug_format() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);
        let debug_str = format!("{cache:?}");

        assert!(debug_str.contains("TlbCache"));
        assert!(debug_str.contains("capacity"));
        assert!(debug_str.contains("policy"));
    }

    #[test]
    fn test_tlb_cache_empty_operations() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);

        // Operations on empty cache should not panic
        cache.invalidate_all();
        cache.invalidate_by_stream(StreamID::new(1).unwrap());
        cache.invalidate_by_pasid(PASID::new(1).unwrap());

        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_tlb_cache_permissions_preserved() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();
        let perms = PagePermissions::read_execute();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, perms, 0);

        cache.insert(key, entry);

        let result = cache.lookup(&key).unwrap();
        assert_eq!(result.permissions, perms);
        assert!(result.permissions.read());
        assert!(!result.permissions.write());
        assert!(result.permissions.execute());
    }

    #[test]
    fn test_tlb_cache_lru_timestamp_update() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);

        let entry1 = cache.lookup(&key).unwrap();
        let timestamp1 = entry1.timestamp;

        // Second lookup should update timestamp
        let entry2 = cache.lookup(&key).unwrap();
        let timestamp2 = entry2.timestamp;

        assert!(timestamp2 > timestamp1);
    }

    #[test]
    fn test_tlb_cache_fifo_no_timestamp_update() {
        let cache = TlbCache::new(10, ReplacementPolicy::Fifo);
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);

        let entry1 = cache.lookup(&key).unwrap();
        let timestamp1 = entry1.timestamp;

        // FIFO doesn't update timestamp on lookup
        let entry2 = cache.lookup(&key).unwrap();
        let timestamp2 = entry2.timestamp;

        assert_eq!(timestamp1, timestamp2);
    }

    #[test]
    fn test_tlb_cache_statistics_zero_lookups() {
        let stats = CacheStatistics::new();
        assert_eq!(stats.hit_rate(), 0.0);
        assert_eq!(stats.miss_rate(), 0.0);
    }

    #[test]
    fn test_tlb_cache_invalidate_nonexistent_stream() {
        let cache = TlbCache::new(10, ReplacementPolicy::Lru);

        // Insert an entry
        let stream_id = StreamID::new(1).unwrap();
        let pasid = PASID::new(2).unwrap();
        let iova = IOVA::new(0x1000).unwrap();
        let pa = PA::new(0x2000).unwrap();

        let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
        let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

        cache.insert(key, entry);

        // Try to invalidate different stream
        cache.invalidate_by_stream(StreamID::new(99).unwrap());

        // Original entry should still be there
        assert_eq!(cache.len(), 1);
        assert!(cache.lookup(&key).is_some());
    }

    #[test]
    fn test_tlb_cache_multiple_streams_same_pasid() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);
        let pasid = PASID::new(1).unwrap();

        // Insert entries for multiple streams with same PASID
        for i in 0..10 {
            let stream_id = StreamID::new(i).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 10);

        // Invalidate by PASID should remove all
        cache.invalidate_by_pasid(pasid);

        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_tlb_cache_same_stream_multiple_pasids() {
        let cache = TlbCache::new(100, ReplacementPolicy::Lru);
        let stream_id = StreamID::new(1).unwrap();

        // Insert entries for same stream with multiple PASIDs
        for i in 0..10 {
            let pasid = PASID::new(i).unwrap();
            let iova = IOVA::new((i as u64) * 0x1000).unwrap();
            let pa = PA::new((i as u64) * 0x2000).unwrap();

            let key = CacheKey::new(stream_id, pasid, iova, SecurityState::NonSecure);
            let entry = CacheEntry::new(iova, pa, PagePermissions::read_only(), 0);

            cache.insert(key, entry);
        }

        assert_eq!(cache.len(), 10);

        // Invalidate by stream should remove all
        cache.invalidate_by_stream(stream_id);

        assert_eq!(cache.len(), 0);
    }
}