hc
2023-05-26 a23f51ed7a39e452c1037343a84d7db1ca2c5bd7
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
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
/*************************************************************************/ /*!
@File
@Title          Common MMU Management
@Copyright      Copyright (c) Imagination Technologies Ltd. All Rights Reserved
@Description    Implements basic low level control of MMU.
@License        Dual MIT/GPLv2
 
The contents of this file are subject to the MIT license as set out below.
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 ("GPL") in which case the provisions
of GPL are applicable instead of those above.
 
If you wish to allow use of your version of this file only under the terms of
GPL, and not to allow others to use your version of this file under the terms
of the MIT license, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by GPL as set
out in the file called "GPL-COPYING" included in this distribution. If you do
not delete the provisions above, a recipient may use your version of this file
under the terms of either the MIT license or GPL.
 
This License is also included in this distribution in the file called
"MIT-COPYING".
 
EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /***************************************************************************/
 
#include "devicemem_server_utils.h"
 
/* Our own interface */
#include "mmu_common.h"
 
#include "rgx_bvnc_defs_km.h"
/*
Interfaces to other modules:
 
Let's keep this graph up-to-date:
 
   +-----------+
   | devicemem |
   +-----------+
         |
   +============+
   | mmu_common |
   +============+
         |
         +-----------------+
         |                 |
    +---------+      +----------+
    |   pmr   |      |  device  |
    +---------+      +----------+
*/
 
#include "img_types.h"
#include "osfunc.h"
#include "allocmem.h"
#if defined(PDUMP)
#include "pdump_km.h"
#include "pdump_physmem.h"
#endif
#include "pmr.h"
/* include/ */
#include "pvr_debug.h"
#include "pvr_notifier.h"
#include "pvrsrv_error.h"
#include "pvrsrv.h"
#include "htbuffer.h"
 
#include "rgxdevice.h"
 
#if defined(SUPPORT_GPUVIRT_VALIDATION)
#include "physmem_lma.h"
#endif
 
#include "dllist.h"
 
// #define MMU_OBJECT_REFCOUNT_DEBUGING 1
#if defined (MMU_OBJECT_REFCOUNT_DEBUGING)
#define MMU_OBJ_DBG(x)    PVR_DPF(x);
#else
#define MMU_OBJ_DBG(x)
#endif
 
typedef IMG_UINT32 MMU_FLAGS_T;
 
typedef enum _MMU_MOD_
{
   MMU_MOD_UNKNOWN = 0,
   MMU_MOD_MAP,
   MMU_MOD_UNMAP,
} MMU_MOD;
 
 
/*!
 * Refcounted structure that is shared between the context and
 * the cleanup thread items.
 * It is used to keep track of all cleanup items and whether the creating
 * MMU context has been destroyed and therefore is not allowed to be
 * accessed anymore.
 *
 * The cleanup thread is used to defer the freeing of the page tables
 * because we have to make sure that the MMU cache has been invalidated.
 * If we don't take care of this the MMU might partially access cached
 * and uncached tables which might lead to inconsistencies and in the
 * worst case to MMU pending faults on random memory.
 */
typedef struct _MMU_CTX_CLEANUP_DATA_
{
   /*! Refcount to know when this structure can be destroyed */
   IMG_UINT32 uiRef;
   /*! Protect items in this structure, especially the refcount */
   POS_LOCK hCleanupLock;
   /*! List of all cleanup items currently in flight */
   DLLIST_NODE sMMUCtxCleanupItemsHead;
   /*! Was the MMU context destroyed and should not be accessed anymore? */
   IMG_BOOL bMMUContextExists;
} MMU_CTX_CLEANUP_DATA;
 
 
/*!
 * Structure holding one or more page tables that need to be
 * freed after the MMU cache has been flushed which is signalled when
 * the stored sync has a value that is <= the required value.
 */
typedef struct _MMU_CLEANUP_ITEM_
{
   /*! Cleanup thread data */
   PVRSRV_CLEANUP_THREAD_WORK sCleanupThreadFn;
   /*! List to hold all the MMU_MEMORY_MAPPINGs, i.e. page tables */
   DLLIST_NODE sMMUMappingHead;
   /*! Node of the cleanup item list for the context */
   DLLIST_NODE sMMUCtxCleanupItem;
   /* Pointer to the cleanup meta data */
   MMU_CTX_CLEANUP_DATA *psMMUCtxCleanupData;
   /* Sync to query if the MMU cache was flushed */
   PVRSRV_CLIENT_SYNC_PRIM *psSync;
   /*! The update value of the sync to signal that the cache was flushed */
   IMG_UINT32 uiRequiredSyncVal;
   /*! The device node needed to free the page tables */
   PVRSRV_DEVICE_NODE *psDevNode;
} MMU_CLEANUP_ITEM;
 
/*!
   All physical allocations and frees are relative to this context, so
   we would get all the allocations of PCs, PDs, and PTs from the same
   RA.
 
   We have one per MMU context in case we have mixed UMA/LMA devices
   within the same system.
*/
typedef struct _MMU_PHYSMEM_CONTEXT_
{
   /*! Parent device node */
   PVRSRV_DEVICE_NODE *psDevNode;
 
   /*! Refcount so we know when to free up the arena */
   IMG_UINT32 uiNumAllocations;
 
   /*! Arena from which physical memory is derived */
   RA_ARENA *psPhysMemRA;
   /*! Arena name */
   IMG_CHAR *pszPhysMemRAName;
   /*! Size of arena name string */
   size_t uiPhysMemRANameAllocSize;
 
   /*! Meta data for deferred cleanup */
   MMU_CTX_CLEANUP_DATA *psCleanupData;
   /*! Temporary list of all deferred MMU_MEMORY_MAPPINGs. */
   DLLIST_NODE sTmpMMUMappingHead;
 
} MMU_PHYSMEM_CONTEXT;
 
/*!
   Mapping structure for MMU memory allocation
*/
typedef struct _MMU_MEMORY_MAPPING_
{
   /*! Physmem context to allocate from */
   MMU_PHYSMEM_CONTEXT        *psContext;
   /*! OS/system Handle for this allocation */
   PG_HANDLE                sMemHandle;
   /*! CPU virtual address of this allocation */
   void                    *pvCpuVAddr;
   /*! Device physical address of this allocation */
   IMG_DEV_PHYADDR            sDevPAddr;
   /*! Size of this allocation */
   size_t                    uiSize;
   /*! Number of current mappings of this allocation */
   IMG_UINT32                uiCpuVAddrRefCount;
   /*! Node for the defer free list */
   DLLIST_NODE                sMMUMappingItem;
} MMU_MEMORY_MAPPING;
 
/*!
   Memory descriptor for MMU objects. There can be more than one memory
   descriptor per MMU memory allocation.
*/
typedef struct _MMU_MEMORY_DESC_
{
   /* NB: bValid is set if this descriptor describes physical
      memory.  This allows "empty" descriptors to exist, such that we
      can allocate them in batches.  */
   /*! Does this MMU object have physical backing */
   IMG_BOOL                bValid;
   /*! Device Physical address of physical backing */
   IMG_DEV_PHYADDR            sDevPAddr;
   /*! CPU virtual address of physical backing */
   void                    *pvCpuVAddr;
   /*! Mapping data for this MMU object */
   MMU_MEMORY_MAPPING        *psMapping;
   /*! Memdesc offset into the psMapping */
   IMG_UINT32 uiOffset;
   /*! Size of the Memdesc */
   IMG_UINT32 uiSize;
} MMU_MEMORY_DESC;
 
/*!
   MMU levelx structure. This is generic and is used
   for all levels (PC, PD, PT).
*/
typedef struct _MMU_Levelx_INFO_
{
   /*! The Number of entries in this level */
   IMG_UINT32 ui32NumOfEntries;
 
   /*! Number of times this level has been reference. Note: For Level1 (PTE)
       we still take/drop the reference when setting up the page tables rather
       then at map/unmap time as this simplifies things */
   IMG_UINT32 ui32RefCount;
 
   /*! MemDesc for this level */
   MMU_MEMORY_DESC sMemDesc;
 
   /*! Array of infos for the next level. Must be last member in structure */
   struct _MMU_Levelx_INFO_ *apsNextLevel[1];
} MMU_Levelx_INFO;
 
/*!
   MMU context structure
*/
struct _MMU_CONTEXT_
{
   /*! Parent device node */
   PVRSRV_DEVICE_NODE *psDevNode;
 
   MMU_DEVICEATTRIBS *psDevAttrs;
 
   /*! For allocation and deallocation of the physical memory where
       the pagetables live */
   struct _MMU_PHYSMEM_CONTEXT_ *psPhysMemCtx;
 
#if defined(PDUMP)
   /*! PDump context ID (required for PDump commands with virtual addresses) */
   IMG_UINT32 uiPDumpContextID;
 
   /*! The refcount of the PDump context ID */
   IMG_UINT32 ui32PDumpContextIDRefCount;
#endif
 
   /*! Data that is passed back during device specific callbacks */
   IMG_HANDLE hDevData;
 
#if defined(SUPPORT_GPUVIRT_VALIDATION)
    IMG_UINT32  ui32OSid;
   IMG_UINT32    ui32OSidReg;
    IMG_BOOL   bOSidAxiProt;
#endif
 
   /*! Lock to ensure exclusive access when manipulating the MMU context or
    * reading and using its content
    */
   POS_LOCK hLock;
   
   /*! Base level info structure. Must be last member in structure */
   MMU_Levelx_INFO sBaseLevelInfo;
   /* NO OTHER MEMBERS AFTER THIS STRUCTURE ! */
};
 
static const IMG_DEV_PHYADDR gsBadDevPhyAddr = {MMU_BAD_PHYS_ADDR};
 
#if defined(DEBUG)
#include "log2.h"
#endif
 
 
/*****************************************************************************
 *                          Utility functions                                *
 *****************************************************************************/
 
/*************************************************************************/ /*!
@Function       _FreeMMUMapping
 
@Description    Free a given dllist of MMU_MEMORY_MAPPINGs and the page tables
                they represent.
 
@Input          psDevNode           Device node
 
@Input          psTmpMMUMappingHead List of MMU_MEMORY_MAPPINGs to free
*/
/*****************************************************************************/
static void
_FreeMMUMapping(PVRSRV_DEVICE_NODE *psDevNode,
                PDLLIST_NODE psTmpMMUMappingHead)
{
   PDLLIST_NODE psNode, psNextNode;
 
   /* Free the current list unconditionally */
   dllist_foreach_node(psTmpMMUMappingHead,
                       psNode,
                       psNextNode)
   {
       MMU_MEMORY_MAPPING *psMapping = IMG_CONTAINER_OF(psNode,
                                                        MMU_MEMORY_MAPPING,
                                                        sMMUMappingItem);
 
       psDevNode->pfnDevPxFree(psDevNode, &psMapping->sMemHandle);
       dllist_remove_node(psNode);
       OSFreeMem(psMapping);
   }
}
 
/*************************************************************************/ /*!
@Function       _CleanupThread_FreeMMUMapping
 
@Description    Function to be executed by the cleanup thread to free
                MMU_MEMORY_MAPPINGs after the MMU cache has been invalidated.
 
                This function will request a MMU cache invalidate once and
                retry to free the MMU_MEMORY_MAPPINGs until the invalidate
                has been executed.
 
                If the memory context that created this cleanup item has been
                destroyed in the meantime this function will directly free the
                MMU_MEMORY_MAPPINGs without waiting for any MMU cache
                invalidation.
 
@Input          pvData           Cleanup data in form of a MMU_CLEANUP_ITEM
 
@Return         PVRSRV_OK if successful otherwise PVRSRV_ERROR_RETRY
*/
/*****************************************************************************/
static PVRSRV_ERROR
_CleanupThread_FreeMMUMapping(void* pvData)
{
   PVRSRV_ERROR eError;
   MMU_CLEANUP_ITEM *psCleanup = (MMU_CLEANUP_ITEM *) pvData;
   MMU_CTX_CLEANUP_DATA *psMMUCtxCleanupData = psCleanup->psMMUCtxCleanupData;
   PVRSRV_DEVICE_NODE *psDevNode = psCleanup->psDevNode;
   IMG_BOOL bFreeNow;
   IMG_UINT32 uiSyncCurrent;
   IMG_UINT32 uiSyncReq;
 
   OSLockAcquire(psMMUCtxCleanupData->hCleanupLock);
 
   /* Don't attempt to free anything when the context has been destroyed.
    * Especially don't access any device specific structures anymore!*/
   if (!psMMUCtxCleanupData->bMMUContextExists)
   {
       OSFreeMem(psCleanup);
       eError = PVRSRV_OK;
       goto e0;
   }
 
   if (psCleanup->psSync == NULL)
   {
       /* Kick to invalidate the MMU caches and get sync info */
       psDevNode->pfnMMUCacheInvalidateKick(psDevNode,
                                            &psCleanup->uiRequiredSyncVal,
                                            IMG_TRUE);
       psCleanup->psSync = psDevNode->psMMUCacheSyncPrim;
   }
 
   uiSyncCurrent = *(psCleanup->psSync->pui32LinAddr);
   uiSyncReq = psCleanup->uiRequiredSyncVal;
 
   /* Either the invalidate has been executed ... */
   bFreeNow = (uiSyncCurrent >= uiSyncReq) ? IMG_TRUE :
           /* ... with the counter wrapped around ... */
           (uiSyncReq - uiSyncCurrent) > 0xEFFFFFFFUL ? IMG_TRUE :
           /* ... or are we still waiting for the invalidate? */
           IMG_FALSE;
 
#if defined(NO_HARDWARE)
   /* In NOHW the syncs will never be updated so just free the tables */
   bFreeNow = IMG_TRUE;
#endif
 
   if (bFreeNow)
   {
       _FreeMMUMapping(psDevNode, &psCleanup->sMMUMappingHead);
 
       dllist_remove_node(&psCleanup->sMMUCtxCleanupItem);
       OSFreeMem(psCleanup);
 
       eError = PVRSRV_OK;
   }
   else
   {
       eError = PVRSRV_ERROR_RETRY;
   }
 
e0:
 
   /* If this cleanup task has been successfully executed we can
    * decrease the context cleanup data refcount. Successfully
    * means here that the MMU_MEMORY_MAPPINGs have been freed by
    * either this cleanup task of when the MMU context has been
    * destroyed. */
   if (eError == PVRSRV_OK)
   {
       IMG_UINT32 uiRef;
 
       uiRef = --psMMUCtxCleanupData->uiRef;
       OSLockRelease(psMMUCtxCleanupData->hCleanupLock);
 
       if (uiRef == 0)
       {
           OSLockDestroy(psMMUCtxCleanupData->hCleanupLock);
           OSFreeMem(psMMUCtxCleanupData);
       }
   }
   else
   {
       OSLockRelease(psMMUCtxCleanupData->hCleanupLock);
   }
 
 
   return eError;
}
 
/*************************************************************************/ /*!
@Function       _SetupCleanup_FreeMMUMapping
 
@Description    Setup a cleanup item for the cleanup thread that will
                kick off a MMU invalidate request and free the associated
                MMU_MEMORY_MAPPINGs when the invalidate was successful.
 
@Input          psDevNode           Device node
 
@Input          psPhysMemCtx        The current MMU physmem context
*/
/*****************************************************************************/
static void
_SetupCleanup_FreeMMUMapping(PVRSRV_DEVICE_NODE *psDevNode,
                             MMU_PHYSMEM_CONTEXT *psPhysMemCtx)
{
 
   MMU_CLEANUP_ITEM *psCleanupItem;
   MMU_CTX_CLEANUP_DATA *psCleanupData = psPhysMemCtx->psCleanupData;
 
   if (dllist_is_empty(&psPhysMemCtx->sTmpMMUMappingHead))
   {
       goto e0;
   }
 
#if !defined(SUPPORT_MMU_PENDING_FAULT_PROTECTION)
   /* If users deactivated this we immediately free the page tables */
   goto e1;
#endif
 
   /* Don't defer the freeing if we are currently unloading the driver
    * or if the sync has been destroyed */
   if (PVRSRVGetPVRSRVData()->bUnload ||
       psDevNode->psMMUCacheSyncPrim == NULL)
   {
       goto e1;
   }
 
   /* Allocate a cleanup item */
   psCleanupItem = OSAllocMem(sizeof(*psCleanupItem));
   if(!psCleanupItem)
   {
       PVR_DPF((PVR_DBG_ERROR,
                "%s: Failed to get memory for deferred page table cleanup. "
                "Freeing tables immediately",
                __FUNCTION__));
       goto e1;
   }
 
   /* Set sync to NULL to indicate we did not interact with
    * the FW yet. Kicking off an MMU cache invalidate should
    * be done in the cleanup thread to not waste time here. */
   psCleanupItem->psSync = NULL;
   psCleanupItem->uiRequiredSyncVal = 0;
   psCleanupItem->psDevNode = psDevNode;
   psCleanupItem->psMMUCtxCleanupData = psCleanupData;
 
   OSLockAcquire(psCleanupData->hCleanupLock);
 
   psCleanupData->uiRef++;
 
   /* Move the page tables to free to the cleanup item */
   dllist_replace_head(&psPhysMemCtx->sTmpMMUMappingHead,
                       &psCleanupItem->sMMUMappingHead);
 
   /* Add the cleanup item itself to the context list */
   dllist_add_to_tail(&psCleanupData->sMMUCtxCleanupItemsHead,
                      &psCleanupItem->sMMUCtxCleanupItem);
 
   OSLockRelease(psCleanupData->hCleanupLock);
 
   /* Setup the cleanup thread data and add the work item */
   psCleanupItem->sCleanupThreadFn.pfnFree = _CleanupThread_FreeMMUMapping;
   psCleanupItem->sCleanupThreadFn.pvData = psCleanupItem;
   psCleanupItem->sCleanupThreadFn.ui32RetryCount = CLEANUP_THREAD_RETRY_COUNT_DEFAULT;
   psCleanupItem->sCleanupThreadFn.bDependsOnHW = IMG_TRUE;
 
   PVRSRVCleanupThreadAddWork(&psCleanupItem->sCleanupThreadFn);
 
   return;
 
e1:
   /* Free the page tables now */
   _FreeMMUMapping(psDevNode, &psPhysMemCtx->sTmpMMUMappingHead);
e0:
   return;
}
 
/*************************************************************************/ /*!
@Function       _CalcPCEIdx
 
@Description    Calculate the page catalogue index
 
@Input          sDevVAddr           Device virtual address
 
@Input          psDevVAddrConfig    Configuration of the virtual address
 
@Input          bRoundUp            Round up the index
 
@Return         The page catalogue index
*/
/*****************************************************************************/
static IMG_UINT32 _CalcPCEIdx(IMG_DEV_VIRTADDR sDevVAddr,
                              const MMU_DEVVADDR_CONFIG *psDevVAddrConfig,
                              IMG_BOOL bRoundUp)
{
   IMG_DEV_VIRTADDR sTmpDevVAddr;
    IMG_UINT32 ui32RetVal;
 
    sTmpDevVAddr = sDevVAddr;
 
   if (bRoundUp)
   {
        sTmpDevVAddr.uiAddr --;
    }
    ui32RetVal = (IMG_UINT32) ((sTmpDevVAddr.uiAddr & psDevVAddrConfig->uiPCIndexMask)
        >> psDevVAddrConfig->uiPCIndexShift);
 
    if (bRoundUp)
    {
        ui32RetVal ++;
    }
 
    return ui32RetVal;
}
 
 
/*************************************************************************/ /*!
@Function       _CalcPCEIdx
 
@Description    Calculate the page directory index
 
@Input          sDevVAddr           Device virtual address
 
@Input          psDevVAddrConfig    Configuration of the virtual address
 
@Input          bRoundUp            Round up the index
 
@Return         The page directory index
*/
/*****************************************************************************/
static IMG_UINT32 _CalcPDEIdx(IMG_DEV_VIRTADDR sDevVAddr,
                              const MMU_DEVVADDR_CONFIG *psDevVAddrConfig,
                              IMG_BOOL bRoundUp)
{
   IMG_DEV_VIRTADDR sTmpDevVAddr;
    IMG_UINT32 ui32RetVal;
 
    sTmpDevVAddr = sDevVAddr;
 
   if (bRoundUp)
   {
        sTmpDevVAddr.uiAddr --;
    }
    ui32RetVal = (IMG_UINT32) ((sTmpDevVAddr.uiAddr & psDevVAddrConfig->uiPDIndexMask)
        >> psDevVAddrConfig->uiPDIndexShift);
 
    if (bRoundUp)
    {
        ui32RetVal ++;
    }
 
    return ui32RetVal;
}
 
 
/*************************************************************************/ /*!
@Function       _CalcPTEIdx
 
@Description    Calculate the page entry index
 
@Input          sDevVAddr           Device virtual address
 
@Input          psDevVAddrConfig    Configuration of the virtual address
 
@Input          bRoundUp            Round up the index
 
@Return         The page entry index
*/
/*****************************************************************************/
static IMG_UINT32 _CalcPTEIdx(IMG_DEV_VIRTADDR sDevVAddr,
                              const MMU_DEVVADDR_CONFIG *psDevVAddrConfig,
                              IMG_BOOL bRoundUp)
{
   IMG_DEV_VIRTADDR sTmpDevVAddr;
    IMG_UINT32 ui32RetVal;
 
    sTmpDevVAddr = sDevVAddr;
    sTmpDevVAddr.uiAddr -= psDevVAddrConfig->uiOffsetInBytes;
   if (bRoundUp)
   {
        sTmpDevVAddr.uiAddr --;
    }
    ui32RetVal = (IMG_UINT32) ((sTmpDevVAddr.uiAddr & psDevVAddrConfig->uiPTIndexMask)
        >> psDevVAddrConfig->uiPTIndexShift);
 
    if (bRoundUp)
    {
        ui32RetVal ++;
    }
 
    return ui32RetVal;
}
 
/*****************************************************************************
 *         MMU memory allocation/management functions (mem desc)             *
 *****************************************************************************/
 
/*************************************************************************/ /*!
@Function       _MMU_PhysMem_RAImportAlloc
 
@Description    Imports MMU Px memory into the RA. This is where the
                actual allocation of physical memory happens.
 
@Input          hArenaHandle    Handle that was passed in during the
                                creation of the RA
 
@Input          uiSize          Size of the memory to import
 
@Input          uiFlags         Flags that where passed in the allocation.
 
@Output         puiBase         The address of where to insert this import
 
@Output         puiActualSize   The actual size of the import
 
@Output         phPriv          Handle which will be passed back when
                                this import is freed
 
@Return         PVRSRV_OK if import alloc was successful
*/
/*****************************************************************************/
static PVRSRV_ERROR _MMU_PhysMem_RAImportAlloc(RA_PERARENA_HANDLE hArenaHandle,
                                           RA_LENGTH_T uiSize,
                                           RA_FLAGS_T uiFlags,
                                           const IMG_CHAR *pszAnnotation,
                                           RA_BASE_T *puiBase,
                                           RA_LENGTH_T *puiActualSize,
                                           RA_PERISPAN_HANDLE *phPriv)
{
   MMU_PHYSMEM_CONTEXT *psCtx = (MMU_PHYSMEM_CONTEXT *) hArenaHandle;
   PVRSRV_DEVICE_NODE *psDevNode = (PVRSRV_DEVICE_NODE *) psCtx->psDevNode;
   MMU_MEMORY_MAPPING *psMapping;
   PVRSRV_ERROR eError;
 
   PVR_UNREFERENCED_PARAMETER(pszAnnotation);
   PVR_UNREFERENCED_PARAMETER(uiFlags);
 
   psMapping = OSAllocMem(sizeof(MMU_MEMORY_MAPPING));
   if (psMapping == NULL)
   {
       eError = PVRSRV_ERROR_OUT_OF_MEMORY;
       goto e0;
   }
 
   eError = psDevNode->pfnDevPxAlloc(psDevNode, TRUNCATE_64BITS_TO_SIZE_T(uiSize), &psMapping->sMemHandle,
                                       &psMapping->sDevPAddr);
   if (eError != PVRSRV_OK)
   {
       goto e1;
   }
 
   psMapping->psContext = psCtx;
   psMapping->uiSize = TRUNCATE_64BITS_TO_SIZE_T(uiSize);
 
   psMapping->uiCpuVAddrRefCount = 0;
 
   *phPriv = (RA_PERISPAN_HANDLE) psMapping;
 
   /* Note: This assumes this memory never gets paged out */
   *puiBase = (RA_BASE_T)psMapping->sDevPAddr.uiAddr;
   *puiActualSize = uiSize;
 
   return PVRSRV_OK;
 
e1:
   OSFreeMem(psMapping);
e0:
   return eError;
}
 
/*************************************************************************/ /*!
@Function       _MMU_PhysMem_RAImportFree
 
@Description    Imports MMU Px memory into the RA. This is where the
                actual free of physical memory happens.
 
@Input          hArenaHandle    Handle that was passed in during the
                                creation of the RA
 
@Input          puiBase         The address of where to insert this import
 
@Output         phPriv          Private data that the import alloc provided
 
@Return         None
*/
/*****************************************************************************/
static void _MMU_PhysMem_RAImportFree(RA_PERARENA_HANDLE hArenaHandle,
                                     RA_BASE_T uiBase,
                                     RA_PERISPAN_HANDLE hPriv)
{
   MMU_MEMORY_MAPPING *psMapping = (MMU_MEMORY_MAPPING *) hPriv;
   MMU_PHYSMEM_CONTEXT *psCtx = (MMU_PHYSMEM_CONTEXT *) hArenaHandle;
 
   PVR_UNREFERENCED_PARAMETER(uiBase);
 
   /* Check we have dropped all CPU mappings */
   PVR_ASSERT(psMapping->uiCpuVAddrRefCount == 0);
 
   /* Add mapping to defer free list */
   psMapping->psContext = NULL;
   dllist_add_to_tail(&psCtx->sTmpMMUMappingHead, &psMapping->sMMUMappingItem);
}
 
/*************************************************************************/ /*!
@Function       _MMU_PhysMemAlloc
 
@Description    Allocates physical memory for MMU objects
 
@Input          psCtx           Physmem context to do the allocation from
 
@Output         psMemDesc       Allocation description
 
@Input          uiBytes         Size of the allocation in bytes
 
@Input          uiAlignment     Alignment requirement of this allocation
 
@Return         PVRSRV_OK if allocation was successful
*/
/*****************************************************************************/
 
static PVRSRV_ERROR _MMU_PhysMemAlloc(MMU_PHYSMEM_CONTEXT *psCtx,
                                      MMU_MEMORY_DESC *psMemDesc,
                                      size_t uiBytes,
                                      size_t uiAlignment)
{
   PVRSRV_ERROR eError;
   RA_BASE_T uiPhysAddr;
 
   if (!psMemDesc || psMemDesc->bValid)
   {
       return PVRSRV_ERROR_INVALID_PARAMS;
   }
 
   eError = RA_Alloc(psCtx->psPhysMemRA,
                     uiBytes,
                     RA_NO_IMPORT_MULTIPLIER,
                     0, // flags
                     uiAlignment,
                     "",
                     &uiPhysAddr,
                     NULL,
                     (RA_PERISPAN_HANDLE *) &psMemDesc->psMapping);
   if(PVRSRV_OK != eError)
   {
       PVR_DPF((PVR_DBG_ERROR, "_MMU_PhysMemAlloc: ERROR call to RA_Alloc() failed"));
       return eError;
   }
 
   psMemDesc->bValid = IMG_TRUE;
   psMemDesc->pvCpuVAddr = NULL;
   psMemDesc->sDevPAddr.uiAddr = (IMG_UINT64) uiPhysAddr;
 
   if (psMemDesc->psMapping->uiCpuVAddrRefCount == 0)
   {
       eError = psCtx->psDevNode->pfnDevPxMap(psCtx->psDevNode,
                                              &psMemDesc->psMapping->sMemHandle,
                                              psMemDesc->psMapping->uiSize,
                                              &psMemDesc->psMapping->sDevPAddr,
                                              &psMemDesc->psMapping->pvCpuVAddr);
       if (eError != PVRSRV_OK)
       {
           RA_Free(psCtx->psPhysMemRA, psMemDesc->sDevPAddr.uiAddr);
           return eError;
       }
   }
 
   psMemDesc->psMapping->uiCpuVAddrRefCount++;
   psMemDesc->pvCpuVAddr = (IMG_UINT8 *) psMemDesc->psMapping->pvCpuVAddr
                           + (psMemDesc->sDevPAddr.uiAddr - psMemDesc->psMapping->sDevPAddr.uiAddr);
   psMemDesc->uiOffset = (psMemDesc->sDevPAddr.uiAddr - psMemDesc->psMapping->sDevPAddr.uiAddr);
   psMemDesc->uiSize = uiBytes;
   PVR_ASSERT(psMemDesc->pvCpuVAddr != NULL);
 
   return PVRSRV_OK;
}
 
/*************************************************************************/ /*!
@Function       _MMU_PhysMemFree
 
@Description    Allocates physical memory for MMU objects
 
@Input          psCtx           Physmem context to do the free on
 
@Input          psMemDesc       Allocation description
 
@Return         None
*/
/*****************************************************************************/
static void _MMU_PhysMemFree(MMU_PHYSMEM_CONTEXT *psCtx,
                            MMU_MEMORY_DESC *psMemDesc)
{
   RA_BASE_T uiPhysAddr;
 
   PVR_ASSERT(psMemDesc->bValid);
 
   if (--psMemDesc->psMapping->uiCpuVAddrRefCount == 0)
   {
       psCtx->psDevNode->pfnDevPxUnMap(psCtx->psDevNode, &psMemDesc->psMapping->sMemHandle,
                               psMemDesc->psMapping->pvCpuVAddr);
   }
 
   psMemDesc->pvCpuVAddr = NULL;
 
   uiPhysAddr = psMemDesc->sDevPAddr.uiAddr;
   RA_Free(psCtx->psPhysMemRA, uiPhysAddr);
 
   psMemDesc->bValid = IMG_FALSE;
}
 
 
/*****************************************************************************
 *              MMU object allocation/management functions                   *
 *****************************************************************************/
 
static INLINE void _MMU_ConvertDevMemFlags(IMG_BOOL bInvalidate,
                                           PVRSRV_MEMALLOCFLAGS_T uiMappingFlags,
                                           MMU_PROTFLAGS_T *uiMMUProtFlags,
                                           MMU_CONTEXT *psMMUContext)
{
   /* Do flag conversion between devmem flags and MMU generic flags */
   if (bInvalidate == IMG_FALSE)
   {
       *uiMMUProtFlags |= ( (uiMappingFlags & PVRSRV_MEMALLOCFLAG_DEVICE_FLAGS_MASK)
                           >> PVRSRV_MEMALLOCFLAG_DEVICE_FLAGS_OFFSET)
                           << MMU_PROTFLAGS_DEVICE_OFFSET;
 
       if (PVRSRV_CHECK_GPU_READABLE(uiMappingFlags))
       {
           *uiMMUProtFlags |= MMU_PROTFLAGS_READABLE;
       }
       if (PVRSRV_CHECK_GPU_WRITEABLE(uiMappingFlags))
       {
           *uiMMUProtFlags |= MMU_PROTFLAGS_WRITEABLE;
       }
 
       switch (DevmemDeviceCacheMode(psMMUContext->psDevNode, uiMappingFlags))
       {
           case PVRSRV_MEMALLOCFLAG_GPU_UNCACHED:
           case PVRSRV_MEMALLOCFLAG_GPU_WRITE_COMBINE:
                   break;
           case PVRSRV_MEMALLOCFLAG_GPU_CACHED:
                   *uiMMUProtFlags |= MMU_PROTFLAGS_CACHED;
                   break;
           default:
                   PVR_DPF((PVR_DBG_ERROR,"_MMU_DerivePTProtFlags: Wrong parameters"));
                   return;
       }
 
       if (DevmemDeviceCacheCoherency(psMMUContext->psDevNode, uiMappingFlags))
       {
           *uiMMUProtFlags |= MMU_PROTFLAGS_CACHE_COHERENT;
       }
 
       if( (psMMUContext->psDevNode->pfnCheckDeviceFeature) && \
               psMMUContext->psDevNode->pfnCheckDeviceFeature(psMMUContext->psDevNode, RGX_FEATURE_MIPS_BIT_MASK))
       {
           /*
               If we are allocating on the MMU of the firmware processor, the cached/uncached attributes
               must depend on the FIRMWARE_CACHED allocation flag.
            */
           if (psMMUContext->psDevAttrs == psMMUContext->psDevNode->psFirmwareMMUDevAttrs)
           {
               if (uiMappingFlags & PVRSRV_MEMALLOCFLAG_DEVICE_FLAG(FIRMWARE_CACHED))
               {
                   *uiMMUProtFlags |= MMU_PROTFLAGS_CACHED;
               }
               else
               {
                   *uiMMUProtFlags &= ~MMU_PROTFLAGS_CACHED;
 
               }
               *uiMMUProtFlags &= ~MMU_PROTFLAGS_CACHE_COHERENT;
           }
       }
   }
   else
   {
       *uiMMUProtFlags |= MMU_PROTFLAGS_INVALID;
   }
}
 
/*************************************************************************/ /*!
@Function       _PxMemAlloc
 
@Description    Allocates physical memory for MMU objects, initialises
                and PDumps it.
 
@Input          psMMUContext    MMU context
 
@Input          uiNumEntries    Number of entries to allocate
 
@Input          psConfig        MMU Px config
 
@Input          eMMULevel       MMU level that that allocation is for
 
@Output         psMemDesc       Description of allocation
 
@Return         PVRSRV_OK if allocation was successful
*/
/*****************************************************************************/
static PVRSRV_ERROR _PxMemAlloc(MMU_CONTEXT *psMMUContext,
                               IMG_UINT32 uiNumEntries,
                               const MMU_PxE_CONFIG *psConfig,
                               MMU_LEVEL eMMULevel,
                               MMU_MEMORY_DESC *psMemDesc,
                               IMG_UINT32 uiLog2Align)
{
   PVRSRV_ERROR eError;
   size_t uiBytes;
   size_t uiAlign;
 
   PVR_ASSERT(psConfig->uiBytesPerEntry != 0);
 
   uiBytes = uiNumEntries * psConfig->uiBytesPerEntry;
   /* We need here the alignment of the previous level because that is the entry for we generate here */
   uiAlign = 1 << uiLog2Align;
 
   /*  allocate the object */
   eError = _MMU_PhysMemAlloc(psMMUContext->psPhysMemCtx,
                               psMemDesc, uiBytes, uiAlign);
   if(eError != PVRSRV_OK)
   {
       PVR_DPF((PVR_DBG_ERROR, "_PxMemAlloc: failed to allocate memory for the  MMU object"));
       eError = PVRSRV_ERROR_OUT_OF_MEMORY;
       goto e0;
   }
 
   /*
       Clear the object
       Note: if any MMUs are cleared with non-zero values then will need a
       custom clear function
       Note: 'Cached' is wrong for the LMA + ARM64 combination, but this is
       unlikely
   */
   OSCachedMemSet(psMemDesc->pvCpuVAddr, 0, uiBytes);
 
   eError = psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                                   &psMemDesc->psMapping->sMemHandle,
                                                   psMemDesc->uiOffset,
                                                   psMemDesc->uiSize);
   if(eError != PVRSRV_OK)
   {
       goto e1;
   }
 
#if defined(PDUMP)
   PDUMPCOMMENT("Alloc MMU object");
 
   PDumpMMUMalloc(psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName,
                  eMMULevel,
                  &psMemDesc->sDevPAddr,
                  uiBytes,
                  uiAlign,
                  psMMUContext->psDevAttrs->eMMUType);
 
   PDumpMMUDumpPxEntries(eMMULevel,
                         psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName,
                         psMemDesc->pvCpuVAddr,
                         psMemDesc->sDevPAddr,
                         0,
                         uiNumEntries,
                         NULL, NULL, 0, /* pdump symbolic info is irrelevant here */
                         psConfig->uiBytesPerEntry,
                         uiLog2Align,
                         psConfig->uiAddrShift,
                         psConfig->uiAddrMask,
                         psConfig->uiProtMask,
                         psConfig->uiValidEnMask,
                         0,
                         psMMUContext->psDevAttrs->eMMUType);
#endif
 
   return PVRSRV_OK;
e1:
   _MMU_PhysMemFree(psMMUContext->psPhysMemCtx,
                    psMemDesc);
e0:
   PVR_ASSERT(eError != PVRSRV_OK);
   return eError;
}
 
/*************************************************************************/ /*!
@Function       _PxMemFree
 
@Description    Frees physical memory for MMU objects, de-initialises
                and PDumps it.
 
@Input          psMemDesc       Description of allocation
 
@Return         PVRSRV_OK if allocation was successful
*/
/*****************************************************************************/
 
static void _PxMemFree(MMU_CONTEXT *psMMUContext,
                      MMU_MEMORY_DESC *psMemDesc, MMU_LEVEL eMMULevel)
{
#if defined(MMU_CLEARMEM_ON_FREE)
   PVRSRV_ERROR eError;
 
   /*
       Clear the MMU object
       Note: if any MMUs are cleared with non-zero values then will need a
       custom clear function
       Note: 'Cached' is wrong for the LMA + ARM64 combination, but this is
       unlikely
   */
   OSCachedMemSet(psMemDesc->pvCpuVAddr, 0, psMemDesc->ui32Bytes);
 
#if defined(PDUMP)
   PDUMPCOMMENT("Clear MMU object before freeing it");
#endif
#endif/* MMU_CLEARMEM_ON_FREE */
 
#if defined(PDUMP)
   PDUMPCOMMENT("Free MMU object");
   {
       PDumpMMUFree(psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName,
                    eMMULevel,
                    &psMemDesc->sDevPAddr,
                    psMMUContext->psDevAttrs->eMMUType);
   }
#else
   PVR_UNREFERENCED_PARAMETER(eMMULevel);
#endif
   /*  free the PC */
   _MMU_PhysMemFree(psMMUContext->psPhysMemCtx, psMemDesc);
}
 
static INLINE PVRSRV_ERROR _SetupPTE(MMU_CONTEXT *psMMUContext,
                              MMU_Levelx_INFO *psLevel,
                              IMG_UINT32 uiIndex,
                              const MMU_PxE_CONFIG *psConfig,
                              const IMG_DEV_PHYADDR *psDevPAddr,
                              IMG_BOOL bUnmap,
#if defined(PDUMP)
                              const IMG_CHAR *pszMemspaceName,
                              const IMG_CHAR *pszSymbolicAddr,
                              IMG_DEVMEM_OFFSET_T uiSymbolicAddrOffset,
#endif
                              IMG_UINT64 uiProtFlags)
{
   MMU_MEMORY_DESC *psMemDesc = &psLevel->sMemDesc;
   IMG_UINT64 ui64PxE64;
   IMG_UINT64 uiAddr = psDevPAddr->uiAddr;
 
   if(psMMUContext->psDevNode->pfnCheckDeviceFeature(psMMUContext->psDevNode, \
           RGX_FEATURE_MIPS_BIT_MASK))
   {
       /*
        * If mapping for the MIPS FW context, check for sensitive PAs
        */
       if (psMMUContext->psDevAttrs == psMMUContext->psDevNode->psFirmwareMMUDevAttrs
           && RGXMIPSFW_SENSITIVE_ADDR(uiAddr))
       {
           PVRSRV_RGXDEV_INFO *psDevice = (PVRSRV_RGXDEV_INFO *)psMMUContext->psDevNode->pvDevice;
 
           uiAddr = psDevice->sTrampoline.sPhysAddr.uiAddr + RGXMIPSFW_TRAMPOLINE_OFFSET(uiAddr);
       }
   }
 
   /* Calculate Entry */
   ui64PxE64 =    uiAddr /* Calculate the offset to that base */
               >> psConfig->uiAddrLog2Align /* Shift away the useless bits, because the alignment is very coarse and we address by alignment */
               << psConfig->uiAddrShift /* Shift back to fit address in the Px entry */
                & psConfig->uiAddrMask; /* Delete unused bits */
   ui64PxE64 |= uiProtFlags;
 
   /* Set the entry */
   if (psConfig->uiBytesPerEntry == 8)
   {
       IMG_UINT64 *pui64Px = psMemDesc->pvCpuVAddr; /* Give the virtual base address of Px */
 
       pui64Px[uiIndex] = ui64PxE64;
   }
   else if (psConfig->uiBytesPerEntry == 4)
   {
       IMG_UINT32 *pui32Px = psMemDesc->pvCpuVAddr; /* Give the virtual base address of Px */
 
       /* assert that the result fits into 32 bits before writing
          it into the 32-bit array with a cast */
       PVR_ASSERT(ui64PxE64 == (ui64PxE64 & 0xffffffffU));
 
       pui32Px[uiIndex] = (IMG_UINT32) ui64PxE64;
   }
   else
   {
       return PVRSRV_ERROR_MMU_CONFIG_IS_WRONG;
   }
 
 
   /* Log modification */
   HTBLOGK(HTB_SF_MMU_PAGE_OP_TABLE,
       HTBLOG_PTR_BITS_HIGH(psLevel), HTBLOG_PTR_BITS_LOW(psLevel),
       uiIndex, MMU_LEVEL_1,
       HTBLOG_U64_BITS_HIGH(ui64PxE64), HTBLOG_U64_BITS_LOW(ui64PxE64),
       !bUnmap);
 
#if defined (PDUMP)
   PDumpMMUDumpPxEntries(MMU_LEVEL_1,
                         psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName,
                         psMemDesc->pvCpuVAddr,
                         psMemDesc->sDevPAddr,
                         uiIndex,
                         1,
                         pszMemspaceName,
                         pszSymbolicAddr,
                         uiSymbolicAddrOffset,
                         psConfig->uiBytesPerEntry,
                         psConfig->uiAddrLog2Align,
                         psConfig->uiAddrShift,
                         psConfig->uiAddrMask,
                         psConfig->uiProtMask,
                         psConfig->uiValidEnMask,
                         0,
                         psMMUContext->psDevAttrs->eMMUType);
#endif /*PDUMP*/
 
   return PVRSRV_OK;
}
 
/*************************************************************************/ /*!
@Function       _SetupPxE
 
@Description    Sets up an entry of an MMU object to point to the
                provided address
 
@Input          psMMUContext    MMU context to operate on
 
@Input          psLevel         Level info for MMU object
 
@Input          uiIndex         Index into the MMU object to setup
 
@Input          psConfig        MMU Px config
 
@Input          eMMULevel       Level of MMU object
 
@Input          psDevPAddr      Address to setup the MMU object to point to
 
@Input          pszMemspaceName Name of the PDump memory space that the entry
                                will point to
 
@Input          pszSymbolicAddr PDump symbolic address that the entry will
                                point to
 
@Input          uiProtFlags     MMU protection flags
 
@Return         PVRSRV_OK if the setup was successful
*/
/*****************************************************************************/
static PVRSRV_ERROR _SetupPxE(MMU_CONTEXT *psMMUContext,
                               MMU_Levelx_INFO *psLevel,
                               IMG_UINT32 uiIndex,
                               const MMU_PxE_CONFIG *psConfig,
                               MMU_LEVEL eMMULevel,
                               const IMG_DEV_PHYADDR *psDevPAddr,
#if defined(PDUMP)
                               const IMG_CHAR *pszMemspaceName,
                               const IMG_CHAR *pszSymbolicAddr,
                               IMG_DEVMEM_OFFSET_T uiSymbolicAddrOffset,
#endif
                               MMU_FLAGS_T uiProtFlags,
                               IMG_UINT32 uiLog2DataPageSize)
{
   PVRSRV_DEVICE_NODE *psDevNode = psMMUContext->psDevNode;
   MMU_MEMORY_DESC *psMemDesc = &psLevel->sMemDesc;
 
   IMG_UINT32 (*pfnDerivePxEProt4)(IMG_UINT32);
   IMG_UINT64 (*pfnDerivePxEProt8)(IMG_UINT32, IMG_UINT32);
 
   if (!psDevPAddr)
   {
       /* Invalidate entry */
       if (~uiProtFlags & MMU_PROTFLAGS_INVALID)
       {
           PVR_DPF((PVR_DBG_ERROR, "Error, no physical address specified, but not invalidating entry"));
           uiProtFlags |= MMU_PROTFLAGS_INVALID;
       }
       psDevPAddr = &gsBadDevPhyAddr;
   }
   else
   {
       if (uiProtFlags & MMU_PROTFLAGS_INVALID)
       {
           PVR_DPF((PVR_DBG_ERROR, "A physical address was specified when requesting invalidation of entry"));
           uiProtFlags |= MMU_PROTFLAGS_INVALID;
       }
   }
 
   switch(eMMULevel)
   {
       case MMU_LEVEL_3:
               pfnDerivePxEProt4 = psMMUContext->psDevAttrs->pfnDerivePCEProt4;
               pfnDerivePxEProt8 = psMMUContext->psDevAttrs->pfnDerivePCEProt8;
               break;
 
       case MMU_LEVEL_2:
               pfnDerivePxEProt4 = psMMUContext->psDevAttrs->pfnDerivePDEProt4;
               pfnDerivePxEProt8 = psMMUContext->psDevAttrs->pfnDerivePDEProt8;
               break;
 
       case MMU_LEVEL_1:
               pfnDerivePxEProt4 = psMMUContext->psDevAttrs->pfnDerivePTEProt4;
               pfnDerivePxEProt8 = psMMUContext->psDevAttrs->pfnDerivePTEProt8;
               break;
 
       default:
               PVR_DPF((PVR_DBG_ERROR, "%s: invalid MMU level", __func__));
               return PVRSRV_ERROR_INVALID_PARAMS;
   }
 
   /* How big is a PxE in bytes? */
   /* Filling the actual Px entry with an address */
   switch(psConfig->uiBytesPerEntry)
   {
       case 4:
       {
           IMG_UINT32 *pui32Px;
           IMG_UINT64 ui64PxE64;
 
           pui32Px = psMemDesc->pvCpuVAddr; /* Give the virtual base address of Px */
 
           ui64PxE64 = psDevPAddr->uiAddr               /* Calculate the offset to that base */
                           >> psConfig->uiAddrLog2Align /* Shift away the unnecessary bits of the address */
                           << psConfig->uiAddrShift     /* Shift back to fit address in the Px entry */
                           & psConfig->uiAddrMask;      /* Delete unused higher bits */
 
           ui64PxE64 |= (IMG_UINT64)pfnDerivePxEProt4(uiProtFlags);
           /* assert that the result fits into 32 bits before writing
              it into the 32-bit array with a cast */
           PVR_ASSERT(ui64PxE64 == (ui64PxE64 & 0xffffffffU));
 
           /* We should never invalidate an invalid page */
           if (uiProtFlags & MMU_PROTFLAGS_INVALID)
           {
               PVR_ASSERT(pui32Px[uiIndex] != ui64PxE64);
           }
           pui32Px[uiIndex] = (IMG_UINT32) ui64PxE64;
           HTBLOGK(HTB_SF_MMU_PAGE_OP_TABLE,
               HTBLOG_PTR_BITS_HIGH(psLevel), HTBLOG_PTR_BITS_LOW(psLevel),
               uiIndex, eMMULevel,
               HTBLOG_U64_BITS_HIGH(ui64PxE64), HTBLOG_U64_BITS_LOW(ui64PxE64),
               (uiProtFlags & MMU_PROTFLAGS_INVALID)? 0: 1);
           break;
       }
       case 8:
       {
           IMG_UINT64 *pui64Px = psMemDesc->pvCpuVAddr; /* Give the virtual base address of Px */
           
           pui64Px[uiIndex] = psDevPAddr->uiAddr             /* Calculate the offset to that base */
                               >> psConfig->uiAddrLog2Align  /* Shift away the unnecessary bits of the address */
                               << psConfig->uiAddrShift      /* Shift back to fit address in the Px entry */
                               & psConfig->uiAddrMask;       /* Delete unused higher bits */
           pui64Px[uiIndex] |= pfnDerivePxEProt8(uiProtFlags, uiLog2DataPageSize);
 
           HTBLOGK(HTB_SF_MMU_PAGE_OP_TABLE,
               HTBLOG_PTR_BITS_HIGH(psLevel), HTBLOG_PTR_BITS_LOW(psLevel),
               uiIndex, eMMULevel,
               HTBLOG_U64_BITS_HIGH(pui64Px[uiIndex]), HTBLOG_U64_BITS_LOW(pui64Px[uiIndex]),
               (uiProtFlags & MMU_PROTFLAGS_INVALID)? 0: 1);
           break;
       }
       default:
           PVR_DPF((PVR_DBG_ERROR, "%s: PxE size not supported (%d) for level %d",
                                   __func__, psConfig->uiBytesPerEntry, eMMULevel));
 
           return PVRSRV_ERROR_MMU_CONFIG_IS_WRONG;
   }
 
#if defined (PDUMP)
   PDumpMMUDumpPxEntries(eMMULevel,
                         psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName,
                         psMemDesc->pvCpuVAddr,
                         psMemDesc->sDevPAddr,
                         uiIndex,
                         1,
                         pszMemspaceName,
                         pszSymbolicAddr,
                         uiSymbolicAddrOffset,
                         psConfig->uiBytesPerEntry,
                         psConfig->uiAddrLog2Align,
                         psConfig->uiAddrShift,
                         psConfig->uiAddrMask,
                         psConfig->uiProtMask,
                         psConfig->uiValidEnMask,
                         0,
                         psMMUContext->psDevAttrs->eMMUType);
#endif
 
   psDevNode->pfnMMUCacheInvalidate(psDevNode, psMMUContext->hDevData,
                                    eMMULevel,
                                    (uiProtFlags & MMU_PROTFLAGS_INVALID)?IMG_TRUE:IMG_FALSE);
   
   return PVRSRV_OK;
}
 
/*****************************************************************************
 *                   MMU host control functions (Level Info)                 *
 *****************************************************************************/
 
 
/*************************************************************************/ /*!
@Function       _MMU_FreeLevel
 
@Description    Recursively frees the specified range of Px entries. If any
                level has its last reference dropped then the MMU object
                memory and the MMU_Levelx_Info will be freed.
 
               At each level we might be crossing a boundary from one Px to
               another. The values for auiStartArray should be by used for
               the first call into each level and the values in auiEndArray
               should only be used in the last call for each level.
               In order to determine if this is the first/last call we pass
               in bFirst and bLast.
               When one level calls down to the next only if bFirst/bLast is set
               and it's the first/last iteration of the loop at its level will
               bFirst/bLast set for the next recursion.
               This means that each iteration has the knowledge of the previous
               level which is required.
 
@Input          psMMUContext    MMU context to operate on
 
@Input          psLevel                 Level info on which to free the
                                        specified range
 
@Input          auiStartArray           Array of start indexes (one for each level)
 
@Input          auiEndArray             Array of end indexes (one for each level)
 
@Input          auiEntriesPerPxArray    Array of number of entries for the Px
                                        (one for each level)
 
@Input          apsConfig               Array of PxE configs (one for each level)
 
@Input          aeMMULevel              Array of MMU levels (one for each level)
 
@Input          pui32CurrentLevel       Pointer to a variable which is set to our
                                        current level
 
@Input          uiStartIndex            Start index of the range to free
 
@Input          uiEndIndex              End index of the range to free
 
@Input            bFirst                  This is the first call for this level
 
@Input            bLast                   This is the last call for this level
 
@Return         IMG_TRUE if the last reference to psLevel was dropped
*/
/*****************************************************************************/
static IMG_BOOL _MMU_FreeLevel(MMU_CONTEXT *psMMUContext,
                              MMU_Levelx_INFO *psLevel,
                              IMG_UINT32 auiStartArray[],
                              IMG_UINT32 auiEndArray[],
                              IMG_UINT32 auiEntriesPerPxArray[],
                              const MMU_PxE_CONFIG *apsConfig[],
                              MMU_LEVEL aeMMULevel[],
                              IMG_UINT32 *pui32CurrentLevel,
                              IMG_UINT32 uiStartIndex,
                              IMG_UINT32 uiEndIndex,
                              IMG_BOOL bFirst,
                              IMG_BOOL bLast,
                              IMG_UINT32 uiLog2DataPageSize)
{
   IMG_UINT32 uiThisLevel = *pui32CurrentLevel;
   const MMU_PxE_CONFIG *psConfig = apsConfig[uiThisLevel];
   IMG_UINT32 i;
   IMG_BOOL bFreed = IMG_FALSE;
 
   /* Sanity check */
   PVR_ASSERT(*pui32CurrentLevel < MMU_MAX_LEVEL);
   PVR_ASSERT(psLevel != NULL);
 
   MMU_OBJ_DBG((PVR_DBG_ERROR, "_MMU_FreeLevel: level = %d, range %d - %d, refcount = %d",
               aeMMULevel[uiThisLevel], uiStartIndex,
               uiEndIndex, psLevel->ui32RefCount));
 
   for (i = uiStartIndex;(i < uiEndIndex) && (psLevel != NULL);i++)
   {
       if (aeMMULevel[uiThisLevel] != MMU_LEVEL_1)
       {
           MMU_Levelx_INFO *psNextLevel = psLevel->apsNextLevel[i];
           IMG_UINT32 uiNextStartIndex;
           IMG_UINT32 uiNextEndIndex;
           IMG_BOOL bNextFirst;
           IMG_BOOL bNextLast;
 
           /* If we're crossing a Px then the start index changes */
           if (bFirst && (i == uiStartIndex))
           {
               uiNextStartIndex = auiStartArray[uiThisLevel + 1];
               bNextFirst = IMG_TRUE;
           }
           else
           {
               uiNextStartIndex = 0;
               bNextFirst = IMG_FALSE;
           }
 
           /* If we're crossing a Px then the end index changes */
           if (bLast && (i == (uiEndIndex - 1)))
           {
               uiNextEndIndex = auiEndArray[uiThisLevel + 1];
               bNextLast = IMG_TRUE;
           }
           else
           {
               uiNextEndIndex = auiEntriesPerPxArray[uiThisLevel + 1];
               bNextLast = IMG_FALSE;
           }
 
           /* Recurse into the next level */
           (*pui32CurrentLevel)++;
           if (_MMU_FreeLevel(psMMUContext, psNextLevel, auiStartArray,
                               auiEndArray, auiEntriesPerPxArray,
                               apsConfig, aeMMULevel, pui32CurrentLevel,
                               uiNextStartIndex, uiNextEndIndex,
                               bNextFirst, bNextLast, uiLog2DataPageSize))
           {
               PVRSRV_ERROR eError;
 
               /* Un-wire the entry */
               eError = _SetupPxE(psMMUContext,
                               psLevel,
                               i,
                               psConfig,
                               aeMMULevel[uiThisLevel],
                               NULL,
#if defined(PDUMP)
                               NULL,    /* Only required for data page */
                               NULL,    /* Only required for data page */
                               0,      /* Only required for data page */
#endif
                               MMU_PROTFLAGS_INVALID,
                               uiLog2DataPageSize);
 
               PVR_ASSERT(eError == PVRSRV_OK);
 
               /* Free table of the level below, pointed to by this table entry.
                * We don't destroy the table inside the above _MMU_FreeLevel call because we
                * first have to set the table entry of the level above to invalid. */
               _PxMemFree(psMMUContext, &psNextLevel->sMemDesc, aeMMULevel[*pui32CurrentLevel]);
               OSFreeMem(psNextLevel);
 
               /* The level below us is empty, drop the refcount and clear the pointer */
               psLevel->ui32RefCount--;
               psLevel->apsNextLevel[i] = NULL;
 
               /* Check we haven't wrapped around */
               PVR_ASSERT(psLevel->ui32RefCount <= psLevel->ui32NumOfEntries);
           }
           (*pui32CurrentLevel)--;
       }
       else
       {
           psLevel->ui32RefCount--;
       }
 
       /*
          Free this level if it is no longer referenced, unless it's the base
          level in which case it's part of the MMU context and should be freed
          when the MMU context is freed
       */
       if ((psLevel->ui32RefCount == 0) && (psLevel != &psMMUContext->sBaseLevelInfo))
       {
           bFreed = IMG_TRUE;
       }
   }
 
   /* Level one flushing is done when we actually write the table entries */
   if (aeMMULevel[uiThisLevel] != MMU_LEVEL_1)
   {
       psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                              &psLevel->sMemDesc.psMapping->sMemHandle,
                                              uiStartIndex * psConfig->uiBytesPerEntry + psLevel->sMemDesc.uiOffset,
                                              (uiEndIndex - uiStartIndex) * psConfig->uiBytesPerEntry);
   }
 
   MMU_OBJ_DBG((PVR_DBG_ERROR, "_MMU_FreeLevel end: level = %d, refcount = %d",
               aeMMULevel[uiThisLevel], bFreed?0:psLevel->ui32RefCount));
 
   return bFreed;
}
 
/*************************************************************************/ /*!
@Function       _MMU_AllocLevel
 
@Description    Recursively allocates the specified range of Px entries. If any
                level has its last reference dropped then the MMU object
                memory and the MMU_Levelx_Info will be freed.
 
               At each level we might be crossing a boundary from one Px to
               another. The values for auiStartArray should be by used for
               the first call into each level and the values in auiEndArray
               should only be used in the last call for each level.
               In order to determine if this is the first/last call we pass
               in bFirst and bLast.
               When one level calls down to the next only if bFirst/bLast is set
               and it's the first/last iteration of the loop at its level will
               bFirst/bLast set for the next recursion.
               This means that each iteration has the knowledge of the previous
               level which is required.
 
@Input          psMMUContext    MMU context to operate on
 
@Input          psLevel                 Level info on which to to free the
                                        specified range
 
@Input          auiStartArray           Array of start indexes (one for each level)
 
@Input          auiEndArray             Array of end indexes (one for each level)
 
@Input          auiEntriesPerPxArray    Array of number of entries for the Px
                                        (one for each level)
 
@Input          apsConfig               Array of PxE configs (one for each level)
 
@Input          aeMMULevel              Array of MMU levels (one for each level)
 
@Input          pui32CurrentLevel       Pointer to a variable which is set to our
                                        current level
 
@Input          uiStartIndex            Start index of the range to free
 
@Input          uiEndIndex              End index of the range to free
 
@Input            bFirst                  This is the first call for this level
 
@Input            bLast                   This is the last call for this level
 
@Return         IMG_TRUE if the last reference to psLevel was dropped
*/
/*****************************************************************************/
static PVRSRV_ERROR _MMU_AllocLevel(MMU_CONTEXT *psMMUContext,
                                   MMU_Levelx_INFO *psLevel,
                                   IMG_UINT32 auiStartArray[],
                                   IMG_UINT32 auiEndArray[],
                                   IMG_UINT32 auiEntriesPerPxArray[],
                                   const MMU_PxE_CONFIG *apsConfig[],
                                   MMU_LEVEL aeMMULevel[],
                                   IMG_UINT32 *pui32CurrentLevel,
                                   IMG_UINT32 uiStartIndex,
                                   IMG_UINT32 uiEndIndex,
                                   IMG_BOOL bFirst,
                                   IMG_BOOL bLast,
                                   IMG_UINT32 uiLog2DataPageSize)
{
   IMG_UINT32 uiThisLevel = *pui32CurrentLevel; /* Starting with 0 */
   const MMU_PxE_CONFIG *psConfig = apsConfig[uiThisLevel]; /* The table config for the current level */
   PVRSRV_ERROR eError = PVRSRV_ERROR_OUT_OF_MEMORY;
   IMG_UINT32 uiAllocState = 99; /* Debug info to check what progress was made in the function. Updated during this function. */
   IMG_UINT32 i;
 
   /* Sanity check */
   PVR_ASSERT(*pui32CurrentLevel < MMU_MAX_LEVEL);
 
   MMU_OBJ_DBG((PVR_DBG_ERROR, "_MMU_AllocLevel: level = %d, range %d - %d, refcount = %d",
               aeMMULevel[uiThisLevel], uiStartIndex,
               uiEndIndex, psLevel->ui32RefCount));
 
   /* Go from uiStartIndex to uiEndIndex through the Px */
   for (i = uiStartIndex;i < uiEndIndex;i++)
   {
       /* Only try an allocation if this is not the last level */
       /*Because a PT allocation is already done while setting the entry in PD */
       if (aeMMULevel[uiThisLevel] != MMU_LEVEL_1)
       {
           IMG_UINT32 uiNextStartIndex;
           IMG_UINT32 uiNextEndIndex;
           IMG_BOOL bNextFirst;
           IMG_BOOL bNextLast;
 
           /* If there is already a next Px level existing, do not allocate it */
           if (!psLevel->apsNextLevel[i])
           {
               MMU_Levelx_INFO *psNextLevel;
               IMG_UINT32 ui32AllocSize;
               IMG_UINT32 uiNextEntries;
 
               /* Allocate and setup the next level */
               uiNextEntries = auiEntriesPerPxArray[uiThisLevel + 1];
               ui32AllocSize = sizeof(MMU_Levelx_INFO);
               if (aeMMULevel[uiThisLevel + 1] != MMU_LEVEL_1)
               {
                   ui32AllocSize += sizeof(MMU_Levelx_INFO *) * (uiNextEntries - 1);
               }
               psNextLevel = OSAllocZMem(ui32AllocSize);
               if (psNextLevel == NULL)
               {
                   uiAllocState = 0;
                   goto e0;
               }
 
               /* Hook in this level for next time */
               psLevel->apsNextLevel[i] = psNextLevel;
 
               psNextLevel->ui32NumOfEntries = uiNextEntries;
               psNextLevel->ui32RefCount = 0;
               /* Allocate Px memory for a sub level*/
               eError = _PxMemAlloc(psMMUContext, uiNextEntries, apsConfig[uiThisLevel + 1],
                                       aeMMULevel[uiThisLevel + 1],
                                       &psNextLevel->sMemDesc,
                                       psConfig->uiAddrLog2Align);
               if (eError != PVRSRV_OK)
               {
                   uiAllocState = 1;
                   goto e0;
               }
 
               /* Wire up the entry */
               eError = _SetupPxE(psMMUContext,
                                   psLevel,
                                   i,
                                   psConfig,
                                   aeMMULevel[uiThisLevel],
                                   &psNextLevel->sMemDesc.sDevPAddr,
#if defined(PDUMP)
                                   NULL, /* Only required for data page */
                                   NULL, /* Only required for data page */
                                   0,    /* Only required for data page */
#endif
                                   0,
                                   uiLog2DataPageSize);
 
               if (eError != PVRSRV_OK)
               {
                   uiAllocState = 2;
                   goto e0;
               }
 
               psLevel->ui32RefCount++;
           }
 
           /* If we're crossing a Px then the start index changes */
           if (bFirst && (i == uiStartIndex))
           {
               uiNextStartIndex = auiStartArray[uiThisLevel + 1];
               bNextFirst = IMG_TRUE;
           }
           else
           {
               uiNextStartIndex = 0;
               bNextFirst = IMG_FALSE;
           }
 
           /* If we're crossing a Px then the end index changes */
           if (bLast && (i == (uiEndIndex - 1)))
           {
               uiNextEndIndex = auiEndArray[uiThisLevel + 1];
               bNextLast = IMG_TRUE;
           }
           else
           {
               uiNextEndIndex = auiEntriesPerPxArray[uiThisLevel + 1];
               bNextLast = IMG_FALSE;
           }
 
           /* Recurse into the next level */
           (*pui32CurrentLevel)++;
           eError = _MMU_AllocLevel(psMMUContext, psLevel->apsNextLevel[i],
                                    auiStartArray,
                                    auiEndArray,
                                    auiEntriesPerPxArray,
                                    apsConfig,
                                    aeMMULevel,
                                    pui32CurrentLevel,
                                    uiNextStartIndex,
                                    uiNextEndIndex,
                                    bNextFirst,
                                    bNextLast,
                                    uiLog2DataPageSize);
           (*pui32CurrentLevel)--;
           if (eError != PVRSRV_OK)
           {
               uiAllocState = 2;
               goto e0;
           }
       }
       else
       {
           /* All we need to do for level 1 is bump the refcount */
           psLevel->ui32RefCount++;
       }
       PVR_ASSERT(psLevel->ui32RefCount <= psLevel->ui32NumOfEntries);
   }
 
   /* Level one flushing is done when we actually write the table entries */
   if (aeMMULevel[uiThisLevel] != MMU_LEVEL_1)
   {
       eError = psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                                       &psLevel->sMemDesc.psMapping->sMemHandle,
                                                       uiStartIndex * psConfig->uiBytesPerEntry + psLevel->sMemDesc.uiOffset,
                                                       (uiEndIndex - uiStartIndex) * psConfig->uiBytesPerEntry);
       if (eError != PVRSRV_OK)
           goto e0;
   }
 
   MMU_OBJ_DBG((PVR_DBG_ERROR, "_MMU_AllocLevel end: level = %d, refcount = %d",
               aeMMULevel[uiThisLevel], psLevel->ui32RefCount));
   return PVRSRV_OK;
 
e0:
   /* Sanity check that we've not come down this route unexpectedly */
   PVR_ASSERT(uiAllocState!=99);
   PVR_DPF((PVR_DBG_ERROR, "_MMU_AllocLevel: Error %d allocating Px for level %d in stage %d"
                           ,eError, aeMMULevel[uiThisLevel], uiAllocState));
 
   /* the start value of index variable i is nor initialised on purpose
      indeed this for loop deinitialise what has already been initialised
      just before failing in reverse order. So the i index has already the
      right value. */
   for (/* i already set */ ; i>= uiStartIndex  &&  i< uiEndIndex; i--)
   {
       switch(uiAllocState)
       {
           IMG_UINT32 uiNextStartIndex;
           IMG_UINT32 uiNextEndIndex;
           IMG_BOOL bNextFirst;
           IMG_BOOL bNextLast;
 
           case 3:
                   /* If we're crossing a Px then the start index changes */
                   if (bFirst && (i == uiStartIndex))
                   {
                       uiNextStartIndex = auiStartArray[uiThisLevel + 1];
                       bNextFirst = IMG_TRUE;
                   }
                   else
                   {
                       uiNextStartIndex = 0;
                       bNextFirst = IMG_FALSE;
                   }
 
                   /* If we're crossing a Px then the end index changes */
                   if (bLast && (i == (uiEndIndex - 1)))
                   {
                       uiNextEndIndex = auiEndArray[uiThisLevel + 1];
                       bNextLast = IMG_TRUE;
                   }
                   else
                   {
                       uiNextEndIndex = auiEntriesPerPxArray[uiThisLevel + 1];
                       bNextLast = IMG_FALSE;
                   }
 
                   if (aeMMULevel[uiThisLevel] != MMU_LEVEL_1)
                   {
                       (*pui32CurrentLevel)++;
                       if (_MMU_FreeLevel(psMMUContext, psLevel->apsNextLevel[i],
                                           auiStartArray, auiEndArray,
                                           auiEntriesPerPxArray, apsConfig,
                                           aeMMULevel, pui32CurrentLevel,
                                           uiNextStartIndex, uiNextEndIndex,
                                           bNextFirst, bNextLast, uiLog2DataPageSize))
                       {
                           psLevel->ui32RefCount--;
                           psLevel->apsNextLevel[i] = NULL;
 
                           /* Check we haven't wrapped around */
                           PVR_ASSERT(psLevel->ui32RefCount <= psLevel->ui32NumOfEntries);
                       }
                       (*pui32CurrentLevel)--;
                   }
                   else
                   {
                       /* We should never come down this path, but it's here
                          for completeness */
                       psLevel->ui32RefCount--;
 
                       /* Check we haven't wrapped around */
                       PVR_ASSERT(psLevel->ui32RefCount <= psLevel->ui32NumOfEntries);
                   }
           case 2:
                   if (psLevel->apsNextLevel[i] != NULL  &&
                       psLevel->apsNextLevel[i]->ui32RefCount == 0)
                   {
                       _PxMemFree(psMMUContext, &psLevel->sMemDesc,
                                   aeMMULevel[uiThisLevel]);
                   }
           case 1:
                   if (psLevel->apsNextLevel[i] != NULL  &&
                       psLevel->apsNextLevel[i]->ui32RefCount == 0)
                   {
                       OSFreeMem(psLevel->apsNextLevel[i]);
                       psLevel->apsNextLevel[i] = NULL;
                   }
           case 0:
                   uiAllocState = 3;
                   break;
       }
   }
   return eError;
}
 
/*****************************************************************************
 *                   MMU page table functions                                *
 *****************************************************************************/
 
/*************************************************************************/ /*!
@Function       _MMU_GetLevelData
 
@Description    Get the all the level data and calculates the indexes for the
                specified address range
 
@Input          psMMUContext            MMU context to operate on
 
@Input          sDevVAddrStart          Start device virtual address
 
@Input          sDevVAddrEnd            End device virtual address
 
@Input          uiLog2DataPageSize      Log2 of the page size to use
 
@Input          auiStartArray           Array of start indexes (one for each level)
 
@Input          auiEndArray             Array of end indexes (one for each level)
 
@Input          uiEntriesPerPxArray     Array of number of entries for the Px
                                        (one for each level)
 
@Input          apsConfig               Array of PxE configs (one for each level)
 
@Input          aeMMULevel              Array of MMU levels (one for each level)
 
@Input          ppsMMUDevVAddrConfig    Device virtual address config
 
@Input            phPriv                    Private data of page size config
 
@Return         IMG_TRUE if the last reference to psLevel was dropped
*/
/*****************************************************************************/
static void _MMU_GetLevelData(MMU_CONTEXT *psMMUContext,
                                   IMG_DEV_VIRTADDR sDevVAddrStart,
                                   IMG_DEV_VIRTADDR sDevVAddrEnd,
                                   IMG_UINT32 uiLog2DataPageSize,
                                   IMG_UINT32 auiStartArray[],
                                   IMG_UINT32 auiEndArray[],
                                   IMG_UINT32 auiEntriesPerPx[],
                                   const MMU_PxE_CONFIG *apsConfig[],
                                   MMU_LEVEL aeMMULevel[],
                                   const MMU_DEVVADDR_CONFIG **ppsMMUDevVAddrConfig,
                                   IMG_HANDLE *phPriv)
{
   const MMU_PxE_CONFIG *psMMUPDEConfig;
   const MMU_PxE_CONFIG *psMMUPTEConfig;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
   MMU_DEVICEATTRIBS *psDevAttrs = psMMUContext->psDevAttrs;
   PVRSRV_ERROR eError;
   IMG_UINT32 i = 0;
 
   eError = psDevAttrs->pfnGetPageSizeConfiguration(uiLog2DataPageSize,
                                                       &psMMUPDEConfig,
                                                       &psMMUPTEConfig,
                                                       ppsMMUDevVAddrConfig,
                                                       phPriv);
   PVR_ASSERT(eError == PVRSRV_OK);
   
   psDevVAddrConfig = *ppsMMUDevVAddrConfig;
 
   if (psDevVAddrConfig->uiPCIndexMask != 0)
   {
       auiStartArray[i] = _CalcPCEIdx(sDevVAddrStart, psDevVAddrConfig, IMG_FALSE);
       auiEndArray[i] = _CalcPCEIdx(sDevVAddrEnd, psDevVAddrConfig, IMG_TRUE);
       auiEntriesPerPx[i] = psDevVAddrConfig->uiNumEntriesPC;
       apsConfig[i] = psDevAttrs->psBaseConfig;
       aeMMULevel[i] = MMU_LEVEL_3;
       i++;
   }
 
   if (psDevVAddrConfig->uiPDIndexMask != 0)
   {
       auiStartArray[i] = _CalcPDEIdx(sDevVAddrStart, psDevVAddrConfig, IMG_FALSE);
       auiEndArray[i] = _CalcPDEIdx(sDevVAddrEnd, psDevVAddrConfig, IMG_TRUE);
       auiEntriesPerPx[i] = psDevVAddrConfig->uiNumEntriesPD;
       if (i == 0)
       {
           apsConfig[i] = psDevAttrs->psBaseConfig;
       }
       else
       {
           apsConfig[i] = psMMUPDEConfig;
       }
       aeMMULevel[i] = MMU_LEVEL_2;
       i++;
   }
 
   /*
       There is always a PTE entry so we have a slightly different behaviour than above.
       E.g. for 2 MB RGX pages the uiPTIndexMask is 0x0000000000 but still there
       is a PT with one entry.
 
   */
   auiStartArray[i] = _CalcPTEIdx(sDevVAddrStart, psDevVAddrConfig, IMG_FALSE);
   if (psDevVAddrConfig->uiPTIndexMask !=0)
   {
       auiEndArray[i] = _CalcPTEIdx(sDevVAddrEnd, psDevVAddrConfig, IMG_TRUE);
   }
   else
   {
       /*
           If the PTE mask is zero it means there is only 1 PTE and thus
           the start and end array are one in the same
       */
       auiEndArray[i] = auiStartArray[i];
   }
 
   auiEntriesPerPx[i] = psDevVAddrConfig->uiNumEntriesPT;
 
   if (i == 0)
   {
       apsConfig[i] = psDevAttrs->psBaseConfig;
   }
   else
   {
       apsConfig[i] = psMMUPTEConfig;
   }
   aeMMULevel[i] = MMU_LEVEL_1;
}
 
static void _MMU_PutLevelData(MMU_CONTEXT *psMMUContext, IMG_HANDLE hPriv)
{
   MMU_DEVICEATTRIBS *psDevAttrs = psMMUContext->psDevAttrs;
 
   psDevAttrs->pfnPutPageSizeConfiguration(hPriv);
}
 
/*************************************************************************/ /*!
@Function       _AllocPageTables
 
@Description    Allocate page tables and any higher level MMU objects required
                for the specified virtual range
 
@Input          psMMUContext            MMU context to operate on
 
@Input          sDevVAddrStart          Start device virtual address
 
@Input          sDevVAddrEnd            End device virtual address
 
@Input          uiLog2DataPageSize      Page size of the data pages
 
@Return         PVRSRV_OK if the allocation was successful
*/
/*****************************************************************************/
static PVRSRV_ERROR
_AllocPageTables(MMU_CONTEXT *psMMUContext,
                 IMG_DEV_VIRTADDR sDevVAddrStart,
                 IMG_DEV_VIRTADDR sDevVAddrEnd,
                 IMG_UINT32 uiLog2DataPageSize)
{
   PVRSRV_ERROR eError;
   IMG_UINT32 auiStartArray[MMU_MAX_LEVEL];
   IMG_UINT32 auiEndArray[MMU_MAX_LEVEL];
   IMG_UINT32 auiEntriesPerPx[MMU_MAX_LEVEL];
   MMU_LEVEL aeMMULevel[MMU_MAX_LEVEL];
   const MMU_PxE_CONFIG *apsConfig[MMU_MAX_LEVEL];
   const MMU_DEVVADDR_CONFIG    *psDevVAddrConfig;
   IMG_HANDLE hPriv;
   IMG_UINT32 ui32CurrentLevel = 0;
 
 
   PVR_DPF((PVR_DBG_ALLOC,
            "_AllocPageTables: vaddr range: 0x%010llx:0x%010llx",
            sDevVAddrStart.uiAddr,
            sDevVAddrEnd.uiAddr
            ));
 
#if defined(PDUMP)
   PDUMPCOMMENT("Allocating page tables for %llu bytes virtual range: 0x%010llX to 0x%010llX",
               (IMG_UINT64)sDevVAddrEnd.uiAddr - (IMG_UINT64)sDevVAddrStart.uiAddr,
                 (IMG_UINT64)sDevVAddrStart.uiAddr,
                 (IMG_UINT64)sDevVAddrEnd.uiAddr);
#endif
 
   _MMU_GetLevelData(psMMUContext, sDevVAddrStart, sDevVAddrEnd,
                       (IMG_UINT32) uiLog2DataPageSize, auiStartArray, auiEndArray,
                       auiEntriesPerPx, apsConfig, aeMMULevel,
                       &psDevVAddrConfig, &hPriv);
 
   HTBLOGK(HTB_SF_MMU_PAGE_OP_ALLOC,
       HTBLOG_U64_BITS_HIGH(sDevVAddrStart.uiAddr), HTBLOG_U64_BITS_LOW(sDevVAddrStart.uiAddr),
       HTBLOG_U64_BITS_HIGH(sDevVAddrEnd.uiAddr), HTBLOG_U64_BITS_LOW(sDevVAddrEnd.uiAddr));
 
   eError = _MMU_AllocLevel(psMMUContext, &psMMUContext->sBaseLevelInfo,
                               auiStartArray, auiEndArray, auiEntriesPerPx,
                               apsConfig, aeMMULevel, &ui32CurrentLevel,
                               auiStartArray[0], auiEndArray[0],
                               IMG_TRUE, IMG_TRUE, uiLog2DataPageSize);
 
   _MMU_PutLevelData(psMMUContext, hPriv);
 
   return eError;
}
 
/*************************************************************************/ /*!
@Function       _FreePageTables
 
@Description    Free page tables and any higher level MMU objects at are no
                longer referenced for the specified virtual range.
                This will fill the temporary free list of the MMU context which
                needs cleanup after the call.
 
@Input          psMMUContext            MMU context to operate on
 
@Input          sDevVAddrStart          Start device virtual address
 
@Input          sDevVAddrEnd            End device virtual address
 
@Input          uiLog2DataPageSize      Page size of the data pages
 
@Return         None
*/
/*****************************************************************************/
static void _FreePageTables(MMU_CONTEXT *psMMUContext,
                           IMG_DEV_VIRTADDR sDevVAddrStart,
                           IMG_DEV_VIRTADDR sDevVAddrEnd,
                           IMG_UINT32 uiLog2DataPageSize)
{
   IMG_UINT32 auiStartArray[MMU_MAX_LEVEL];
   IMG_UINT32 auiEndArray[MMU_MAX_LEVEL];
   IMG_UINT32 auiEntriesPerPx[MMU_MAX_LEVEL];
   MMU_LEVEL aeMMULevel[MMU_MAX_LEVEL];
   const MMU_PxE_CONFIG *apsConfig[MMU_MAX_LEVEL];
   const MMU_DEVVADDR_CONFIG    *psDevVAddrConfig;
   IMG_UINT32 ui32CurrentLevel = 0;
   IMG_HANDLE hPriv;
 
 
   PVR_DPF((PVR_DBG_ALLOC,
            "_FreePageTables: vaddr range: 0x%010llx:0x%010llx",
            sDevVAddrStart.uiAddr,
            sDevVAddrEnd.uiAddr
            ));
 
   _MMU_GetLevelData(psMMUContext, sDevVAddrStart, sDevVAddrEnd,
                       uiLog2DataPageSize, auiStartArray, auiEndArray,
                       auiEntriesPerPx, apsConfig, aeMMULevel,
                       &psDevVAddrConfig, &hPriv);
 
   HTBLOGK(HTB_SF_MMU_PAGE_OP_FREE,
       HTBLOG_U64_BITS_HIGH(sDevVAddrStart.uiAddr), HTBLOG_U64_BITS_LOW(sDevVAddrStart.uiAddr),
       HTBLOG_U64_BITS_HIGH(sDevVAddrEnd.uiAddr), HTBLOG_U64_BITS_LOW(sDevVAddrEnd.uiAddr));
 
   _MMU_FreeLevel(psMMUContext, &psMMUContext->sBaseLevelInfo,
                   auiStartArray, auiEndArray, auiEntriesPerPx,
                   apsConfig, aeMMULevel, &ui32CurrentLevel,
                   auiStartArray[0], auiEndArray[0],
                   IMG_TRUE, IMG_TRUE, uiLog2DataPageSize);
 
   _MMU_PutLevelData(psMMUContext, hPriv);
}
 
 
/*************************************************************************/ /*!
@Function       _MMU_GetPTInfo
 
@Description    Get the PT level information and PT entry index for the specified
                virtual address
 
@Input          psMMUContext            MMU context to operate on
 
@Input          psDevVAddr              Device virtual address to get the PTE info
                                        from.
 
@Input          psDevVAddrConfig        The current virtual address config obtained
                                        by another function call before.
 
@Output         psLevel                 Level info of the PT
 
@Output         pui32PTEIndex           Index into the PT the address corresponds to
 
@Return         None
*/
/*****************************************************************************/
static INLINE void _MMU_GetPTInfo(MMU_CONTEXT                *psMMUContext,
                                 IMG_DEV_VIRTADDR            sDevVAddr,
                                 const MMU_DEVVADDR_CONFIG  *psDevVAddrConfig,
                                 MMU_Levelx_INFO           **psLevel,
                                 IMG_UINT32                 *pui32PTEIndex)
{
   MMU_Levelx_INFO *psLocalLevel = NULL;
 
   IMG_UINT32 uiPCEIndex;
   IMG_UINT32 uiPDEIndex;
 
   switch(psMMUContext->psDevAttrs->eTopLevel)
   {
       case MMU_LEVEL_3:
           /* find the page directory containing the PCE */
           uiPCEIndex = _CalcPCEIdx(sDevVAddr, psDevVAddrConfig, IMG_FALSE);
           psLocalLevel = psMMUContext->sBaseLevelInfo.apsNextLevel[uiPCEIndex];
 
       case MMU_LEVEL_2:
           /* find the page table containing the PDE */
           uiPDEIndex = _CalcPDEIdx(sDevVAddr, psDevVAddrConfig, IMG_FALSE);
           if (psLocalLevel != NULL)
           {
               psLocalLevel = psLocalLevel->apsNextLevel[uiPDEIndex];
           }
           else
           {
               psLocalLevel = psMMUContext->sBaseLevelInfo.apsNextLevel[uiPDEIndex];
           }
 
       case MMU_LEVEL_1:
           /* find PTE index into page table */
           *pui32PTEIndex = _CalcPTEIdx(sDevVAddr, psDevVAddrConfig, IMG_FALSE);
           if (psLocalLevel == NULL)
           {
               psLocalLevel = &psMMUContext->sBaseLevelInfo;
           }
           break;
 
       default:
           PVR_DPF((PVR_DBG_ERROR, "_MMU_GetPTEInfo: Invalid MMU level"));
           return;
   }
 
   *psLevel = psLocalLevel;
}
 
/*************************************************************************/ /*!
@Function       _MMU_GetPTConfig
 
@Description    Get the level config. Call _MMU_PutPTConfig after use!
 
@Input          psMMUContext            MMU context to operate on
 
@Input          uiLog2DataPageSize      Log 2 of the page size
 
@Output         ppsConfig               Config of the PTE
 
@Output         phPriv                  Private data handle to be passed back
                                        when the info is put
 
@Output         ppsDevVAddrConfig       Config of the device virtual addresses
 
@Return         None
*/
/*****************************************************************************/
static INLINE void _MMU_GetPTConfig(MMU_CONTEXT               *psMMUContext,
                                   IMG_UINT32                  uiLog2DataPageSize,
                                   const MMU_PxE_CONFIG      **ppsConfig,
                                   IMG_HANDLE                 *phPriv,
                                   const MMU_DEVVADDR_CONFIG **ppsDevVAddrConfig)
{
   MMU_DEVICEATTRIBS *psDevAttrs = psMMUContext->psDevAttrs;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
   const MMU_PxE_CONFIG *psPDEConfig;
   const MMU_PxE_CONFIG *psPTEConfig;
 
   if (psDevAttrs->pfnGetPageSizeConfiguration(uiLog2DataPageSize,
                                               &psPDEConfig,
                                               &psPTEConfig,
                                               &psDevVAddrConfig,
                                               phPriv) != PVRSRV_OK)
   {
       /*
          There should be no way we got here unless uiLog2DataPageSize
          has changed after the MMU_Alloc call (in which case it's a bug in
          the MM code)
       */
       PVR_DPF((PVR_DBG_ERROR, "_MMU_GetPTConfig: Could not get valid page size config"));
       PVR_ASSERT(0);
   }
 
   *ppsConfig = psPTEConfig;
   *ppsDevVAddrConfig = psDevVAddrConfig;
}
 
/*************************************************************************/ /*!
@Function       _MMU_PutPTConfig
 
@Description    Put the level info. Has to be called after _MMU_GetPTConfig to
                ensure correct refcounting.
 
@Input          psMMUContext            MMU context to operate on
 
@Input          phPriv                  Private data handle created by
                                        _MMU_GetPTConfig.
 
@Return         None
*/
/*****************************************************************************/
static INLINE void _MMU_PutPTConfig(MMU_CONTEXT *psMMUContext,
                                 IMG_HANDLE hPriv)
{
   MMU_DEVICEATTRIBS *psDevAttrs = psMMUContext->psDevAttrs;
 
   if( psDevAttrs->pfnPutPageSizeConfiguration(hPriv) != PVRSRV_OK )
   {
       PVR_DPF((PVR_DBG_ERROR, "_MMU_GetPTConfig: Could not put page size config"));
       PVR_ASSERT(0);
   }
 
}
 
 
/*****************************************************************************
 *                     Public interface functions                            *
 *****************************************************************************/
 
/*
   MMU_ContextCreate
*/
PVRSRV_ERROR
MMU_ContextCreate(PVRSRV_DEVICE_NODE *psDevNode,
                  MMU_CONTEXT **ppsMMUContext,
                  MMU_DEVICEATTRIBS *psDevAttrs)
{
   MMU_CONTEXT *psMMUContext;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
   const MMU_PxE_CONFIG *psConfig;
   MMU_PHYSMEM_CONTEXT *psCtx;
   IMG_UINT32 ui32BaseObjects;
   IMG_UINT32 ui32Size;
   IMG_CHAR sBuf[40];
   PVRSRV_ERROR eError = PVRSRV_OK;
 
   psConfig = psDevAttrs->psBaseConfig;
   psDevVAddrConfig = psDevAttrs->psTopLevelDevVAddrConfig;
 
   switch(psDevAttrs->eTopLevel)
   {
       case MMU_LEVEL_3:
           ui32BaseObjects = psDevVAddrConfig->uiNumEntriesPC;
           break;
 
       case MMU_LEVEL_2:
           ui32BaseObjects = psDevVAddrConfig->uiNumEntriesPD;
           break;
 
       case MMU_LEVEL_1:
           ui32BaseObjects = psDevVAddrConfig->uiNumEntriesPT;
           break;
 
       default:
           PVR_DPF((PVR_DBG_ERROR, "MMU_ContextCreate: Invalid MMU config"));
           eError = PVRSRV_ERROR_INVALID_PARAMS;
           goto e0;
   }
 
   /* Allocate the MMU context with the Level 1 Px info's */
   ui32Size = sizeof(MMU_CONTEXT) + 
                       ((ui32BaseObjects - 1) * sizeof(MMU_Levelx_INFO *));
 
   psMMUContext = OSAllocZMem(ui32Size);
   if (psMMUContext == NULL)
   {
       PVR_DPF((PVR_DBG_ERROR, "MMU_ContextCreate: ERROR call to OSAllocMem failed"));
       eError = PVRSRV_ERROR_OUT_OF_MEMORY;
       goto e0;
   }
 
#if defined(PDUMP)
   /* Clear the refcount */
   psMMUContext->ui32PDumpContextIDRefCount = 0;
#endif
   /* Record Device specific attributes in the context for subsequent use */
   psMMUContext->psDevAttrs = psDevAttrs;
   psMMUContext->psDevNode = psDevNode;
 
#if defined(SUPPORT_GPUVIRT_VALIDATION)
{
   IMG_UINT32 ui32OSid, ui32OSidReg;
    IMG_BOOL bOSidAxiProt;
 
    RetrieveOSidsfromPidList(OSGetCurrentClientProcessIDKM(), &ui32OSid, &ui32OSidReg, &bOSidAxiProt);
 
    MMU_SetOSids(psMMUContext, ui32OSid, ui32OSidReg, bOSidAxiProt);
}
#endif
 
   /*
     Allocate physmem context and set it up
    */
   psCtx = OSAllocZMem(sizeof(MMU_PHYSMEM_CONTEXT));
   if (psCtx == NULL)
   {
       PVR_DPF((PVR_DBG_ERROR, "MMU_ContextCreate: ERROR call to OSAllocMem failed"));
       eError = PVRSRV_ERROR_OUT_OF_MEMORY;
       goto e1;
   }
   psMMUContext->psPhysMemCtx = psCtx;
 
   psCtx->psDevNode = psDevNode;
 
   OSSNPrintf(sBuf, sizeof(sBuf)-1, "pgtables %p", psCtx);
   psCtx->uiPhysMemRANameAllocSize = OSStringLength(sBuf)+1;
   psCtx->pszPhysMemRAName = OSAllocMem(psCtx->uiPhysMemRANameAllocSize);
   if (psCtx->pszPhysMemRAName == NULL)
   {
       PVR_DPF((PVR_DBG_ERROR, "MMU_ContextCreate: Out of memory"));
       eError = PVRSRV_ERROR_OUT_OF_MEMORY;
       goto e2;
   }
 
   OSStringCopy(psCtx->pszPhysMemRAName, sBuf);
 
   psCtx->psPhysMemRA = RA_Create(psCtx->pszPhysMemRAName,
                                   /* subsequent import */
                                   psDevNode->uiMMUPxLog2AllocGran,
                                   RA_LOCKCLASS_1,
                                   _MMU_PhysMem_RAImportAlloc,
                                   _MMU_PhysMem_RAImportFree,
                                   psCtx, /* priv */
                                   IMG_FALSE);
   if (psCtx->psPhysMemRA == NULL)
   {
       OSFreeMem(psCtx->pszPhysMemRAName);
       psCtx->pszPhysMemRAName = NULL;
       eError = PVRSRV_ERROR_OUT_OF_MEMORY;
       goto e3;
   }
 
   /* Setup cleanup meta data to check if a MMU context
    * has been destroyed and should not be accessed anymore */
   psCtx->psCleanupData = OSAllocMem(sizeof(*(psCtx->psCleanupData)));
   if (psCtx->psCleanupData == NULL)
   {
       PVR_DPF((PVR_DBG_ERROR, "MMU_ContextCreate: ERROR call to OSAllocMem failed"));
       eError = PVRSRV_ERROR_OUT_OF_MEMORY;
       goto e4;
   }
 
   OSLockCreate(&psCtx->psCleanupData->hCleanupLock, LOCK_TYPE_PASSIVE);
   psCtx->psCleanupData->bMMUContextExists = IMG_TRUE;
   dllist_init(&psCtx->psCleanupData->sMMUCtxCleanupItemsHead);
   psCtx->psCleanupData->uiRef = 1;
 
   /* allocate the base level object */
   /*
      Note: Although this is not required by the this file until
            the 1st allocation is made, a device specific callback
            might request the base object address so we allocate
            it up front.
   */
   if (_PxMemAlloc(psMMUContext,
                           ui32BaseObjects,
                           psConfig,
                           psDevAttrs->eTopLevel,
                           &psMMUContext->sBaseLevelInfo.sMemDesc,
                           psDevAttrs->ui32BaseAlign))
   {
       PVR_DPF((PVR_DBG_ERROR, "MMU_ContextCreate: Failed to alloc level 1 object"));
       eError = PVRSRV_ERROR_OUT_OF_MEMORY;
       goto e5;
   }
 
   dllist_init(&psMMUContext->psPhysMemCtx->sTmpMMUMappingHead);
 
   psMMUContext->sBaseLevelInfo.ui32NumOfEntries = ui32BaseObjects;
   psMMUContext->sBaseLevelInfo.ui32RefCount = 0;
 
   eError = OSLockCreate(&psMMUContext->hLock, LOCK_TYPE_PASSIVE);
 
   if(eError != PVRSRV_OK)
   {
       PVR_DPF((PVR_DBG_ERROR, "MMU_ContextCreate: Failed to create lock for MMU_CONTEXT"));
       goto e6;
   }
 
   /* return context */
   *ppsMMUContext = psMMUContext;
 
   return PVRSRV_OK;
 
e6:
   _PxMemFree(psMMUContext, &psMMUContext->sBaseLevelInfo.sMemDesc, psDevAttrs->eTopLevel);
e5:
   OSFreeMem(psCtx->psCleanupData);
e4:
   RA_Delete(psCtx->psPhysMemRA);
e3:
   OSFreeMem(psCtx->pszPhysMemRAName);
e2:
   OSFreeMem(psCtx);
e1:
   OSFreeMem(psMMUContext);
e0:
   return eError;
}
 
/*
   MMU_ContextDestroy
*/
void
MMU_ContextDestroy (MMU_CONTEXT *psMMUContext)
{
   PVRSRV_DATA *psPVRSRVData = PVRSRVGetPVRSRVData();
   PDLLIST_NODE psNode, psNextNode;
 
   PVRSRV_DEVICE_NODE *psDevNode = (PVRSRV_DEVICE_NODE *) psMMUContext->psDevNode;
   MMU_CTX_CLEANUP_DATA *psCleanupData = psMMUContext->psPhysMemCtx->psCleanupData;
   IMG_UINT32 uiRef;
 
   PVR_DPF ((PVR_DBG_MESSAGE, "MMU_ContextDestroy: Enter"));
 
   if (psPVRSRVData->eServicesState == PVRSRV_SERVICES_STATE_OK)
   {
       /* There should be no way to get here with live pages unless
          there is a bug in this module or the MM code */
       PVR_ASSERT(psMMUContext->sBaseLevelInfo.ui32RefCount == 0);
   }
 
   OSLockAcquire(psMMUContext->hLock);
 
   /* Free the top level MMU object - will be put on defer free list.
    * This has to be done before the step below that will empty the
    * defer-free list. */
   _PxMemFree(psMMUContext,
              &psMMUContext->sBaseLevelInfo.sMemDesc,
              psMMUContext->psDevAttrs->eTopLevel);
 
   /* Empty the temporary defer-free list of Px */
   _FreeMMUMapping(psDevNode, &psMMUContext->psPhysMemCtx->sTmpMMUMappingHead);
   PVR_ASSERT(dllist_is_empty(&psMMUContext->psPhysMemCtx->sTmpMMUMappingHead));
 
   OSLockAcquire(psCleanupData->hCleanupLock);
 
   /* Empty the defer free list so the cleanup thread will
    * not have to access any MMU context related structures anymore */
   dllist_foreach_node(&psCleanupData->sMMUCtxCleanupItemsHead,
                       psNode,
                       psNextNode)
   {
       MMU_CLEANUP_ITEM *psCleanup = IMG_CONTAINER_OF(psNode,
                                                      MMU_CLEANUP_ITEM,
                                                      sMMUCtxCleanupItem);
 
       _FreeMMUMapping(psDevNode, &psCleanup->sMMUMappingHead);
 
       dllist_remove_node(psNode);
   }
   PVR_ASSERT(dllist_is_empty(&psCleanupData->sMMUCtxCleanupItemsHead));
 
   psCleanupData->bMMUContextExists = IMG_FALSE;
   uiRef = --psCleanupData->uiRef;
 
   OSLockRelease(psCleanupData->hCleanupLock);
 
   if (uiRef == 0)
   {
       OSLockDestroy(psCleanupData->hCleanupLock);
       OSFreeMem(psCleanupData);
   }
 
   /* Free physmem context */
   RA_Delete(psMMUContext->psPhysMemCtx->psPhysMemRA);
   psMMUContext->psPhysMemCtx->psPhysMemRA = NULL;
   OSFreeMem(psMMUContext->psPhysMemCtx->pszPhysMemRAName);
   psMMUContext->psPhysMemCtx->pszPhysMemRAName = NULL;
 
   OSFreeMem(psMMUContext->psPhysMemCtx);
 
   OSLockRelease(psMMUContext->hLock);
 
#if defined(SUPPORT_GPUVIRT_VALIDATION)
   RemovePidOSidCoupling(OSGetCurrentClientProcessIDKM());
#endif
 
   OSLockDestroy(psMMUContext->hLock);
 
   /* free the context itself. */
   OSFreeMem(psMMUContext);
   /*not nulling pointer, copy on stack*/
 
   PVR_DPF ((PVR_DBG_MESSAGE, "MMU_ContextDestroy: Exit"));
}
 
/*
   MMU_Alloc
*/
PVRSRV_ERROR
MMU_Alloc (MMU_CONTEXT *psMMUContext,
          IMG_DEVMEM_SIZE_T uSize,
          IMG_DEVMEM_SIZE_T *puActualSize,
           IMG_UINT32 uiProtFlags,
          IMG_DEVMEM_SIZE_T uDevVAddrAlignment,
          IMG_DEV_VIRTADDR *psDevVAddr,
          IMG_UINT32 uiLog2PageSize)
{
    PVRSRV_ERROR eError;
    IMG_DEV_VIRTADDR sDevVAddrEnd;
 
 
   const MMU_PxE_CONFIG *psPDEConfig;
   const MMU_PxE_CONFIG *psPTEConfig;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
 
   MMU_DEVICEATTRIBS *psDevAttrs;
   IMG_HANDLE hPriv;
   
#if !defined (DEBUG)
   PVR_UNREFERENCED_PARAMETER(uDevVAddrAlignment);
#endif
 
   PVR_DPF ((PVR_DBG_MESSAGE, "MMU_Alloc: uSize=0x%010llx, uiProtFlags=0x%x, align=0x%010llx", uSize, uiProtFlags, uDevVAddrAlignment));
 
   /* check params */
   if (!psMMUContext || !psDevVAddr || !puActualSize)
   {
       PVR_DPF((PVR_DBG_ERROR,"MMU_Alloc: invalid params"));
       return PVRSRV_ERROR_INVALID_PARAMS;
   }
 
   psDevAttrs = psMMUContext->psDevAttrs;
 
   eError = psDevAttrs->pfnGetPageSizeConfiguration(uiLog2PageSize,
                                                   &psPDEConfig,
                                                   &psPTEConfig,
                                                   &psDevVAddrConfig,
                                                   &hPriv);
   if (eError != PVRSRV_OK)
   {
       PVR_DPF((PVR_DBG_ERROR,"MMU_Alloc: Failed to get config info (%d)", eError));
       return eError;
   }
 
   /* size and alignment must be datapage granular */
   if(((psDevVAddr->uiAddr & psDevVAddrConfig->uiPageOffsetMask) != 0)
   || ((uSize & psDevVAddrConfig->uiPageOffsetMask) != 0))
   {
       PVR_DPF((PVR_DBG_ERROR,"MMU_Alloc: invalid address or size granularity"));
       return PVRSRV_ERROR_INVALID_PARAMS;
   }
 
   sDevVAddrEnd = *psDevVAddr;
   sDevVAddrEnd.uiAddr += uSize;
 
   OSLockAcquire(psMMUContext->hLock);
   eError = _AllocPageTables(psMMUContext, *psDevVAddr, sDevVAddrEnd, uiLog2PageSize);
   OSLockRelease(psMMUContext->hLock);
 
   if (eError != PVRSRV_OK)
   {
       PVR_DPF((PVR_DBG_ERROR,"MMU_Alloc: _DeferredAllocPagetables failed"));
        return PVRSRV_ERROR_MMU_FAILED_TO_ALLOCATE_PAGETABLES;
   }
 
   psDevAttrs->pfnPutPageSizeConfiguration(hPriv);
 
   return PVRSRV_OK;
}
 
/*
   MMU_Free
*/
void
MMU_Free (MMU_CONTEXT *psMMUContext,
          IMG_DEV_VIRTADDR sDevVAddr,
          IMG_DEVMEM_SIZE_T uiSize,
          IMG_UINT32 uiLog2DataPageSize)
{
   IMG_DEV_VIRTADDR sDevVAddrEnd;
 
   if (psMMUContext == NULL)
   {
       PVR_DPF((PVR_DBG_ERROR, "MMU_Free: invalid parameter"));
       return;
   }
 
   PVR_DPF((PVR_DBG_MESSAGE, "MMU_Free: Freeing DevVAddr 0x%010llX",
            sDevVAddr.uiAddr));
 
   /* ensure the address range to free is inside the heap */
   sDevVAddrEnd = sDevVAddr;
   sDevVAddrEnd.uiAddr += uiSize;
 
   OSLockAcquire(psMMUContext->hLock);
 
   _FreePageTables(psMMUContext,
                   sDevVAddr,
                   sDevVAddrEnd,
                   uiLog2DataPageSize);
 
   _SetupCleanup_FreeMMUMapping(psMMUContext->psDevNode,
                                psMMUContext->psPhysMemCtx);
 
   OSLockRelease(psMMUContext->hLock);
 
   return;
 
}
 
PVRSRV_ERROR
MMU_MapPages(MMU_CONTEXT *psMMUContext,
             PVRSRV_MEMALLOCFLAGS_T uiMappingFlags,
             IMG_DEV_VIRTADDR sDevVAddrBase,
             PMR *psPMR,
             IMG_UINT32 ui32PhysPgOffset,
             IMG_UINT32 ui32MapPageCount,
             IMG_UINT32 *paui32MapIndices,
             IMG_UINT32 uiLog2PageSize)
{
   PVRSRV_ERROR eError;
   IMG_HANDLE hPriv;
 
   MMU_Levelx_INFO *psLevel = NULL;
 
   MMU_Levelx_INFO *psPrevLevel = NULL;
 
   IMG_UINT32 uiPTEIndex = 0;
   IMG_UINT32 uiPageSize = (1 << uiLog2PageSize);
   IMG_UINT32 uiLoop = 0;
   IMG_UINT32 ui32MappedCount = 0;
   IMG_UINT32 uiPgOffset = 0;
   IMG_UINT32 uiFlushEnd = 0, uiFlushStart = 0;
 
   IMG_UINT64 uiProtFlags = 0;
   MMU_PROTFLAGS_T uiMMUProtFlags = 0;
 
   const MMU_PxE_CONFIG *psConfig;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
 
   IMG_DEV_VIRTADDR sDevVAddr = sDevVAddrBase;
 
   IMG_DEV_PHYADDR asDevPAddr[PMR_MAX_TRANSLATION_STACK_ALLOC];
   IMG_BOOL abValid[PMR_MAX_TRANSLATION_STACK_ALLOC];
   IMG_DEV_PHYADDR *psDevPAddr;
   IMG_DEV_PHYADDR sDevPAddr;
   IMG_BOOL *pbValid;
   IMG_BOOL bValid;
   IMG_BOOL bDummyBacking = IMG_FALSE;
   IMG_BOOL bNeedBacking = IMG_FALSE;
 
#if defined(PDUMP)
   IMG_CHAR aszMemspaceName[PHYSMEM_PDUMP_MEMSPACE_MAX_LENGTH];
   IMG_CHAR aszSymbolicAddress[PHYSMEM_PDUMP_SYMNAME_MAX_LENGTH];
   IMG_DEVMEM_OFFSET_T uiSymbolicAddrOffset;
 
   PDUMPCOMMENT("Wire up Page Table entries to point to the Data Pages (%lld bytes)",
                 (IMG_UINT64)(ui32MapPageCount * uiPageSize));
#endif /*PDUMP*/
 
 
   /* Validate the most essential parameters */
   if((NULL == psMMUContext) || (0 == sDevVAddrBase.uiAddr) || (NULL == psPMR))
   {
       PVR_DPF((PVR_DBG_ERROR,"%s: Invalid mapping parameter issued", __func__));
       eError = PVRSRV_ERROR_INVALID_PARAMS;
       goto e0;
   }
 
   /* Allocate memory for page-frame-numbers and validity states,
      N.B. assert could be triggered by an illegal uiSizeBytes */
   if (ui32MapPageCount > PMR_MAX_TRANSLATION_STACK_ALLOC)
   {
       psDevPAddr = OSAllocMem(ui32MapPageCount * sizeof(IMG_DEV_PHYADDR));
       if (psDevPAddr == NULL)
       {
           PVR_DPF((PVR_DBG_ERROR, "Failed to allocate PMR device PFN list"));
           eError = PVRSRV_ERROR_OUT_OF_MEMORY;
           goto e0;
       }
 
       pbValid = OSAllocMem(ui32MapPageCount * sizeof(IMG_BOOL));
       if (pbValid == NULL)
       {
           /* Should allocation fail, clean-up here before exit */
           PVR_DPF((PVR_DBG_ERROR, "Failed to allocate PMR device PFN state"));
           eError = PVRSRV_ERROR_OUT_OF_MEMORY;
           OSFreeMem(psDevPAddr);
           goto e0;
       }
   }
   else
   {
       psDevPAddr = asDevPAddr;
       pbValid    = abValid;
   }
 
   /* Get the Device physical addresses of the pages we are trying to map
    * In the case of non indexed mapping we can get all addresses at once */
   if(NULL == paui32MapIndices)
   {
       eError = PMR_DevPhysAddr(psPMR,
                                uiLog2PageSize,
                                ui32MapPageCount,
                                (ui32PhysPgOffset << uiLog2PageSize),
                                psDevPAddr,
                                pbValid);
       if (eError != PVRSRV_OK)
       {
           goto e1;
       }
   }
 
   /*Get the Page table level configuration */
   _MMU_GetPTConfig(psMMUContext,
                    (IMG_UINT32) uiLog2PageSize,
                    &psConfig,
                    &hPriv,
                    &psDevVAddrConfig);
 
   _MMU_ConvertDevMemFlags(IMG_FALSE,
                                uiMappingFlags,
                                &uiMMUProtFlags,
                                psMMUContext);
   /* Callback to get device specific protection flags */
   if (psConfig->uiBytesPerEntry == 8)
   {
       uiProtFlags = psMMUContext->psDevAttrs->pfnDerivePTEProt8(uiMMUProtFlags , uiLog2PageSize);
   }
   else if (psConfig->uiBytesPerEntry == 4)
   {
       uiProtFlags = psMMUContext->psDevAttrs->pfnDerivePTEProt4(uiMMUProtFlags);
   }
   else
   {
       PVR_DPF((PVR_DBG_ERROR,"%s: The page table entry byte length is not supported", __func__));
       eError = PVRSRV_ERROR_INVALID_PARAMS;
       goto e2;
   }
 
   if (PMR_IsSparse(psPMR))
   {
       /* We know there will not be 4G number of PMR's */
       bDummyBacking = PVRSRV_IS_SPARSE_DUMMY_BACKING_REQUIRED(uiMappingFlags);
   }
 
   OSLockAcquire(psMMUContext->hLock);
 
   for(uiLoop = 0; uiLoop < ui32MapPageCount; uiLoop++)
   {
 
#if defined(PDUMP)
       IMG_DEVMEM_OFFSET_T uiNextSymName;
#endif /*PDUMP*/
 
       if(NULL != paui32MapIndices)
       {
           uiPgOffset = paui32MapIndices[uiLoop];
 
           /*Calculate the Device Virtual Address of the page */
           sDevVAddr.uiAddr = sDevVAddrBase.uiAddr + (uiPgOffset * uiPageSize);
           /* Get the physical address to map */
           eError = PMR_DevPhysAddr(psPMR,
                                    uiLog2PageSize,
                                    1,
                                    uiPgOffset * uiPageSize,
                                    &sDevPAddr,
                                    &bValid);
           if (eError != PVRSRV_OK)
           {
               goto e3;
           }
       }
       else
       {
           uiPgOffset = uiLoop + ui32PhysPgOffset;
           sDevPAddr = psDevPAddr[uiLoop];
           bValid = pbValid[uiLoop];
       }
 
       /*
           The default value of the entry is invalid so we don't need to mark
           it as such if the page wasn't valid, we just advance pass that address
       */
       if (bValid || bDummyBacking)
       {
 
           if(!bValid)
           {
               sDevPAddr.uiAddr = psMMUContext->psDevNode->sDummyPage.ui64DummyPgPhysAddr;
           }
           else
           {
               /* check the physical alignment of the memory to map */
               PVR_ASSERT((sDevPAddr.uiAddr & (uiPageSize-1)) == 0);
           }
 
#if defined(DEBUG)
{
           IMG_INT32    i32FeatureVal = 0;
           IMG_UINT32 ui32BitLength = FloorLog2(sDevPAddr.uiAddr);
 
           i32FeatureVal = psMMUContext->psDevNode->pfnGetDeviceFeatureValue(psMMUContext->psDevNode, \
                                                       RGX_FEATURE_PHYS_BUS_WIDTH_BIT_MASK);
           do {
               /* i32FeatureVal can be negative for cases where this feature is undefined
                * In that situation we need to bail out than go ahead with debug comparison */
               if(0 > i32FeatureVal)
                   break;
 
               if (ui32BitLength > i32FeatureVal )
               {
                   PVR_DPF((PVR_DBG_ERROR,"_MMU_MapPage Failed. The physical address bitlength (%d) "
                            "is greater than what the chip can handle (%d).",
                            ui32BitLength, i32FeatureVal));
 
                   PVR_ASSERT(ui32BitLength <= i32FeatureVal );
                   eError = PVRSRV_ERROR_INVALID_PARAMS;
                   goto e3;
               }
           }while(0);
}
#endif /*DEBUG*/
 
#if defined(PDUMP)
           if(bValid)
           {
               eError = PMR_PDumpSymbolicAddr(psPMR, uiPgOffset * uiPageSize,
                                              sizeof(aszMemspaceName), &aszMemspaceName[0],
                                              sizeof(aszSymbolicAddress), &aszSymbolicAddress[0],
                                              &uiSymbolicAddrOffset,
                                              &uiNextSymName);
               PVR_ASSERT(eError == PVRSRV_OK);
           }
#endif /*PDUMP*/
 
           psPrevLevel = psLevel;
           /* Calculate PT index and get new table descriptor */
           _MMU_GetPTInfo(psMMUContext, sDevVAddr, psDevVAddrConfig,
                          &psLevel, &uiPTEIndex);
 
           if (psPrevLevel == psLevel)
           {
               uiFlushEnd = uiPTEIndex;
           }
           else
           {
               /* Flush if we moved to another psLevel, i.e. page table */
               if (psPrevLevel != NULL)
               {
                   eError = psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                                                   &psPrevLevel->sMemDesc.psMapping->sMemHandle,
                                                                   uiFlushStart * psConfig->uiBytesPerEntry + psPrevLevel->sMemDesc.uiOffset,
                                                                   (uiFlushEnd+1 - uiFlushStart) * psConfig->uiBytesPerEntry);
                   if (eError != PVRSRV_OK)
                       goto e3;
               }
 
               uiFlushStart = uiPTEIndex;
               uiFlushEnd = uiFlushStart;
           }
 
           HTBLOGK(HTB_SF_MMU_PAGE_OP_MAP,
               HTBLOG_U64_BITS_HIGH(sDevVAddr.uiAddr), HTBLOG_U64_BITS_LOW(sDevVAddr.uiAddr),
               HTBLOG_U64_BITS_HIGH(sDevPAddr.uiAddr), HTBLOG_U64_BITS_LOW(sDevPAddr.uiAddr));
 
               /* Set the PT entry with the specified address and protection flags */
           eError = _SetupPTE(psMMUContext,
                              psLevel,
                              uiPTEIndex,
                              psConfig,
                              &sDevPAddr,
                              IMG_FALSE,
#if defined(PDUMP)
                              (bValid)?aszMemspaceName:(psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName),
                              (bValid)?aszSymbolicAddress:DUMMY_PAGE,
                              (bValid)?uiSymbolicAddrOffset:0,
#endif /*PDUMP*/
                              uiProtFlags);
 
 
           if(eError != PVRSRV_OK)
           {
               PVR_DPF((PVR_DBG_ERROR, "%s: Mapping failed", __func__));
               goto e3;
           }
 
           if(bValid)
           {
               PVR_ASSERT(psLevel->ui32RefCount <= psLevel->ui32NumOfEntries);
               PVR_DPF ((PVR_DBG_MESSAGE,
                         "%s: devVAddr=%10llX, size=0x%x",
                         __func__,
                         sDevVAddr.uiAddr,
                         uiPgOffset * uiPageSize));
 
               ui32MappedCount++;
           }
       }
 
       sDevVAddr.uiAddr += uiPageSize;
   }
 
   /* Flush the last level we touched */
   if (psLevel != NULL)
   {
       eError = psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                                       &psLevel->sMemDesc.psMapping->sMemHandle,
                                                       uiFlushStart * psConfig->uiBytesPerEntry + psLevel->sMemDesc.uiOffset,
                                                       (uiFlushEnd+1 - uiFlushStart) * psConfig->uiBytesPerEntry);
       if (eError != PVRSRV_OK)
           goto e3;
   }
 
   OSLockRelease(psMMUContext->hLock);
 
   _MMU_PutPTConfig(psMMUContext, hPriv);
 
   if (psDevPAddr != asDevPAddr)
   {
       OSFreeMem(pbValid);
       OSFreeMem(psDevPAddr);
   }
 
   /* Flush TLB for PTs*/
   psMMUContext->psDevNode->pfnMMUCacheInvalidate(psMMUContext->psDevNode,
                                                  psMMUContext->hDevData,
                                                  MMU_LEVEL_1,
                                                  IMG_FALSE);
 
#if defined(PDUMP)
   PDUMPCOMMENT("Wired up %d Page Table entries (out of %d)", ui32MappedCount, ui32MapPageCount);
#endif /*PDUMP*/
 
   return PVRSRV_OK;
 
e3:
   OSLockRelease(psMMUContext->hLock);
 
   if(PMR_IsSparse(psPMR) && PVRSRV_IS_SPARSE_DUMMY_BACKING_REQUIRED(uiMappingFlags))
   {
       bNeedBacking = IMG_TRUE;
   }
 
   MMU_UnmapPages(psMMUContext,(bNeedBacking)?uiMappingFlags:0, sDevVAddrBase, uiLoop, paui32MapIndices, uiLog2PageSize, bNeedBacking);
e2:
   _MMU_PutPTConfig(psMMUContext, hPriv);
e1:
   if (psDevPAddr != asDevPAddr)
   {
       OSFreeMem(pbValid);
       OSFreeMem(psDevPAddr);
   }
e0:
   return eError;
}
 
/*
   MMU_UnmapPages
*/
void
MMU_UnmapPages (MMU_CONTEXT *psMMUContext,
               PVRSRV_MEMALLOCFLAGS_T uiMappingFlags,
                IMG_DEV_VIRTADDR sDevVAddrBase,
                IMG_UINT32 ui32PageCount,
                IMG_UINT32 *pai32FreeIndices,
                IMG_UINT32 uiLog2PageSize,
                IMG_BOOL bDummyBacking)
{
   IMG_UINT32 uiPTEIndex = 0, ui32Loop=0;
   IMG_UINT32 uiPageSize = 1 << uiLog2PageSize;
   IMG_UINT32 uiFlushEnd = 0, uiFlushStart = 0;
   MMU_Levelx_INFO *psLevel = NULL;
   MMU_Levelx_INFO *psPrevLevel = NULL;
   IMG_HANDLE hPriv;
   const MMU_PxE_CONFIG *psConfig;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
   IMG_UINT64 uiProtFlags = 0;
   MMU_PROTFLAGS_T uiMMUProtFlags = 0;
   IMG_DEV_VIRTADDR sDevVAddr = sDevVAddrBase;
   IMG_DEV_PHYADDR sDummyPgDevPhysAddr;
   IMG_BOOL bUnmap = IMG_TRUE;
 
#if defined(PDUMP)
   PDUMPCOMMENT("Invalidate %d entries in page tables for virtual range: 0x%010llX to 0x%010llX",
                ui32PageCount,
                (IMG_UINT64)sDevVAddr.uiAddr,
                ((IMG_UINT64)sDevVAddr.uiAddr) + (uiPageSize*ui32PageCount)-1);
#endif
 
   sDummyPgDevPhysAddr.uiAddr = psMMUContext->psDevNode->sDummyPage.ui64DummyPgPhysAddr;
   bUnmap = (bDummyBacking)?IMG_FALSE:IMG_TRUE;
   /* Get PT and address configs */
   _MMU_GetPTConfig(psMMUContext, (IMG_UINT32) uiLog2PageSize,
                    &psConfig, &hPriv, &psDevVAddrConfig);
 
   _MMU_ConvertDevMemFlags(bUnmap,
                               uiMappingFlags,
                                &uiMMUProtFlags,
                                psMMUContext);
 
   /* Callback to get device specific protection flags */
   if (psConfig->uiBytesPerEntry == 4)
   {
       uiProtFlags = psMMUContext->psDevAttrs->pfnDerivePTEProt4(uiMMUProtFlags);
   }
   else if (psConfig->uiBytesPerEntry == 8)
   {
       uiProtFlags = psMMUContext->psDevAttrs->pfnDerivePTEProt8(uiMMUProtFlags , uiLog2PageSize);
   }
 
 
   OSLockAcquire(psMMUContext->hLock);
 
   /* Unmap page by page */
   while (ui32Loop < ui32PageCount)
   {
       if(NULL != pai32FreeIndices)
       {
           /*Calculate the Device Virtual Address of the page */
           sDevVAddr.uiAddr = sDevVAddrBase.uiAddr +
                                       pai32FreeIndices[ui32Loop] * uiPageSize;
       }
 
       psPrevLevel = psLevel;
       /* Calculate PT index and get new table descriptor */
       _MMU_GetPTInfo(psMMUContext, sDevVAddr, psDevVAddrConfig,
                      &psLevel, &uiPTEIndex);
 
       if (psPrevLevel == psLevel)
       {
           uiFlushEnd = uiPTEIndex;
       }
       else
       {
           /* Flush if we moved to another psLevel, i.e. page table */
           if (psPrevLevel != NULL)
           {
               psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                                      &psPrevLevel->sMemDesc.psMapping->sMemHandle,
                                                      uiFlushStart * psConfig->uiBytesPerEntry + psPrevLevel->sMemDesc.uiOffset,
                                                      (uiFlushEnd+1 - uiFlushStart) * psConfig->uiBytesPerEntry);
           }
 
           uiFlushStart = uiPTEIndex;
           uiFlushEnd = uiFlushStart;
       }
 
       HTBLOGK(HTB_SF_MMU_PAGE_OP_UNMAP,
           HTBLOG_U64_BITS_HIGH(sDevVAddr.uiAddr), HTBLOG_U64_BITS_LOW(sDevVAddr.uiAddr));
 
       /* Set the PT entry to invalid and poison it with a bad address */
       if (_SetupPTE(psMMUContext,
                     psLevel,
                     uiPTEIndex,
                     psConfig,
                     (bDummyBacking)?&sDummyPgDevPhysAddr:&gsBadDevPhyAddr,
                     bUnmap,
#if defined(PDUMP)
                     (bDummyBacking)?(psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName):NULL,
                     (bDummyBacking)?DUMMY_PAGE:NULL,
                     0U,
#endif
                     uiProtFlags) != PVRSRV_OK )
       {
           goto e0;
       }
 
       /* Check we haven't wrapped around */
       PVR_ASSERT(psLevel->ui32RefCount <= psLevel->ui32NumOfEntries);
       ui32Loop++;
       sDevVAddr.uiAddr += uiPageSize;
   }
 
   /* Flush the last level we touched */
   if (psLevel != NULL)
   {
       psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                              &psLevel->sMemDesc.psMapping->sMemHandle,
                                              uiFlushStart * psConfig->uiBytesPerEntry + psLevel->sMemDesc.uiOffset,
                                              (uiFlushEnd+1 - uiFlushStart) * psConfig->uiBytesPerEntry);
   }
 
   OSLockRelease(psMMUContext->hLock);
 
   _MMU_PutPTConfig(psMMUContext, hPriv);
 
   /* Flush TLB for PTs*/
   psMMUContext->psDevNode->pfnMMUCacheInvalidate(psMMUContext->psDevNode,
                                                  psMMUContext->hDevData,
                                                  MMU_LEVEL_1,
                                                  IMG_TRUE);
 
   return;
 
e0:
   _MMU_PutPTConfig(psMMUContext, hPriv);
   PVR_DPF((PVR_DBG_ERROR, "MMU_UnmapPages: Failed to map/unmap page table"));
   PVR_ASSERT(0);
   OSLockRelease(psMMUContext->hLock);
   return;
}
 
PVRSRV_ERROR
MMU_MapPMRFast (MMU_CONTEXT *psMMUContext,
            IMG_DEV_VIRTADDR sDevVAddrBase,
            const PMR *psPMR,
            IMG_DEVMEM_SIZE_T uiSizeBytes,
            PVRSRV_MEMALLOCFLAGS_T uiMappingFlags,
            IMG_UINT32 uiLog2PageSize)
{
   PVRSRV_ERROR eError = PVRSRV_OK;
   IMG_UINT32 uiCount, i;
   IMG_UINT32 uiPageSize = 1 << uiLog2PageSize;
   IMG_UINT32 uiPTEIndex = 0;
   IMG_UINT64 uiProtFlags;
   MMU_PROTFLAGS_T uiMMUProtFlags = 0;
   MMU_Levelx_INFO *psLevel = NULL;
   IMG_HANDLE hPriv;
   const MMU_PxE_CONFIG *psConfig;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
   IMG_DEV_VIRTADDR sDevVAddr = sDevVAddrBase;
   IMG_DEV_PHYADDR asDevPAddr[PMR_MAX_TRANSLATION_STACK_ALLOC];
   IMG_BOOL abValid[PMR_MAX_TRANSLATION_STACK_ALLOC];
   IMG_DEV_PHYADDR *psDevPAddr;
   IMG_BOOL *pbValid;
   IMG_UINT32 uiFlushStart = 0;
 
#if defined(PDUMP)
   IMG_CHAR aszMemspaceName[PHYSMEM_PDUMP_MEMSPACE_MAX_LENGTH];
   IMG_CHAR aszSymbolicAddress[PHYSMEM_PDUMP_SYMNAME_MAX_LENGTH];
   IMG_DEVMEM_OFFSET_T uiSymbolicAddrOffset;
   IMG_UINT32 ui32MappedCount = 0;
   PDUMPCOMMENT("Wire up Page Table entries to point to the Data Pages (%lld bytes)", uiSizeBytes);
#endif /*PDUMP*/
 
   /* We should verify the size and contiguity when supporting variable page size */
 
   PVR_ASSERT (psMMUContext != NULL);
   PVR_ASSERT (psPMR != NULL);
 
 
   /* Allocate memory for page-frame-numbers and validity states,
      N.B. assert could be triggered by an illegal uiSizeBytes */
   uiCount = uiSizeBytes >> uiLog2PageSize;
   PVR_ASSERT((IMG_DEVMEM_OFFSET_T)uiCount << uiLog2PageSize == uiSizeBytes);
    if (uiCount > PMR_MAX_TRANSLATION_STACK_ALLOC)
    {
       psDevPAddr = OSAllocMem(uiCount * sizeof(IMG_DEV_PHYADDR));
       if (psDevPAddr == NULL)
       {
           PVR_DPF((PVR_DBG_ERROR, "Failed to allocate PMR device PFN list"));
           eError = PVRSRV_ERROR_OUT_OF_MEMORY;
           goto e0;
       }
 
       pbValid = OSAllocMem(uiCount * sizeof(IMG_BOOL));
       if (pbValid == NULL)
       {
           /* Should allocation fail, clean-up here before exit */
           PVR_DPF((PVR_DBG_ERROR, "Failed to allocate PMR device PFN state"));
           eError = PVRSRV_ERROR_OUT_OF_MEMORY;
           OSFreeMem(psDevPAddr);
           goto e0;
       }
    }
   else
   {
       psDevPAddr = asDevPAddr;
       pbValid    = abValid;
   }
 
   /* Get general PT and address configs */
   _MMU_GetPTConfig(psMMUContext, (IMG_UINT32) uiLog2PageSize,
                    &psConfig, &hPriv, &psDevVAddrConfig);
 
   _MMU_ConvertDevMemFlags(IMG_FALSE,
                           uiMappingFlags,
                           &uiMMUProtFlags,
                           psMMUContext);
 
   /* Callback to get device specific protection flags */
 
   if (psConfig->uiBytesPerEntry == 8)
   {
       uiProtFlags = psMMUContext->psDevAttrs->pfnDerivePTEProt8(uiMMUProtFlags , uiLog2PageSize);
   }
   else if (psConfig->uiBytesPerEntry == 4)
   {
       uiProtFlags = psMMUContext->psDevAttrs->pfnDerivePTEProt4(uiMMUProtFlags);
   }
   else
   {
       PVR_DPF((PVR_DBG_ERROR,"%s: The page table entry byte length is not supported", __func__));
       eError = PVRSRV_ERROR_MMU_CONFIG_IS_WRONG;
       goto e1;
   }
 
 
   /* "uiSize" is the amount of contiguity in the underlying
      page.  Normally this would be constant for the system, but,
      that constant needs to be communicated, in case it's ever
      different; caller guarantees that PMRLockSysPhysAddr() has
      already been called */
   eError = PMR_DevPhysAddr(psPMR,
                            uiLog2PageSize,
                            uiCount,
                            0,
                            psDevPAddr,
                            pbValid);
   if (eError != PVRSRV_OK)
   {
       goto e1;
   }
 
   OSLockAcquire(psMMUContext->hLock);
 
   _MMU_GetPTInfo(psMMUContext, sDevVAddr, psDevVAddrConfig,
                  &psLevel, &uiPTEIndex);
   uiFlushStart = uiPTEIndex;
 
   /* Map in all pages of that PMR page by page*/
   for (i=0, uiCount=0; uiCount < uiSizeBytes; i++)
   {
#if defined(DEBUG)
{
   IMG_INT32    i32FeatureVal = 0;
   IMG_UINT32 ui32BitLength = FloorLog2(psDevPAddr[i].uiAddr);
   i32FeatureVal = psMMUContext->psDevNode->pfnGetDeviceFeatureValue(psMMUContext->psDevNode, \
           RGX_FEATURE_PHYS_BUS_WIDTH_BIT_MASK);
   do {
       if(0 > i32FeatureVal)
           break;
 
       if (ui32BitLength > i32FeatureVal )
       {
           PVR_DPF((PVR_DBG_ERROR,"_MMU_MapPage Failed. The physical address bitlength (%d) "
                   "is greater than what the chip can handle (%d).",
                   ui32BitLength, i32FeatureVal));
 
           PVR_ASSERT(ui32BitLength <= i32FeatureVal );
           eError = PVRSRV_ERROR_INVALID_PARAMS;
           OSLockRelease(psMMUContext->hLock);
           goto e1;
       }
   }while(0);
}
#endif /*DEBUG*/
#if defined(PDUMP)
       {
           IMG_DEVMEM_OFFSET_T uiNextSymName;
 
           eError = PMR_PDumpSymbolicAddr(psPMR, uiCount,
                                          sizeof(aszMemspaceName), &aszMemspaceName[0],
                                          sizeof(aszSymbolicAddress), &aszSymbolicAddress[0],
                                          &uiSymbolicAddrOffset,
                                          &uiNextSymName);
           PVR_ASSERT(eError == PVRSRV_OK);
           ui32MappedCount++;
       }
#endif /*PDUMP*/
 
       HTBLOGK(HTB_SF_MMU_PAGE_OP_PMRMAP,
           HTBLOG_U64_BITS_HIGH(sDevVAddr.uiAddr), HTBLOG_U64_BITS_LOW(sDevVAddr.uiAddr),
           HTBLOG_U64_BITS_HIGH(psDevPAddr[i].uiAddr), HTBLOG_U64_BITS_LOW(psDevPAddr[i].uiAddr));
 
       /* Set the PT entry with the specified address and protection flags */
       eError = _SetupPTE(psMMUContext, psLevel, uiPTEIndex,
                          psConfig, &psDevPAddr[i], IMG_FALSE,
#if defined(PDUMP)
                          aszMemspaceName,
                          aszSymbolicAddress,
                          uiSymbolicAddrOffset,
#endif /*PDUMP*/
                          uiProtFlags);
       if (eError != PVRSRV_OK)
           goto e2;
 
       sDevVAddr.uiAddr += uiPageSize;
       uiCount += uiPageSize;
 
       /* Calculate PT index and get new table descriptor */
       if (uiPTEIndex < (psDevVAddrConfig->uiNumEntriesPT - 1) && (uiCount != uiSizeBytes))
       {
           uiPTEIndex++;
       }
       else
       {
           eError = psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                                           &psLevel->sMemDesc.psMapping->sMemHandle,
                                                           uiFlushStart * psConfig->uiBytesPerEntry + psLevel->sMemDesc.uiOffset,
                                                           (uiPTEIndex+1 - uiFlushStart) * psConfig->uiBytesPerEntry);
           if (eError != PVRSRV_OK)
               goto e2;
 
 
           _MMU_GetPTInfo(psMMUContext, sDevVAddr, psDevVAddrConfig,
                          &psLevel, &uiPTEIndex);
           uiFlushStart = uiPTEIndex;
       }
   }
 
   OSLockRelease(psMMUContext->hLock);
 
 
   _MMU_PutPTConfig(psMMUContext, hPriv);
 
   if (psDevPAddr != asDevPAddr)
   {
       OSFreeMem(pbValid);
       OSFreeMem(psDevPAddr);
   }
 
   /* Flush TLB for PTs*/
   psMMUContext->psDevNode->pfnMMUCacheInvalidate(psMMUContext->psDevNode,
                                                  psMMUContext->hDevData,
                                                  MMU_LEVEL_1,
                                                  IMG_FALSE);
 
#if defined(PDUMP)
   PDUMPCOMMENT("Wired up %d Page Table entries (out of %d)", ui32MappedCount, i);
#endif /*PDUMP*/
 
   return PVRSRV_OK;
 
e2:
   OSLockRelease(psMMUContext->hLock);
   MMU_UnmapPMRFast(psMMUContext,
                    sDevVAddrBase,
                    uiSizeBytes >> uiLog2PageSize,
                    uiLog2PageSize);
e1:
   _MMU_PutPTConfig(psMMUContext, hPriv);
 
   if (psDevPAddr != asDevPAddr)
   {
       OSFreeMem(pbValid);
       OSFreeMem(psDevPAddr);
   }
e0:
   PVR_ASSERT(eError == PVRSRV_OK);
    return eError;
}
 
/*
    MMU_UnmapPages
*/
void
MMU_UnmapPMRFast(MMU_CONTEXT *psMMUContext,
                 IMG_DEV_VIRTADDR sDevVAddrBase,
                 IMG_UINT32 ui32PageCount,
                 IMG_UINT32 uiLog2PageSize)
{
   IMG_UINT32 uiPTEIndex = 0, ui32Loop=0;
   IMG_UINT32 uiPageSize = 1 << uiLog2PageSize;
   MMU_Levelx_INFO *psLevel = NULL;
   IMG_HANDLE hPriv;
   const MMU_PxE_CONFIG *psConfig;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
   IMG_DEV_VIRTADDR sDevVAddr = sDevVAddrBase;
   IMG_UINT64 uiProtFlags = 0;
   MMU_PROTFLAGS_T uiMMUProtFlags = 0;
   IMG_UINT64 uiEntry = 0;
   IMG_UINT32 uiFlushStart = 0;
 
#if defined(PDUMP)
   PDUMPCOMMENT("Invalidate %d entries in page tables for virtual range: 0x%010llX to 0x%010llX",
                ui32PageCount,
                (IMG_UINT64)sDevVAddr.uiAddr,
                ((IMG_UINT64)sDevVAddr.uiAddr) + (uiPageSize*ui32PageCount)-1);
#endif
 
   /* Get PT and address configs */
   _MMU_GetPTConfig(psMMUContext, (IMG_UINT32) uiLog2PageSize,
                    &psConfig, &hPriv, &psDevVAddrConfig);
 
   _MMU_ConvertDevMemFlags(IMG_TRUE,
                           0,
                           &uiMMUProtFlags,
                           psMMUContext);
 
   /* Callback to get device specific protection flags */
 
   if (psConfig->uiBytesPerEntry == 8)
   {
       uiProtFlags = psMMUContext->psDevAttrs->pfnDerivePTEProt8(uiMMUProtFlags , uiLog2PageSize);
 
       /* Fill the entry with a bad address but leave space for protection flags */
       uiEntry = (gsBadDevPhyAddr.uiAddr & ~psConfig->uiProtMask) | uiProtFlags;
   }
   else if (psConfig->uiBytesPerEntry == 4)
   {
       uiProtFlags = psMMUContext->psDevAttrs->pfnDerivePTEProt4(uiMMUProtFlags);
 
       /* Fill the entry with a bad address but leave space for protection flags */
       uiEntry = (((IMG_UINT32) gsBadDevPhyAddr.uiAddr) & ~psConfig->uiProtMask) | (IMG_UINT32) uiProtFlags;
   }
   else
   {
       PVR_DPF((PVR_DBG_ERROR,"%s: The page table entry byte length is not supported", __func__));
       goto e0;
   }
 
   OSLockAcquire(psMMUContext->hLock);
 
   _MMU_GetPTInfo(psMMUContext, sDevVAddr, psDevVAddrConfig,
                  &psLevel, &uiPTEIndex);
   uiFlushStart = uiPTEIndex;
 
   /* Unmap page by page and keep the loop as quick as possible.
    * Only use parts of _SetupPTE that need to be executed. */
   while (ui32Loop < ui32PageCount)
   {
 
       /* Set the PT entry to invalid and poison it with a bad address */
       if (psConfig->uiBytesPerEntry == 8)
       {
           ((IMG_UINT64*) psLevel->sMemDesc.pvCpuVAddr)[uiPTEIndex] = uiEntry;
       }
       else if (psConfig->uiBytesPerEntry == 4)
       {
           ((IMG_UINT32*) psLevel->sMemDesc.pvCpuVAddr)[uiPTEIndex] = (IMG_UINT32) uiEntry;
       }
       else
       {
           PVR_DPF((PVR_DBG_ERROR,"%s: The page table entry byte length is not supported", __func__));
           goto e1;
       }
 
       /* Log modifications */
       HTBLOGK(HTB_SF_MMU_PAGE_OP_UNMAP,
           HTBLOG_U64_BITS_HIGH(sDevVAddr.uiAddr), HTBLOG_U64_BITS_LOW(sDevVAddr.uiAddr));
 
       HTBLOGK(HTB_SF_MMU_PAGE_OP_TABLE,
           HTBLOG_PTR_BITS_HIGH(psLevel), HTBLOG_PTR_BITS_LOW(psLevel),
           uiPTEIndex, MMU_LEVEL_1,
           HTBLOG_U64_BITS_HIGH(uiEntry), HTBLOG_U64_BITS_LOW(uiEntry),
           IMG_FALSE);
 
#if defined (PDUMP)
       PDumpMMUDumpPxEntries(MMU_LEVEL_1,
                             psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName,
                             psLevel->sMemDesc.pvCpuVAddr,
                             psLevel->sMemDesc.sDevPAddr,
                             uiPTEIndex,
                             1,
                             NULL,
                             NULL,
                             0,
                             psConfig->uiBytesPerEntry,
                             psConfig->uiAddrLog2Align,
                             psConfig->uiAddrShift,
                             psConfig->uiAddrMask,
                             psConfig->uiProtMask,
                             psConfig->uiValidEnMask,
                             0,
                             psMMUContext->psDevAttrs->eMMUType);
#endif /*PDUMP*/
 
       sDevVAddr.uiAddr += uiPageSize;
       ui32Loop++;
 
       /* Calculate PT index and get new table descriptor */
       if (uiPTEIndex < (psDevVAddrConfig->uiNumEntriesPT - 1) && (ui32Loop != ui32PageCount))
       {
           uiPTEIndex++;
       }
       else
       {
           psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                                  &psLevel->sMemDesc.psMapping->sMemHandle,
                                                  uiFlushStart * psConfig->uiBytesPerEntry + psLevel->sMemDesc.uiOffset,
                                                  (uiPTEIndex+1 - uiFlushStart) * psConfig->uiBytesPerEntry);
 
           _MMU_GetPTInfo(psMMUContext, sDevVAddr, psDevVAddrConfig,
                          &psLevel, &uiPTEIndex);
           uiFlushStart = uiPTEIndex;
       }
   }
 
   OSLockRelease(psMMUContext->hLock);
 
   _MMU_PutPTConfig(psMMUContext, hPriv);
 
   /* Flush TLB for PTs*/
   psMMUContext->psDevNode->pfnMMUCacheInvalidate(psMMUContext->psDevNode,
                                                  psMMUContext->hDevData,
                                                  MMU_LEVEL_1,
                                                  IMG_TRUE);
 
   return;
 
e1:
   OSLockRelease(psMMUContext->hLock);
   _MMU_PutPTConfig(psMMUContext, hPriv);
e0:
   PVR_DPF((PVR_DBG_ERROR, "MMU_UnmapPages: Failed to map/unmap page table"));
   PVR_ASSERT(0);
   return;
}
 
/*
   MMU_ChangeValidity
*/
PVRSRV_ERROR
MMU_ChangeValidity(MMU_CONTEXT *psMMUContext,
                   IMG_DEV_VIRTADDR sDevVAddr,
                   IMG_DEVMEM_SIZE_T uiNumPages,
                   IMG_UINT32 uiLog2PageSize,
                   IMG_BOOL bMakeValid,
                   PMR *psPMR)
{
    PVRSRV_ERROR eError = PVRSRV_OK;
 
   IMG_HANDLE hPriv;
   const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
   const MMU_PxE_CONFIG *psConfig;
   MMU_Levelx_INFO *psLevel = NULL;
   IMG_UINT32 uiFlushStart = 0;
   IMG_UINT32 uiPTIndex = 0;
   IMG_UINT32 i;
   IMG_UINT32 uiPageSize = 1 << uiLog2PageSize;
   IMG_BOOL bValid;
 
#if defined(PDUMP)
   IMG_CHAR aszMemspaceName[PHYSMEM_PDUMP_MEMSPACE_MAX_LENGTH];
   IMG_CHAR aszSymbolicAddress[PHYSMEM_PDUMP_SYMNAME_MAX_LENGTH];
   IMG_DEVMEM_OFFSET_T uiSymbolicAddrOffset;
   IMG_DEVMEM_OFFSET_T uiNextSymName;
 
   PDUMPCOMMENT("Change valid bit of the data pages to %d (0x%llX - 0x%llX)",
           bMakeValid,
           sDevVAddr.uiAddr,
           sDevVAddr.uiAddr + (uiNumPages<<uiLog2PageSize) - 1 );
#endif /*PDUMP*/
 
   /* We should verify the size and contiguity when supporting variable page size */
   PVR_ASSERT (psMMUContext != NULL);
   PVR_ASSERT (psPMR != NULL);
 
   /* Get general PT and address configs */
   _MMU_GetPTConfig(psMMUContext, (IMG_UINT32) uiLog2PageSize,
                    &psConfig, &hPriv, &psDevVAddrConfig);
 
   _MMU_GetPTInfo(psMMUContext, sDevVAddr, psDevVAddrConfig,
                   &psLevel, &uiPTIndex);
   uiFlushStart = uiPTIndex;
 
   /* Do a page table walk and change attribute for every page in range. */
   for (i=0; i < uiNumPages; )
   {
 
       /* Set the entry */
       if (bMakeValid == IMG_TRUE)
       {
           /* Only set valid if physical address exists (sparse allocs might have none)*/
           eError = PMR_IsOffsetValid(psPMR, uiLog2PageSize, 1, i<<uiLog2PageSize, &bValid);
           if (eError != PVRSRV_OK)
           {
               PVR_DPF((PVR_DBG_ERROR, "Cannot determine validity of page table entries page"));
               goto e_exit;
           }
 
           if (bValid)
           {
               if (psConfig->uiBytesPerEntry == 8)
               {
                   ((IMG_UINT64 *) psLevel->sMemDesc.pvCpuVAddr)[uiPTIndex] |= (psConfig->uiValidEnMask);
               }
               else if (psConfig->uiBytesPerEntry == 4)
               {
                   ((IMG_UINT32 *) psLevel->sMemDesc.pvCpuVAddr)[uiPTIndex] |= (psConfig->uiValidEnMask);
               }
               else
               {
                   eError = PVRSRV_ERROR_MMU_CONFIG_IS_WRONG;
                   PVR_DPF((PVR_DBG_ERROR, "Cannot change page table entries due to wrong configuration"));
                   goto e_exit;
               }
           }
       }
       else
       {
           if (psConfig->uiBytesPerEntry == 8)
           {
               ((IMG_UINT64 *) psLevel->sMemDesc.pvCpuVAddr)[uiPTIndex] &= ~(psConfig->uiValidEnMask);
           }
           else if (psConfig->uiBytesPerEntry == 4)
           {
               ((IMG_UINT32 *) psLevel->sMemDesc.pvCpuVAddr)[uiPTIndex] &= ~(psConfig->uiValidEnMask);
           }
           else
           {
               eError = PVRSRV_ERROR_MMU_CONFIG_IS_WRONG;
               PVR_DPF((PVR_DBG_ERROR, "Cannot change page table entries due to wrong configuration"));
               goto e_exit;
           }
       }
 
#if defined(PDUMP)
       PMR_PDumpSymbolicAddr(psPMR, i<<uiLog2PageSize,
                             sizeof(aszMemspaceName), &aszMemspaceName[0],
                             sizeof(aszSymbolicAddress), &aszSymbolicAddress[0],
                             &uiSymbolicAddrOffset,
                             &uiNextSymName);
 
       PDumpMMUDumpPxEntries(MMU_LEVEL_1,
                             psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName,
                             psLevel->sMemDesc.pvCpuVAddr,
                             psLevel->sMemDesc.sDevPAddr,
                             uiPTIndex,
                             1,
                             aszMemspaceName,
                             aszSymbolicAddress,
                             uiSymbolicAddrOffset,
                             psConfig->uiBytesPerEntry,
                             psConfig->uiAddrLog2Align,
                             psConfig->uiAddrShift,
                             psConfig->uiAddrMask,
                             psConfig->uiProtMask,
                             psConfig->uiValidEnMask,
                             0,
                             psMMUContext->psDevAttrs->eMMUType);
#endif /*PDUMP*/
 
       sDevVAddr.uiAddr += uiPageSize;
       i++;
 
       /* Calculate PT index and get new table descriptor */
       if (uiPTIndex < (psDevVAddrConfig->uiNumEntriesPT - 1) && (i != uiNumPages))
       {
           uiPTIndex++;
       }
       else
       {
 
           eError = psMMUContext->psDevNode->pfnDevPxClean(psMMUContext->psDevNode,
                                                           &psLevel->sMemDesc.psMapping->sMemHandle,
                                                           uiFlushStart * psConfig->uiBytesPerEntry + psLevel->sMemDesc.uiOffset,
                                                           (uiPTIndex+1 - uiFlushStart) * psConfig->uiBytesPerEntry);
           if (eError != PVRSRV_OK)
               goto e_exit;
 
           _MMU_GetPTInfo(psMMUContext, sDevVAddr, psDevVAddrConfig,
                          &psLevel, &uiPTIndex);
           uiFlushStart = uiPTIndex;
       }
   }
 
e_exit:
 
   _MMU_PutPTConfig(psMMUContext, hPriv);
 
   /* Flush TLB for PTs*/
   psMMUContext->psDevNode->pfnMMUCacheInvalidate(psMMUContext->psDevNode,
                                                  psMMUContext->hDevData,
                                                  MMU_LEVEL_1,
                                                  !bMakeValid);
 
   PVR_ASSERT(eError == PVRSRV_OK);
    return eError;
}
 
 
/*
   MMU_AcquireBaseAddr
*/
PVRSRV_ERROR
MMU_AcquireBaseAddr(MMU_CONTEXT *psMMUContext, IMG_DEV_PHYADDR *psPhysAddr)
{
   if (!psMMUContext)
       return PVRSRV_ERROR_INVALID_PARAMS;
 
   *psPhysAddr = psMMUContext->sBaseLevelInfo.sMemDesc.sDevPAddr;
   return PVRSRV_OK;
}
 
/*
   MMU_ReleaseBaseAddr
*/
void
MMU_ReleaseBaseAddr(MMU_CONTEXT *psMMUContext)
{
   PVR_UNREFERENCED_PARAMETER(psMMUContext);
}
 
/*
   MMU_SetDeviceData
*/
void MMU_SetDeviceData(MMU_CONTEXT *psMMUContext, IMG_HANDLE hDevData)
{
   psMMUContext->hDevData = hDevData;
}
 
#if defined(SUPPORT_GPUVIRT_VALIDATION)
/*
    MMU_SetOSid, MMU_GetOSid
*/
 
void MMU_SetOSids(MMU_CONTEXT *psMMUContext, IMG_UINT32 ui32OSid, IMG_UINT32 ui32OSidReg, IMG_BOOL bOSidAxiProt)
{
    psMMUContext->ui32OSid     = ui32OSid;
    psMMUContext->ui32OSidReg  = ui32OSidReg;
    psMMUContext->bOSidAxiProt = bOSidAxiProt;
 
    return ;
}
 
void MMU_GetOSids(MMU_CONTEXT *psMMUContext, IMG_UINT32 *pui32OSid, IMG_UINT32 *pui32OSidReg, IMG_BOOL *pbOSidAxiProt)
{
    *pui32OSid     = psMMUContext->ui32OSid;
    *pui32OSidReg  = psMMUContext->ui32OSidReg;
    *pbOSidAxiProt = psMMUContext->bOSidAxiProt;
 
    return ;
}
 
#endif
 
/*
   MMU_CheckFaultAddress
*/
void MMU_CheckFaultAddress(MMU_CONTEXT *psMMUContext,
               IMG_DEV_VIRTADDR *psDevVAddr,
               DUMPDEBUG_PRINTF_FUNC *pfnDumpDebugPrintf,
               void *pvDumpDebugFile)
{
   MMU_DEVICEATTRIBS *psDevAttrs = psMMUContext->psDevAttrs;
   const MMU_PxE_CONFIG *psConfig;
   const MMU_PxE_CONFIG *psMMUPDEConfig;
   const MMU_PxE_CONFIG *psMMUPTEConfig;
   const MMU_DEVVADDR_CONFIG *psMMUDevVAddrConfig;
   IMG_HANDLE hPriv;
   MMU_Levelx_INFO *psLevel = NULL;
   PVRSRV_ERROR eError;
   IMG_UINT64 uiIndex;
   IMG_UINT32 ui32PCIndex;
   IMG_UINT32 ui32PDIndex;
   IMG_UINT32 ui32PTIndex;
   IMG_UINT32 ui32Log2PageSize;
 
   OSLockAcquire(psMMUContext->hLock);
 
   /*
       At this point we don't know the page size so assume it's 4K.
       When we get the PD level (MMU_LEVEL_2) we can check to see
       if this assumption is correct.
   */
   eError = psDevAttrs->pfnGetPageSizeConfiguration(12,
                                                    &psMMUPDEConfig,
                                                    &psMMUPTEConfig,
                                                    &psMMUDevVAddrConfig,
                                                    &hPriv);
   if (eError != PVRSRV_OK)
   {
       PVR_LOG(("Failed to get the page size info for log2 page sizeof 12"));
   }
 
   psLevel = &psMMUContext->sBaseLevelInfo;
   psConfig = psDevAttrs->psBaseConfig;
 
   switch(psMMUContext->psDevAttrs->eTopLevel)
   {
       case MMU_LEVEL_3:
           /* Determine the PC index */
           uiIndex = psDevVAddr->uiAddr & psDevAttrs->psTopLevelDevVAddrConfig->uiPCIndexMask;
           uiIndex = uiIndex >> psDevAttrs->psTopLevelDevVAddrConfig->uiPCIndexShift;
           ui32PCIndex = (IMG_UINT32) uiIndex;
           PVR_ASSERT(uiIndex == ((IMG_UINT64) ui32PCIndex));
           
           if (ui32PCIndex >= psLevel->ui32NumOfEntries)
           {
               PVR_DUMPDEBUG_LOG("PC index (%d) out of bounds (%d)", ui32PCIndex, psLevel->ui32NumOfEntries);
               break;
           }
 
           if (psConfig->uiBytesPerEntry == 4)
           {
               IMG_UINT32 *pui32Ptr = psLevel->sMemDesc.pvCpuVAddr;
 
               PVR_DUMPDEBUG_LOG("PCE for index %d = 0x%08x and %s be valid",
                        ui32PCIndex,
                        pui32Ptr[ui32PCIndex],
                        psLevel->apsNextLevel[ui32PCIndex]?"should":"should not");
           }
           else
           {
               IMG_UINT64 *pui64Ptr = psLevel->sMemDesc.pvCpuVAddr;
 
               PVR_DUMPDEBUG_LOG("PCE for index %d = 0x%016llx and %s be valid",
                        ui32PCIndex,
                        pui64Ptr[ui32PCIndex],
                        psLevel->apsNextLevel[ui32PCIndex]?"should":"should not");
           }
 
           psLevel = psLevel->apsNextLevel[ui32PCIndex];
           if (!psLevel)
           {
               break;
           }
           psConfig = psMMUPDEConfig;
           /* Fall through */
 
       case MMU_LEVEL_2:
           /* Determine the PD index */
           uiIndex = psDevVAddr->uiAddr & psDevAttrs->psTopLevelDevVAddrConfig->uiPDIndexMask;
           uiIndex = uiIndex >> psDevAttrs->psTopLevelDevVAddrConfig->uiPDIndexShift;
           ui32PDIndex = (IMG_UINT32) uiIndex;
           PVR_ASSERT(uiIndex == ((IMG_UINT64) ui32PDIndex));
 
           if (ui32PDIndex >= psLevel->ui32NumOfEntries)
           {
               PVR_DUMPDEBUG_LOG("PD index (%d) out of bounds (%d)", ui32PDIndex, psLevel->ui32NumOfEntries);
               break;
           }
 
           if (psConfig->uiBytesPerEntry == 4)
           {
               IMG_UINT32 *pui32Ptr = psLevel->sMemDesc.pvCpuVAddr;
 
               PVR_DUMPDEBUG_LOG("PDE for index %d = 0x%08x and %s be valid",
                        ui32PDIndex,
                        pui32Ptr[ui32PDIndex],
                        psLevel->apsNextLevel[ui32PDIndex]?"should":"should not");
 
               if (psDevAttrs->pfnGetPageSizeFromPDE4(pui32Ptr[ui32PDIndex], &ui32Log2PageSize) != PVRSRV_OK)
               {
                   PVR_LOG(("Failed to get the page size from the PDE"));
               }
           }
           else
           {
               IMG_UINT64 *pui64Ptr = psLevel->sMemDesc.pvCpuVAddr;
 
               PVR_DUMPDEBUG_LOG("PDE for index %d = 0x%016llx and %s be valid",
                        ui32PDIndex,
                        pui64Ptr[ui32PDIndex],
                        psLevel->apsNextLevel[ui32PDIndex]?"should":"should not");
 
               if (psDevAttrs->pfnGetPageSizeFromPDE8(pui64Ptr[ui32PDIndex], &ui32Log2PageSize) != PVRSRV_OK)
               {
                   PVR_LOG(("Failed to get the page size from the PDE"));
               }
           }
 
           /*
               We assumed the page size was 4K, now we have the actual size
               from the PDE we can confirm if our assumption was correct.
               Until now it hasn't mattered as the PC and PD are the same
               regardless of the page size
           */
           if (ui32Log2PageSize != 12)
           {
               /* Put the 4K page size data */
               psDevAttrs->pfnPutPageSizeConfiguration(hPriv);
 
               /* Get the correct size data */
               eError = psDevAttrs->pfnGetPageSizeConfiguration(ui32Log2PageSize,
                                                                &psMMUPDEConfig,
                                                                &psMMUPTEConfig,
                                                                &psMMUDevVAddrConfig,
                                                                &hPriv);
               if (eError != PVRSRV_OK)
               {
                   PVR_LOG(("Failed to get the page size info for log2 page sizeof %d", ui32Log2PageSize));
                   break;
               }
           }
           psLevel = psLevel->apsNextLevel[ui32PDIndex];
           if (!psLevel)
           {
               break;
           }
           psConfig = psMMUPTEConfig;
           /* Fall through */
 
       case MMU_LEVEL_1:
           /* Determine the PT index */
           uiIndex = psDevVAddr->uiAddr & psMMUDevVAddrConfig->uiPTIndexMask;
           uiIndex = uiIndex >> psMMUDevVAddrConfig->uiPTIndexShift;
           ui32PTIndex = (IMG_UINT32) uiIndex;
           PVR_ASSERT(uiIndex == ((IMG_UINT64) ui32PTIndex));
 
           if (ui32PTIndex >= psLevel->ui32NumOfEntries)
           {
               PVR_DUMPDEBUG_LOG("PT index (%d) out of bounds (%d)", ui32PTIndex, psLevel->ui32NumOfEntries);
               break;
           }
 
           if (psConfig->uiBytesPerEntry == 4)
           {
               IMG_UINT32 *pui32Ptr = psLevel->sMemDesc.pvCpuVAddr;
 
               PVR_DUMPDEBUG_LOG("PTE for index %d = 0x%08x",
                        ui32PTIndex,
                        pui32Ptr[ui32PTIndex]);
           }
           else
           {
               IMG_UINT64 *pui64Ptr = psLevel->sMemDesc.pvCpuVAddr;
 
               PVR_DUMPDEBUG_LOG("PTE for index %d = 0x%016llx",
                        ui32PTIndex,
                        pui64Ptr[ui32PTIndex]);
           }
 
           break;
           default:
               PVR_LOG(("Unsupported MMU setup"));
               break;
   }
 
   OSLockRelease(psMMUContext->hLock);
}
 
IMG_BOOL MMU_IsVDevAddrValid(MMU_CONTEXT *psMMUContext,
                             IMG_UINT32 uiLog2PageSize,
                             IMG_DEV_VIRTADDR sDevVAddr)
{
    MMU_Levelx_INFO *psLevel = NULL;
    const MMU_PxE_CONFIG *psConfig;
    const MMU_DEVVADDR_CONFIG *psDevVAddrConfig;
    IMG_HANDLE hPriv;
    IMG_UINT32 uiIndex = 0;
    IMG_BOOL bStatus = IMG_FALSE;
 
    _MMU_GetPTConfig(psMMUContext, uiLog2PageSize, &psConfig, &hPriv, &psDevVAddrConfig);
 
    OSLockAcquire(psMMUContext->hLock);
 
    switch(psMMUContext->psDevAttrs->eTopLevel)
    {
        case MMU_LEVEL_3:
            uiIndex = _CalcPCEIdx(sDevVAddr, psDevVAddrConfig, IMG_FALSE);
            psLevel = psMMUContext->sBaseLevelInfo.apsNextLevel[uiIndex];
            if (psLevel == NULL)
                break;
            /* fall through */
        case MMU_LEVEL_2:
            uiIndex = _CalcPDEIdx(sDevVAddr, psDevVAddrConfig, IMG_FALSE);
 
            if (psLevel != NULL)
                psLevel = psLevel->apsNextLevel[uiIndex];
            else
                psLevel = psMMUContext->sBaseLevelInfo.apsNextLevel[uiIndex];
 
            if (psLevel == NULL)
                break;
            /* fall through */
        case MMU_LEVEL_1:
            uiIndex = _CalcPTEIdx(sDevVAddr, psDevVAddrConfig, IMG_FALSE);
 
            if (psLevel == NULL)
                psLevel = &psMMUContext->sBaseLevelInfo;
 
            bStatus = ((IMG_UINT64 *) psLevel->sMemDesc.pvCpuVAddr)[uiIndex]
                      & psConfig->uiValidEnMask;
            break;
        default:
            PVR_LOG(("MMU_IsVDevAddrValid: Unsupported MMU setup"));
            break;
    }
 
    OSLockRelease(psMMUContext->hLock);
 
    _MMU_PutPTConfig(psMMUContext, hPriv);
 
    return bStatus;
}
 
#if defined(PDUMP)
/*
   MMU_ContextDerivePCPDumpSymAddr
*/
PVRSRV_ERROR MMU_ContextDerivePCPDumpSymAddr(MMU_CONTEXT *psMMUContext,
                                             IMG_CHAR *pszPDumpSymbolicNameBuffer,
                                             size_t uiPDumpSymbolicNameBufferSize)
{
    size_t uiCount;
    IMG_UINT64 ui64PhysAddr;
   PVRSRV_DEVICE_IDENTIFIER *psDevId = &psMMUContext->psDevNode->sDevId;
 
    if (!psMMUContext->sBaseLevelInfo.sMemDesc.bValid)
    {
        /* We don't have any allocations.  You're not allowed to ask
           for the page catalogue base address until you've made at
           least one allocation */
        return PVRSRV_ERROR_MMU_API_PROTOCOL_ERROR;
    }
 
    ui64PhysAddr = (IMG_UINT64)psMMUContext->sBaseLevelInfo.sMemDesc.sDevPAddr.uiAddr;
 
    PVR_ASSERT(uiPDumpSymbolicNameBufferSize >= (IMG_UINT32)(21 + OSStringLength(psDevId->pszPDumpDevName)));
 
    /* Page table Symbolic Name is formed from page table phys addr
       prefixed with MMUPT_. */
 
    uiCount = OSSNPrintf(pszPDumpSymbolicNameBuffer,
                         uiPDumpSymbolicNameBufferSize,
                         ":%s:%s%016llX",
                         psDevId->pszPDumpDevName,
                         psMMUContext->sBaseLevelInfo.sMemDesc.bValid?"MMUPC_":"XXX",
                         ui64PhysAddr);
 
    if (uiCount + 1 > uiPDumpSymbolicNameBufferSize)
    {
        return PVRSRV_ERROR_INVALID_PARAMS;
    }
 
    return PVRSRV_OK;
}
 
/*
   MMU_PDumpWritePageCatBase
*/
PVRSRV_ERROR
MMU_PDumpWritePageCatBase(MMU_CONTEXT *psMMUContext,
                          const IMG_CHAR *pszSpaceName,
                          IMG_DEVMEM_OFFSET_T uiOffset,
                          IMG_UINT32 ui32WordSize,
                          IMG_UINT32 ui32AlignShift,
                          IMG_UINT32 ui32Shift,
                          PDUMP_FLAGS_T uiPdumpFlags)
{
   PVRSRV_ERROR eError;
   IMG_CHAR aszPageCatBaseSymbolicAddr[100];
   const IMG_CHAR *pszPDumpDevName = psMMUContext->psDevAttrs->pszMMUPxPDumpMemSpaceName;
 
   eError = MMU_ContextDerivePCPDumpSymAddr(psMMUContext,
                                             &aszPageCatBaseSymbolicAddr[0],
                                             sizeof(aszPageCatBaseSymbolicAddr));
   if (eError ==  PVRSRV_OK)
   {
       eError = PDumpWriteSymbAddress(pszSpaceName,
                                      uiOffset,
                                      aszPageCatBaseSymbolicAddr,
                                      0, /* offset -- Could be non-zero for var. pgsz */
                                      pszPDumpDevName,
                                      ui32WordSize,
                                      ui32AlignShift,
                                      ui32Shift,
                                      uiPdumpFlags | PDUMP_FLAGS_CONTINUOUS);
   }
 
    return eError;
}
 
/*
   MMU_AcquirePDumpMMUContext
*/
PVRSRV_ERROR MMU_AcquirePDumpMMUContext(MMU_CONTEXT *psMMUContext,
                                        IMG_UINT32 *pui32PDumpMMUContextID)
{
   PVRSRV_DEVICE_IDENTIFIER *psDevId = &psMMUContext->psDevNode->sDevId;
 
   if (!psMMUContext->ui32PDumpContextIDRefCount)
   {
       PDUMP_MMU_ALLOC_MMUCONTEXT(psDevId->pszPDumpDevName,
                                           psMMUContext->sBaseLevelInfo.sMemDesc.sDevPAddr,
                                           psMMUContext->psDevAttrs->eMMUType,
                                           &psMMUContext->uiPDumpContextID);
   }
 
   psMMUContext->ui32PDumpContextIDRefCount++;
   *pui32PDumpMMUContextID = psMMUContext->uiPDumpContextID;
 
   return PVRSRV_OK;
}
 
/*
   MMU_ReleasePDumpMMUContext
*/
PVRSRV_ERROR MMU_ReleasePDumpMMUContext(MMU_CONTEXT *psMMUContext)
{
   PVRSRV_DEVICE_IDENTIFIER *psDevId = &psMMUContext->psDevNode->sDevId;
 
   PVR_ASSERT(psMMUContext->ui32PDumpContextIDRefCount != 0);
   psMMUContext->ui32PDumpContextIDRefCount--;
 
   if (psMMUContext->ui32PDumpContextIDRefCount == 0)
   {
       PDUMP_MMU_FREE_MMUCONTEXT(psDevId->pszPDumpDevName,
                                   psMMUContext->uiPDumpContextID);
   }
 
   return PVRSRV_OK;
}
#endif
 
/******************************************************************************
 End of file (mmu_common.c)
******************************************************************************/