summaryrefslogtreecommitdiffstats
path: root/pvr-source/services4/srvkm/common/pdump_common.c
blob: 2d96dc3a7e328557542b69aa8727d0979ef62bf0 (plain)
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
/*************************************************************************/ /*!
@Title          Common PDump functions
@Copyright      Copyright (c) Imagination Technologies Ltd. All Rights Reserved
@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.
*/ /**************************************************************************/

#if defined(PDUMP)
#include <stdarg.h>

#include "services_headers.h"
#include "perproc.h"

/* pdump headers */
#include "pdump_km.h"
#include "pdump_int.h"

/* Allow temporary buffer size override */
#if !defined(PDUMP_TEMP_BUFFER_SIZE)
#define PDUMP_TEMP_BUFFER_SIZE (64 * 1024U)
#endif

/* DEBUG */
#if 1
#define PDUMP_DBG(a)   PDumpOSDebugPrintf (a)
#else
#define PDUMP_DBG(a)
#endif


#define	PTR_PLUS(t, p, x) ((t)(((IMG_CHAR *)(p)) + (x)))
#define	VPTR_PLUS(p, x) PTR_PLUS(IMG_VOID *, p, x)
#define	VPTR_INC(p, x) ((p) = VPTR_PLUS(p, x))
#define MAX_PDUMP_MMU_CONTEXTS	(32)
static IMG_VOID *gpvTempBuffer = IMG_NULL;
static IMG_HANDLE ghTempBufferBlockAlloc;
static IMG_UINT16 gui16MMUContextUsage = 0;

#if defined(PDUMP_DEBUG_OUTFILES)
/* counter increments each time debug write is called */
IMG_UINT32 g_ui32EveryLineCounter = 1U;
#endif

#ifdef INLINE_IS_PRAGMA
#pragma inline(_PDumpIsPersistent)
#endif
static INLINE
IMG_BOOL _PDumpIsPersistent(IMG_VOID)
{
	PVRSRV_PER_PROCESS_DATA* psPerProc = PVRSRVFindPerProcessData();

	if(psPerProc == IMG_NULL)
	{
		/* only occurs early in driver init, and init phase is already persistent */
		return IMG_FALSE;
	}
	return psPerProc->bPDumpPersistent;
}

#if defined(SUPPORT_PDUMP_MULTI_PROCESS)


static INLINE
IMG_BOOL _PDumpIsProcessActive(IMG_VOID)
{
	PVRSRV_PER_PROCESS_DATA* psPerProc = PVRSRVFindPerProcessData();
	if(psPerProc == IMG_NULL)
	{
		/* FIXME: kernel process logs some comments when kernel module is
		 * loaded, want to keep those.
		 */
		return IMG_TRUE;
	}
	return psPerProc->bPDumpActive;
}

#endif /* SUPPORT_PDUMP_MULTI_PROCESS */

#if defined(PDUMP_DEBUG_OUTFILES)
static INLINE
IMG_UINT32 _PDumpGetPID(IMG_VOID)
{
	PVRSRV_PER_PROCESS_DATA* psPerProc = PVRSRVFindPerProcessData();
	if(psPerProc == IMG_NULL)
	{
		/* Kernel PID */
		return 0;
	}
	return psPerProc->ui32PID;
}
#endif /* PDUMP_DEBUG_OUTFILES */

/**************************************************************************
 * Function Name  : GetTempBuffer
 * Inputs         : None
 * Outputs        : None
 * Returns        : Temporary buffer address, or IMG_NULL
 * Description    : Get temporary buffer address.
**************************************************************************/
static IMG_VOID *GetTempBuffer(IMG_VOID)
{
	/*
	 * Allocate the temporary buffer, it it hasn't been allocated already.
	 * Return the address of the temporary buffer, or IMG_NULL if it
	 * couldn't be allocated.
	 * It is expected that the buffer will be allocated once, at driver
	 * load time, and left in place until the driver unloads.
	 */

	if (gpvTempBuffer == IMG_NULL)
	{
		PVRSRV_ERROR eError = OSAllocMem(PVRSRV_OS_PAGEABLE_HEAP,
					  PDUMP_TEMP_BUFFER_SIZE,
					  &gpvTempBuffer,
					  &ghTempBufferBlockAlloc,
					  "PDUMP Temporary Buffer");
		if (eError != PVRSRV_OK)
		{
			PVR_DPF((PVR_DBG_ERROR, "GetTempBuffer: OSAllocMem failed: %d", eError));
		}
	}

	return gpvTempBuffer;
}

static IMG_VOID FreeTempBuffer(IMG_VOID)
{

	if (gpvTempBuffer != IMG_NULL)
	{
		PVRSRV_ERROR eError = OSFreeMem(PVRSRV_OS_PAGEABLE_HEAP,
					  PDUMP_TEMP_BUFFER_SIZE,
					  gpvTempBuffer,
					  ghTempBufferBlockAlloc);
		if (eError != PVRSRV_OK)
		{
			PVR_DPF((PVR_DBG_ERROR, "FreeTempBuffer: OSFreeMem failed: %d", eError));
		}
		else
		{
			gpvTempBuffer = IMG_NULL;
		}
	}
}

IMG_VOID PDumpInitCommon(IMG_VOID)
{
	/* Allocate temporary buffer for copying from user space */
	(IMG_VOID) GetTempBuffer();

	/* Call environment specific PDump initialisation */
	PDumpInit();
}

IMG_VOID PDumpDeInitCommon(IMG_VOID)
{
	/* Free temporary buffer */
	FreeTempBuffer();

	/* Call environment specific PDump Deinitialisation */
	PDumpDeInit();
}

IMG_BOOL PDumpIsSuspended(IMG_VOID)
{
	return PDumpOSIsSuspended();
}

IMG_BOOL PDumpIsCaptureFrameKM(IMG_VOID)
{
#if defined(SUPPORT_PDUMP_MULTI_PROCESS)
	if( _PDumpIsProcessActive() )
	{
		return PDumpOSIsCaptureFrameKM();
	}
	return IMG_FALSE;
#else
	return PDumpOSIsCaptureFrameKM();
#endif
}

PVRSRV_ERROR PDumpSetFrameKM(IMG_UINT32 ui32Frame)
{
#if defined(SUPPORT_PDUMP_MULTI_PROCESS)
	if( _PDumpIsProcessActive() )
	{
		return PDumpOSSetFrameKM(ui32Frame);
	}
	return PVRSRV_OK;
#else
	return PDumpOSSetFrameKM(ui32Frame);
#endif
}

/**************************************************************************
 * Function Name  : PDumpRegWithFlagsKM
 * Inputs         : pszPDumpDevName, Register offset, and value to write
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Create a PDUMP string, which represents a register write
**************************************************************************/
PVRSRV_ERROR PDumpRegWithFlagsKM(IMG_CHAR *pszPDumpRegName,
								IMG_UINT32 ui32Reg,
								IMG_UINT32 ui32Data,
								IMG_UINT32 ui32Flags)
{
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING()
	PDUMP_DBG(("PDumpRegWithFlagsKM"));

	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "WRW :%s:0x%08X 0x%08X\r\n",
								pszPDumpRegName, ui32Reg, ui32Data);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : PDumpRegKM
 * Inputs         : Register offset, and value to write
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Create a PDUMP string, which represents a register write
**************************************************************************/
PVRSRV_ERROR PDumpRegKM(IMG_CHAR *pszPDumpRegName,
						IMG_UINT32 ui32Reg,
						IMG_UINT32 ui32Data)
{
	return PDumpRegWithFlagsKM(pszPDumpRegName, ui32Reg, ui32Data, PDUMP_FLAGS_CONTINUOUS);
}

/**************************************************************************
 * Function Name  : PDumpRegPolWithFlagsKM
 * Inputs         : Description of what this register read is trying to do
 *					pszPDumpDevName
 *					Register offset
 *					expected value
 *					mask for that value
 * Outputs        : None
 * Returns        : None
 * Description    : Create a PDUMP string which represents a register read
 *					with the expected value
**************************************************************************/
PVRSRV_ERROR PDumpRegPolWithFlagsKM(IMG_CHAR *pszPDumpRegName,
									IMG_UINT32 ui32RegAddr, 
									IMG_UINT32 ui32RegValue, 
									IMG_UINT32 ui32Mask,
									IMG_UINT32 ui32Flags,
									PDUMP_POLL_OPERATOR	eOperator)
{
	/* Timings correct for linux and XP */
	#define POLL_DELAY			1000U
	#define POLL_COUNT_LONG		(2000000000U / POLL_DELAY)
	#define POLL_COUNT_SHORT	(1000000U / POLL_DELAY)

	PVRSRV_ERROR eErr;
	IMG_UINT32	ui32PollCount;

	PDUMP_GET_SCRIPT_STRING();
	PDUMP_DBG(("PDumpRegPolWithFlagsKM"));
	if ( _PDumpIsPersistent() )
	{
		/* Don't pdump-poll if the process is persistent */
		return PVRSRV_OK;
	}

	ui32PollCount = POLL_COUNT_LONG;

	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "POL :%s:0x%08X 0x%08X 0x%08X %d %u %d\r\n",
							pszPDumpRegName, ui32RegAddr, ui32RegValue,
							ui32Mask, eOperator, ui32PollCount, POLL_DELAY);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	return PVRSRV_OK;
}


/**************************************************************************
 * Function Name  : PDumpRegPol
 * Inputs         : Description of what this register read is trying to do
 *					pszPDumpDevName
 					Register offset
 *					expected value
 *					mask for that value
 * Outputs        : None
 * Returns        : None
 * Description    : Create a PDUMP string which represents a register read
 *					with the expected value
**************************************************************************/
PVRSRV_ERROR PDumpRegPolKM(IMG_CHAR *pszPDumpRegName, IMG_UINT32 ui32RegAddr, IMG_UINT32 ui32RegValue, IMG_UINT32 ui32Mask, PDUMP_POLL_OPERATOR	eOperator)
{
	return PDumpRegPolWithFlagsKM(pszPDumpRegName, ui32RegAddr, ui32RegValue, ui32Mask, PDUMP_FLAGS_CONTINUOUS, eOperator);
}

/**************************************************************************
 * Function Name  : PDumpMallocPages
 * Inputs         : psDevID, ui32DevVAddr, pvLinAddr, ui32NumBytes, hOSMemHandle
 *                : hUniqueTag
 * Outputs        : None
 * Returns        : None
 * Description    : Malloc memory pages

FIXME: This function assumes pvLinAddr is the address of the start of the 
block for this hOSMemHandle.
If this isn't true, the call to PDumpOSCPUVAddrToDevPAddr below will be 
incorrect.  (Consider using OSMemHandleToCPUPAddr() instead?)
The only caller at the moment is in buffer_manager.c, which does the right
thing.
**************************************************************************/
PVRSRV_ERROR PDumpMallocPages (PVRSRV_DEVICE_IDENTIFIER	*psDevID,
                           IMG_UINT32         ui32DevVAddr,
                           IMG_CPU_VIRTADDR   pvLinAddr,
                           IMG_HANDLE         hOSMemHandle,
                           IMG_UINT32         ui32NumBytes,
                           IMG_UINT32         ui32PageSize,
                           IMG_BOOL			  bShared,
                           IMG_HANDLE         hUniqueTag)
{
	PVRSRV_ERROR eErr;
	IMG_PUINT8		pui8LinAddr;
    IMG_UINT32      ui32Offset;
	IMG_UINT32		ui32NumPages;
	IMG_DEV_PHYADDR	sDevPAddr;
	IMG_UINT32		ui32Page;
	IMG_UINT32		ui32Flags = PDUMP_FLAGS_CONTINUOUS;

	PDUMP_GET_SCRIPT_STRING();
#if defined(SUPPORT_PDUMP_MULTI_PROCESS)
	/* Always dump physical pages backing a shared allocation */
	ui32Flags |= ( _PDumpIsPersistent() || bShared ) ? PDUMP_FLAGS_PERSISTENT : 0;
#else
	PVR_UNREFERENCED_PARAMETER(bShared);
	ui32Flags |= ( _PDumpIsPersistent() ) ? PDUMP_FLAGS_PERSISTENT : 0;
#endif

	/* However, lin addr is only required in non-linux OSes */
#if !defined(LINUX)
	PVR_ASSERT(((IMG_UINTPTR_T)pvLinAddr & HOST_PAGEMASK) == 0);
#endif

	PVR_ASSERT(((IMG_UINT32) ui32DevVAddr & HOST_PAGEMASK) == 0);
	PVR_ASSERT(((IMG_UINT32) ui32NumBytes & HOST_PAGEMASK) == 0);

	/*
		Write a comment to the PDump2 script streams indicating the memory allocation
	*/
	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "-- MALLOC :%s:VA_%08X 0x%08X %u\r\n",
			psDevID->pszPDumpDevName, ui32DevVAddr, ui32NumBytes, ui32PageSize);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	/*
		Write to the MMU script stream indicating the memory allocation
	*/
	pui8LinAddr = (IMG_PUINT8) pvLinAddr;
	ui32Offset = 0;
	ui32NumPages = ui32NumBytes / ui32PageSize;
	while (ui32NumPages)
	{ 
		ui32NumPages--;

		/* See FIXME in function header. 
		 * Currently:  linux pdump uses OSMemHandle and Offset 
		 *             other OSes use the LinAddr. 
		 */
 		/* Calculate the device physical address for this page */
		PDumpOSCPUVAddrToDevPAddr(psDevID->eDeviceType,
				hOSMemHandle,
				ui32Offset,
				pui8LinAddr,
				ui32PageSize,
				&sDevPAddr);
		ui32Page = (IMG_UINT32)(sDevPAddr.uiAddr / ui32PageSize);
		/* increment kernel virtual address */
		pui8LinAddr	+= ui32PageSize;
		ui32Offset += ui32PageSize;

		eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "MALLOC :%s:PA_%08X%08X %u %u 0x%08X\r\n",
												psDevID->pszPDumpDevName,
												(IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
												ui32Page * ui32PageSize,
												ui32PageSize,
												ui32PageSize,
												ui32Page * ui32PageSize);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
		PDumpOSWriteString2(hScript, ui32Flags);
	}
	return PVRSRV_OK;
}


/**************************************************************************
 * Function Name  : PDumpMallocPageTable
 * Inputs         : psDevId, pvLinAddr, ui32NumBytes, hUniqueTag
 * Outputs        : None
 * Returns        : None
 * Description    : Malloc memory page table
**************************************************************************/
PVRSRV_ERROR PDumpMallocPageTable (PVRSRV_DEVICE_IDENTIFIER	*psDevId,
								   IMG_HANDLE hOSMemHandle,
								   IMG_UINT32 ui32Offset,
                              	   IMG_CPU_VIRTADDR pvLinAddr,
								   IMG_UINT32 ui32PTSize,
								   IMG_UINT32 ui32Flags,
								   IMG_HANDLE hUniqueTag)
{
	PVRSRV_ERROR eErr;
	IMG_DEV_PHYADDR	sDevPAddr;

	PDUMP_GET_SCRIPT_STRING();

	PVR_ASSERT(((IMG_UINTPTR_T)pvLinAddr & (ui32PTSize - 1)) == 0);
	ui32Flags |= PDUMP_FLAGS_CONTINUOUS;
	ui32Flags |= ( _PDumpIsPersistent() ) ? PDUMP_FLAGS_PERSISTENT : 0;
	
	/*
		Write a comment to the PDump2 script streams indicating the memory allocation
	*/
	eErr = PDumpOSBufprintf(hScript,
							ui32MaxLen,
							"-- MALLOC :%s:PAGE_TABLE 0x%08X %u\r\n",
							psDevId->pszPDumpDevName,
							ui32PTSize,
							ui32PTSize);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	/*
		Write to the MMU script stream indicating the memory allocation
	*/
	// FIXME: we'll never need more than a 4k page for a pagetable
	// fixing to 1 page for now.
	// note: when the mmu code supports packed pagetables the PTs
	// will be as small as 16bytes

	PDumpOSCPUVAddrToDevPAddr(psDevId->eDeviceType,
			hOSMemHandle, /* um - does this mean the pvLinAddr would be ignored?  Is that safe? */
			ui32Offset,
			(IMG_PUINT8) pvLinAddr,
			ui32PTSize,
			&sDevPAddr);

	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "MALLOC :%s:PA_%08X%08X 0x%X %u 0x%08X\r\n",
											psDevId->pszPDumpDevName,
											(IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
											sDevPAddr.uiAddr,
											ui32PTSize,//size
											ui32PTSize,//alignment
											sDevPAddr.uiAddr);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : PDumpFreePages
 * Inputs         : psBMHeap, sDevVAddr, ui32NumBytes, hUniqueTag,
 					bInterLeaved
 * Outputs        : None
 * Returns        : None
 * Description    : Free memory pages
**************************************************************************/
PVRSRV_ERROR PDumpFreePages	(BM_HEAP 			*psBMHeap,
                         IMG_DEV_VIRTADDR  sDevVAddr,
                         IMG_UINT32        ui32NumBytes,
                         IMG_UINT32        ui32PageSize,
                         IMG_HANDLE        hUniqueTag,
						 IMG_BOOL		   bInterleaved,
						 IMG_BOOL		   bSparse)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32 ui32NumPages, ui32PageCounter;
	IMG_DEV_PHYADDR	sDevPAddr;
	IMG_UINT32 ui32Flags = PDUMP_FLAGS_CONTINUOUS;
	PVRSRV_DEVICE_NODE *psDeviceNode;

	PDUMP_GET_SCRIPT_STRING();

	PVR_ASSERT(((IMG_UINT32) sDevVAddr.uiAddr & (ui32PageSize - 1)) == 0);
	PVR_ASSERT(((IMG_UINT32) ui32NumBytes & (ui32PageSize - 1)) == 0);

	psDeviceNode = psBMHeap->pBMContext->psDeviceNode;
	ui32Flags |= ( _PDumpIsPersistent() ) ? PDUMP_FLAGS_PERSISTENT : 0;

	/*
		Write a comment to the PDUMP2 script streams indicating the memory free
	*/
	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "-- FREE :%s:VA_%08X\r\n", 
							psDeviceNode->sDevId.pszPDumpDevName, sDevVAddr.uiAddr);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

#if defined(SUPPORT_PDUMP_MULTI_PROCESS)
	/* if we're dumping a shared heap, need to ensure phys allocation
	 * is freed even if this app isn't the one marked for pdumping
	 */
	{
		PVRSRV_DEVICE_NODE *psDeviceNode = psBMHeap->pBMContext->psDeviceNode;
		
		if( psDeviceNode->pfnMMUIsHeapShared(psBMHeap->pMMUHeap) )
		{
			ui32Flags |= PDUMP_FLAGS_PERSISTENT;
		}
	}
#endif
	PDumpOSWriteString2(hScript, ui32Flags);

	/*
		Write to the MMU script stream indicating the memory free
	*/
	ui32NumPages = ui32NumBytes / ui32PageSize;
	for (ui32PageCounter = 0; ui32PageCounter < ui32NumPages; ui32PageCounter++)
	{
		if (!bInterleaved || (ui32PageCounter % 2) == 0)
		{
			sDevPAddr = psDeviceNode->pfnMMUGetPhysPageAddr(psBMHeap->pMMUHeap, sDevVAddr);

			/* With sparse mappings we expect spaces */
			if (bSparse && (sDevPAddr.uiAddr == 0))
			{
				continue;
			}

			PVR_ASSERT(sDevPAddr.uiAddr != 0);

			eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "FREE :%s:PA_%08X%08X\r\n",
									psDeviceNode->sDevId.pszPDumpDevName, (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag, sDevPAddr.uiAddr);
			if(eErr != PVRSRV_OK)
			{
				return eErr;
			}
			PDumpOSWriteString2(hScript, ui32Flags);
		}
		else
		{
			/* Gap pages in an interleaved allocation should be ignored. */
		}

		sDevVAddr.uiAddr += ui32PageSize;
	}
	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : PDumpFreePageTable
 * Inputs         : psDevID, pvLinAddr, ui32NumBytes, hUniqueTag
 * Outputs        : None
 * Returns        : None
 * Description    : Free memory page table
**************************************************************************/
PVRSRV_ERROR PDumpFreePageTable	(PVRSRV_DEVICE_IDENTIFIER *psDevID,
								 IMG_HANDLE hOSMemHandle,
								 IMG_CPU_VIRTADDR   pvLinAddr,
								 IMG_UINT32         ui32PTSize,
								 IMG_UINT32			ui32Flags,
								 IMG_HANDLE         hUniqueTag)
{
	PVRSRV_ERROR eErr;
	IMG_DEV_PHYADDR	sDevPAddr;

	PDUMP_GET_SCRIPT_STRING();

	PVR_UNREFERENCED_PARAMETER(ui32PTSize);
	ui32Flags |= PDUMP_FLAGS_CONTINUOUS;
	ui32Flags |= ( _PDumpIsPersistent() ) ? PDUMP_FLAGS_PERSISTENT : 0;

	/* override QAC warning about wrap around */
	PVR_ASSERT(((IMG_UINTPTR_T)pvLinAddr & (ui32PTSize-1UL)) == 0);	/* PRQA S 3382 */

	/*
		Write a comment to the PDUMP2 script streams indicating the memory free
	*/
	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "-- FREE :%s:PAGE_TABLE\r\n", psDevID->pszPDumpDevName);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	/*
		Write to the MMU script stream indicating the memory free
	*/
	// FIXME: we'll never need more than a 4k page for a pagetable
	// fixing to 1 page for now.
	// note: when the mmu code supports packed pagetables the PTs
	// will be as small as 16bytes

	PDumpOSCPUVAddrToDevPAddr(psDevID->eDeviceType,
							  hOSMemHandle, /* um - does this mean the pvLinAddr would be ignored?  Is that safe? */
			0,
			(IMG_PUINT8) pvLinAddr,
			ui32PTSize,
			&sDevPAddr);

	{
		eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "FREE :%s:PA_%08X%08X\r\n",
								psDevID->pszPDumpDevName,
								(IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
								sDevPAddr.uiAddr);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
		PDumpOSWriteString2(hScript, ui32Flags);
	}

	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : PDumpPDRegWithFlags
 * Inputs         : psMMUAttrib
 *				  : ui32Reg
 *				  : ui32Data
 *				  : hUniqueTag
 * Outputs        : None
 * Returns        : None
 * Description    : Kernel Services internal pdump memory API
 *					Used for registers specifying physical addresses
 					e.g. MMU page directory register
**************************************************************************/
PVRSRV_ERROR PDumpPDRegWithFlags(PDUMP_MMU_ATTRIB *psMMUAttrib,
							IMG_UINT32 ui32Reg,
							 IMG_UINT32 ui32Data,
							 IMG_UINT32	ui32Flags,
							 IMG_HANDLE hUniqueTag)
{
	PVRSRV_ERROR eErr;
	IMG_CHAR *pszRegString;
	PDUMP_GET_SCRIPT_STRING()
	
	if(psMMUAttrib->pszPDRegRegion != IMG_NULL)
	{	
		pszRegString = psMMUAttrib->pszPDRegRegion;
	}
	else
	{
		pszRegString = psMMUAttrib->sDevId.pszPDumpRegName;
	}

	/*
		Write to the MMU script stream indicating the physical page directory
	*/
#if defined(SGX_FEATURE_36BIT_MMU)
	eErr = PDumpOSBufprintf(hScript, ui32MaxLen,
			 "WRW :%s:$1 :%s:PA_%08X%08X:0x0\r\n",
			 psMMUAttrib->sDevId.pszPDumpDevName,
			 psMMUAttrib->sDevId.pszPDumpDevName,
			 (IMG_UINT32)hUniqueTag,
			 (ui32Data & psMMUAttrib->ui32PDEMask) << psMMUAttrib->ui32PDEAlignShift);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);
	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "SHR :%s:$1 :%s:$1 0x4\r\n", 
			psMMUAttrib->sDevId.pszPDumpDevName,
			psMMUAttrib->sDevId.pszPDumpDevName);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);
	eErr = PDumpOSBufprintf(hScript, ui32MaxLen,
			 "WRW :%s:0x%08X: %s:$1\r\n",
			 pszRegString,
			 ui32Reg,
			 psMMUAttrib->sDevId.pszPDumpDevName);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);
#else
	eErr = PDumpOSBufprintf(hScript,
				ui32MaxLen,
				"WRW :%s:0x%08X :%s:PA_%08X%08X:0x%08X\r\n",
				pszRegString,
				ui32Reg,
				psMMUAttrib->sDevId.pszPDumpDevName,
				(IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
				(ui32Data & psMMUAttrib->ui32PDEMask) << psMMUAttrib->ui32PDEAlignShift,
				ui32Data & ~psMMUAttrib->ui32PDEMask);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);
#endif
	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : PDumpPDReg
 * Inputs         : psMMUAttrib
 				  : ui32Reg
 *				  : ui32Data
 *				  : hUniqueTag
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Kernel Services internal pdump memory API
 *					Used for registers specifying physical addresses
 					e.g. MMU page directory register
**************************************************************************/
PVRSRV_ERROR PDumpPDReg	(PDUMP_MMU_ATTRIB *psMMUAttrib, 
					 IMG_UINT32 ui32Reg,
					 IMG_UINT32 ui32Data,
					 IMG_HANDLE hUniqueTag)
{
	return PDumpPDRegWithFlags(psMMUAttrib, ui32Reg, ui32Data, PDUMP_FLAGS_CONTINUOUS, hUniqueTag);
}

/**************************************************************************
 * Function Name  : PDumpMemPolKM
 * Inputs         : psMemInfo
 *				  : ui32Offset
 *				  : ui32Value
 *				  : ui32Mask
 *				  : eOperator
 *				  : ui32Flags
 *				  : hUniqueTag
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Implements Client pdump memory poll API
**************************************************************************/
PVRSRV_ERROR PDumpMemPolKM(PVRSRV_KERNEL_MEM_INFO		*psMemInfo,
						   IMG_UINT32			ui32Offset,
						   IMG_UINT32			ui32Value,
						   IMG_UINT32			ui32Mask,
						   PDUMP_POLL_OPERATOR	eOperator,
						   IMG_UINT32			ui32Flags,
						   IMG_HANDLE			hUniqueTag)
{
	#define MEMPOLL_DELAY		(1000)
	#define MEMPOLL_COUNT		(2000000000 / MEMPOLL_DELAY)

	PVRSRV_ERROR eErr;
	IMG_UINT32			ui32PageOffset;
	IMG_UINT8			*pui8LinAddr;
	IMG_DEV_PHYADDR		sDevPAddr;
	IMG_DEV_VIRTADDR	sDevVPageAddr;
	PDUMP_MMU_ATTRIB	*psMMUAttrib;

	PDUMP_GET_SCRIPT_STRING();

	if (PDumpOSIsSuspended())
	{
		return PVRSRV_OK;
	}

	if ( _PDumpIsPersistent() )
	{
		/* Don't pdump-poll if the process is persistent */
		return PVRSRV_OK;
	}

	/* Check the offset and size don't exceed the bounds of the allocation */
	PVR_ASSERT((ui32Offset + sizeof(IMG_UINT32)) <= psMemInfo->uAllocSize);

	psMMUAttrib = ((BM_BUF*)psMemInfo->sMemBlk.hBuffer)->pMapping->pBMHeap->psMMUAttrib;

	/*
		Write a comment to the PDump2 script streams indicating the virtual memory pol
	*/
	eErr = PDumpOSBufprintf(hScript,
			 ui32MaxLen,
			 "-- POL :%s:VA_%08X 0x%08X 0x%08X %d %d %d\r\n",
			 psMMUAttrib->sDevId.pszPDumpDevName,
			 psMemInfo->sDevVAddr.uiAddr + ui32Offset,
			 ui32Value,
			 ui32Mask,
			 eOperator,
			 MEMPOLL_COUNT,
			 MEMPOLL_DELAY);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);


	pui8LinAddr = psMemInfo->pvLinAddrKM;

	/* Advance address by offset */
	pui8LinAddr += ui32Offset;

	/*
		query the buffer manager for the physical pages that back the
		virtual address
	*/
	PDumpOSCPUVAddrToPhysPages(psMemInfo->sMemBlk.hOSMemHandle,
			ui32Offset,
			pui8LinAddr,
			psMMUAttrib->ui32DataPageMask,
			&ui32PageOffset);

	/* calculate the DevV page address */
	sDevVPageAddr.uiAddr = psMemInfo->sDevVAddr.uiAddr + ui32Offset - ui32PageOffset;

	PVR_ASSERT((sDevVPageAddr.uiAddr & psMMUAttrib->ui32DataPageMask) == 0);

	/* get the physical page address based on the device virtual address */
	BM_GetPhysPageAddr(psMemInfo, sDevVPageAddr, &sDevPAddr);

	/* convert DevP page address to byte address */
	sDevPAddr.uiAddr += ui32PageOffset;

	eErr = PDumpOSBufprintf(hScript,
			 ui32MaxLen,
			 "POL :%s:PA_%08X%08X:0x%08X 0x%08X 0x%08X %d %d %d\r\n",
			 psMMUAttrib->sDevId.pszPDumpDevName,
			 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
			 sDevPAddr.uiAddr & ~(psMMUAttrib->ui32DataPageMask),
			 sDevPAddr.uiAddr & (psMMUAttrib->ui32DataPageMask),
			 ui32Value,
			 ui32Mask,
			 eOperator,
			 MEMPOLL_COUNT,
			 MEMPOLL_DELAY);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : _PDumpMemIntKM
 * Inputs         : psMemInfo
 *				  : ui32Offset
 *				  : ui32Bytes
 *				  : ui32Flags
 *				  : hUniqueTag
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Implements Client pdump mem API
**************************************************************************/
static PVRSRV_ERROR _PDumpMemIntKM(IMG_PVOID pvAltLinAddr,
								   PVRSRV_KERNEL_MEM_INFO *psMemInfo,
								   IMG_UINT32 ui32Offset,
								   IMG_UINT32 ui32Bytes,
								   IMG_UINT32 ui32Flags,
								   IMG_HANDLE hUniqueTag)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32 ui32NumPages;
	IMG_UINT32 ui32PageByteOffset;
	IMG_UINT32 ui32BlockBytes;
	IMG_UINT8* pui8LinAddr;
	IMG_UINT8* pui8DataLinAddr = IMG_NULL;
	IMG_DEV_VIRTADDR sDevVPageAddr;
	IMG_DEV_VIRTADDR sDevVAddr;
	IMG_DEV_PHYADDR sDevPAddr;
	IMG_UINT32 ui32ParamOutPos;
	PDUMP_MMU_ATTRIB *psMMUAttrib;
	IMG_UINT32 ui32DataPageSize;

	PDUMP_GET_SCRIPT_AND_FILE_STRING();
	
	/* PRQA S 3415 1 */ /* side effects desired */
	if (ui32Bytes == 0 || PDumpOSIsSuspended())
	{
		return PVRSRV_OK;
	}

	psMMUAttrib = ((BM_BUF*)psMemInfo->sMemBlk.hBuffer)->pMapping->pBMHeap->psMMUAttrib;
	
	/*
		check the offset and size don't exceed the bounds of the allocation
	*/
	PVR_ASSERT((ui32Offset + ui32Bytes) <= psMemInfo->uAllocSize);

	if (!PDumpOSJTInitialised())
	{
		return PVRSRV_ERROR_PDUMP_NOT_AVAILABLE;
	}

#if defined(SUPPORT_PDUMP_MULTI_PROCESS)
	/* if we're dumping a shared heap, need to ensure phys allocation
	 * is initialised even if this app isn't the one marked for pdumping
	 */
	{
		BM_HEAP *pHeap = ((BM_BUF*)psMemInfo->sMemBlk.hBuffer)->pMapping->pBMHeap;
		PVRSRV_DEVICE_NODE *psDeviceNode = pHeap->pBMContext->psDeviceNode;
		
		if( psDeviceNode->pfnMMUIsHeapShared(pHeap->pMMUHeap) )
		{
			ui32Flags |= PDUMP_FLAGS_PERSISTENT;
		}
	}
#endif

	/* setup memory addresses */
	if(pvAltLinAddr)
	{
		pui8DataLinAddr = pvAltLinAddr;
	}
	else if(psMemInfo->pvLinAddrKM)
	{
		pui8DataLinAddr = (IMG_UINT8 *)psMemInfo->pvLinAddrKM + ui32Offset;
	}
	pui8LinAddr = (IMG_UINT8 *)psMemInfo->pvLinAddrKM;
	sDevVAddr = psMemInfo->sDevVAddr;

	/* advance address by offset */
	sDevVAddr.uiAddr += ui32Offset;
	pui8LinAddr += ui32Offset;

	PVR_ASSERT(pui8DataLinAddr);

	PDumpOSCheckForSplitting(PDumpOSGetStream(PDUMP_STREAM_PARAM2), ui32Bytes, ui32Flags);

	ui32ParamOutPos = PDumpOSGetStreamOffset(PDUMP_STREAM_PARAM2);

	/*
		write the binary data up-front.
	*/
	if(!PDumpOSWriteString(PDumpOSGetStream(PDUMP_STREAM_PARAM2),
						pui8DataLinAddr,
						ui32Bytes,
						ui32Flags))
	{
		return PVRSRV_ERROR_PDUMP_BUFFER_FULL;
	}

	if (PDumpOSGetParamFileNum() == 0)
	{
		eErr = PDumpOSSprintf(pszFileName, ui32MaxLenFileName, "%%0%%.prm");
	}
	else
	{
		eErr = PDumpOSSprintf(pszFileName, ui32MaxLenFileName, "%%0%%_%u.prm", PDumpOSGetParamFileNum());
	}
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	/*
		Write a comment to the PDump2 script streams indicating the virtual memory load
	*/
	eErr = PDumpOSBufprintf(hScript,
			 ui32MaxLenScript,
			 "-- LDB :%s:VA_%08X%08X:0x%08X 0x%08X 0x%08X %s\r\n",
			 psMMUAttrib->sDevId.pszPDumpDevName,
			 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
			 psMemInfo->sDevVAddr.uiAddr,
			 ui32Offset,
			 ui32Bytes,
			 ui32ParamOutPos,
			 pszFileName);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	/*
		query the buffer manager for the physical pages that back the
		virtual address
	*/
	PDumpOSCPUVAddrToPhysPages(psMemInfo->sMemBlk.hOSMemHandle,
			ui32Offset,
			pui8LinAddr,
			psMMUAttrib->ui32DataPageMask,
			&ui32PageByteOffset);
	ui32DataPageSize = psMMUAttrib->ui32DataPageMask + 1;
	ui32NumPages = (ui32PageByteOffset + ui32Bytes + psMMUAttrib->ui32DataPageMask) / ui32DataPageSize;

	while(ui32NumPages)
	{
		ui32NumPages--;
	
		/* calculate the DevV page address */
		sDevVPageAddr.uiAddr = sDevVAddr.uiAddr - ui32PageByteOffset;

		if (ui32DataPageSize <= PDUMP_TEMP_BUFFER_SIZE)
		{
			/* if a page fits within temp buffer, we should dump in page-aligned chunks. */
			PVR_ASSERT((sDevVPageAddr.uiAddr & psMMUAttrib->ui32DataPageMask) == 0);
		}

		/* get the physical page address based on the device virtual address */
		BM_GetPhysPageAddr(psMemInfo, sDevVPageAddr, &sDevPAddr);

		/* convert DevP page address to byte address */
		sDevPAddr.uiAddr += ui32PageByteOffset;

		/* how many bytes to dump from this page */
		if (ui32PageByteOffset + ui32Bytes > ui32DataPageSize)
		{
			/* dump up to the page boundary */
			ui32BlockBytes = ui32DataPageSize - ui32PageByteOffset;
		}
		else
		{
			/* dump what's left */
			ui32BlockBytes = ui32Bytes;
		}

		eErr = PDumpOSBufprintf(hScript,
					 ui32MaxLenScript,
					 "LDB :%s:PA_%08X%08X:0x%08X 0x%08X 0x%08X %s\r\n",
					 psMMUAttrib->sDevId.pszPDumpDevName,
					 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
					 sDevPAddr.uiAddr & ~(psMMUAttrib->ui32DataPageMask),
					 sDevPAddr.uiAddr & (psMMUAttrib->ui32DataPageMask),
					 ui32BlockBytes,
					 ui32ParamOutPos,
					 pszFileName);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
		PDumpOSWriteString2(hScript, ui32Flags);

		/* update details for next page */

#if defined(SGX_FEATURE_VARIABLE_MMU_PAGE_SIZE)
		/* page may be larger than pdump temporary buffer */
		ui32PageByteOffset = (ui32PageByteOffset + ui32BlockBytes) % ui32DataPageSize;
#else
		/* page offset 0 after first page dump */
		ui32PageByteOffset = 0;
#endif
		/* bytes left over */
		ui32Bytes -= ui32BlockBytes;	/* PRQA S 3382 */ /* QAC missed MIN test */
		/* advance devVaddr */
		sDevVAddr.uiAddr += ui32BlockBytes;
		/* advance the cpuVaddr */
		pui8LinAddr += ui32BlockBytes;
		/* update the file write offset */
		ui32ParamOutPos += ui32BlockBytes;
	}

	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : PDumpMemKM
 * Inputs         : psMemInfo
 *				  : ui32Offset
 *				  : ui32Bytes
 *				  : ui32Flags
 *				  : hUniqueTag
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Implements Client pdump mem API
**************************************************************************/
PVRSRV_ERROR PDumpMemKM(IMG_PVOID pvAltLinAddr,
						PVRSRV_KERNEL_MEM_INFO *psMemInfo,
						IMG_UINT32 ui32Offset,
						IMG_UINT32 ui32Bytes,
						IMG_UINT32 ui32Flags,
						IMG_HANDLE hUniqueTag)
{
	/*
		For now we don't support dumping sparse allocations that
		are from within the kernel, or are from UM but without a
		alternative linear address
	*/
	PVR_ASSERT((psMemInfo->ui32Flags & PVRSRV_MEM_SPARSE) == 0);

	if (psMemInfo->ui32Flags & PVRSRV_MEM_SPARSE)
	{
		return PVRSRV_ERROR_INVALID_PARAMS;
	}
	else
	{
		return _PDumpMemIntKM(pvAltLinAddr,
							  psMemInfo,
							  ui32Offset,
							  ui32Bytes,
							  ui32Flags,
							  hUniqueTag);
	}
}

PVRSRV_ERROR PDumpMemPDEntriesKM(PDUMP_MMU_ATTRIB *psMMUAttrib,
								 IMG_HANDLE hOSMemHandle,
								 IMG_CPU_VIRTADDR pvLinAddr,
								 IMG_UINT32 ui32Bytes,
								 IMG_UINT32 ui32Flags,
								 IMG_BOOL bInitialisePages,
								 IMG_HANDLE hUniqueTag1,
								 IMG_HANDLE hUniqueTag2)
{
	PDUMP_MMU_ATTRIB sMMUAttrib;
	
	/* Override the (variable) PT size since PDs are always 4K in size */
	sMMUAttrib = *psMMUAttrib;
	sMMUAttrib.ui32PTSize = (IMG_UINT32)HOST_PAGESIZE();
	return PDumpMemPTEntriesKM(	&sMMUAttrib,
								hOSMemHandle,
								pvLinAddr,
								ui32Bytes,
								ui32Flags,
								bInitialisePages,
								hUniqueTag1,
								hUniqueTag2);
}

/**************************************************************************
 * Function Name  : PDumpMemPTEntriesKM
 * Inputs         : psMMUAttrib - MMU attributes for pdump
 *				  : pvLinAddr - CPU address of PT base
 *				  : ui32Bytes - size
 *				  : ui32Flags - pdump flags
 *				  : bInitialisePages - whether to initialise pages from file
 *				  : hUniqueTag1 - ID for PT physical page
 *				  : hUniqueTag2 - ID for target physical page (if !bInitialisePages)
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Kernel Services internal pdump memory API
 *					Used for memory without DevVAddress mappings
 					e.g. MMU page tables
 					FIXME: This function doesn't support non-4k data pages,
 					e.g. dummy data page
**************************************************************************/
PVRSRV_ERROR PDumpMemPTEntriesKM(PDUMP_MMU_ATTRIB *psMMUAttrib,
								 IMG_HANDLE hOSMemHandle,
								 IMG_CPU_VIRTADDR pvLinAddr,
								 IMG_UINT32 ui32Bytes,
								 IMG_UINT32 ui32Flags,
								 IMG_BOOL bInitialisePages,
								 IMG_HANDLE hUniqueTag1,
								 IMG_HANDLE hUniqueTag2)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32 ui32NumPages;
	IMG_UINT32 ui32PageOffset;
	IMG_UINT32 ui32BlockBytes;
	IMG_UINT8* pui8LinAddr;
	IMG_DEV_PHYADDR sDevPAddr;
	IMG_CPU_PHYADDR sCpuPAddr;
	IMG_UINT32 ui32Offset;
	IMG_UINT32 ui32ParamOutPos;
	IMG_UINT32 ui32PageMask; /* mask for the physical page backing the PT */

	PDUMP_GET_SCRIPT_AND_FILE_STRING();
	ui32Flags |= ( _PDumpIsPersistent() ) ? PDUMP_FLAGS_PERSISTENT : 0;

	if (PDumpOSIsSuspended())
	{
		return PVRSRV_OK;
	}

	if (!PDumpOSJTInitialised())
	{
		return PVRSRV_ERROR_PDUMP_NOT_AVAILABLE;
	}

	if (!pvLinAddr)
	{
		return PVRSRV_ERROR_INVALID_PARAMS;
	}

	PDumpOSCheckForSplitting(PDumpOSGetStream(PDUMP_STREAM_PARAM2), ui32Bytes, ui32Flags);

	ui32ParamOutPos = PDumpOSGetStreamOffset(PDUMP_STREAM_PARAM2);

	if (bInitialisePages)
	{
		/*
			write the binary data up-front
			Use the 'continuous' memory stream
		*/
		if (!PDumpOSWriteString(PDumpOSGetStream(PDUMP_STREAM_PARAM2),
							pvLinAddr,
							ui32Bytes,
							ui32Flags | PDUMP_FLAGS_CONTINUOUS))
		{
			return PVRSRV_ERROR_PDUMP_BUFFER_FULL;
		}

		if (PDumpOSGetParamFileNum() == 0)
		{
			eErr = PDumpOSSprintf(pszFileName, ui32MaxLenFileName, "%%0%%.prm");
		}
		else
		{
			eErr = PDumpOSSprintf(pszFileName, ui32MaxLenFileName, "%%0%%_%u.prm", PDumpOSGetParamFileNum());
		}
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
	}

	/*
		Mask for the physical page address backing the PT
		The PT size can be less than 4k with variable page size support
		The PD size is always 4k
		FIXME: This won't work for dumping the dummy data page
	*/
	ui32PageMask = psMMUAttrib->ui32PTSize - 1;

	/*
		Write to the MMU script stream indicating the physical page table entries
	*/
	/* physical pages that back the virtual address	*/
 	ui32PageOffset	= (IMG_UINT32)((IMG_UINTPTR_T)pvLinAddr & (psMMUAttrib->ui32PTSize - 1));
 	ui32NumPages	= (ui32PageOffset + ui32Bytes + psMMUAttrib->ui32PTSize - 1) / psMMUAttrib->ui32PTSize;
	pui8LinAddr		= (IMG_UINT8*) pvLinAddr;

	while (ui32NumPages)
	{
		ui32NumPages--;
		/* FIXME: if we used OSMemHandleToCPUPAddr() here, we might be
		   able to lose the lin addr arg.  At least one thing that
		   would need to be done here is to pass in an offset, as the
		   calling function doesn't necessarily give us the lin addr
		   of the start of the mem area.  Probably best to keep the
		   lin addr arg for now - but would be nice to remove the
		   redundancy */
		sCpuPAddr = OSMapLinToCPUPhys(hOSMemHandle, pui8LinAddr);
		sDevPAddr = SysCpuPAddrToDevPAddr(psMMUAttrib->sDevId.eDeviceType, sCpuPAddr);

		/* how many bytes to dump from this page */
		if (ui32PageOffset + ui32Bytes > psMMUAttrib->ui32PTSize)
		{
			/* dump up to the page boundary */
			ui32BlockBytes = psMMUAttrib->ui32PTSize - ui32PageOffset;
		}
		else
		{
			/* dump what's left */
			ui32BlockBytes = ui32Bytes;
		}

		/*
			Write a comment to the MMU script stream indicating the page table load
		*/
		
		if (bInitialisePages)
		{
			eErr = PDumpOSBufprintf(hScript,
					 ui32MaxLenScript,
					 "LDB :%s:PA_%08X%08X:0x%08X 0x%08X 0x%08X %s\r\n",
					 psMMUAttrib->sDevId.pszPDumpDevName,
					 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag1,
					 sDevPAddr.uiAddr & ~ui32PageMask,
					 sDevPAddr.uiAddr & ui32PageMask,
					 ui32BlockBytes,
					 ui32ParamOutPos,
					 pszFileName);
			if(eErr != PVRSRV_OK)
			{
				return eErr;
			}
			PDumpOSWriteString2(hScript, ui32Flags | PDUMP_FLAGS_CONTINUOUS);
		}
		else
		{
			for (ui32Offset = 0; ui32Offset < ui32BlockBytes; ui32Offset += sizeof(IMG_UINT32))
			{
				IMG_UINT32 ui32PTE = *((IMG_UINT32 *)(IMG_UINTPTR_T)(pui8LinAddr + ui32Offset)); /* PRQA S 3305 */ /* strict pointer */

				if ((ui32PTE & psMMUAttrib->ui32PDEMask) != 0)
				{
					/* PT entry points to non-null page */
#if defined(SGX_FEATURE_36BIT_MMU)
					eErr = PDumpOSBufprintf(hScript,
							ui32MaxLenScript,
							 "WRW :%s:$1 :%s:PA_%08X%08X:0x0\r\n",
							 psMMUAttrib->sDevId.pszPDumpDevName,
							 psMMUAttrib->sDevId.pszPDumpDevName,
							 (IMG_UINT32)hUniqueTag2,
							 (ui32PTE & psMMUAttrib->ui32PDEMask) << psMMUAttrib->ui32PTEAlignShift);
					if(eErr != PVRSRV_OK)
					{
						return eErr;
					}
					PDumpOSWriteString2(hScript, ui32Flags | PDUMP_FLAGS_CONTINUOUS);
					eErr = PDumpOSBufprintf(hScript, ui32MaxLenScript, "SHR :%s:$1 :%s:$1 0x4\r\n",
								psMMUAttrib->sDevId.pszPDumpDevName,
								psMMUAttrib->sDevId.pszPDumpDevName);
					if(eErr != PVRSRV_OK)
					{
						return eErr;
					}
					PDumpOSWriteString2(hScript, ui32Flags | PDUMP_FLAGS_CONTINUOUS);
					eErr = PDumpOSBufprintf(hScript, ui32MaxLenScript, "OR :%s:$1 :%s:$1 0x%08X\r\n",
								psMMUAttrib->sDevId.pszPDumpDevName,
								psMMUAttrib->sDevId.pszPDumpDevName,
								ui32PTE & ~psMMUAttrib->ui32PDEMask);
					if(eErr != PVRSRV_OK)
					{
						return eErr;
					}
					PDumpOSWriteString2(hScript, ui32Flags | PDUMP_FLAGS_CONTINUOUS);
					eErr = PDumpOSBufprintf(hScript,
							ui32MaxLenScript,
							 "WRW :%s:PA_%08X%08X:0x%08X :%s:$1\r\n",
							 psMMUAttrib->sDevId.pszPDumpDevName,
							 (IMG_UINT32)hUniqueTag1,
							 (sDevPAddr.uiAddr + ui32Offset) & ~ui32PageMask,
							 (sDevPAddr.uiAddr + ui32Offset) & ui32PageMask,
							 psMMUAttrib->sDevId.pszPDumpDevName);
					if(eErr != PVRSRV_OK)
					{
						return eErr;
					}
					PDumpOSWriteString2(hScript, ui32Flags | PDUMP_FLAGS_CONTINUOUS);
#else
					eErr = PDumpOSBufprintf(hScript,
							ui32MaxLenScript,
							 "WRW :%s:PA_%08X%08X:0x%08X :%s:PA_%08X%08X:0x%08X\r\n",
							 psMMUAttrib->sDevId.pszPDumpDevName,
							 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag1,
							 (sDevPAddr.uiAddr + ui32Offset) & ~ui32PageMask,
							 (sDevPAddr.uiAddr + ui32Offset) & ui32PageMask,
							 psMMUAttrib->sDevId.pszPDumpDevName,
							 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag2,
							 (ui32PTE & psMMUAttrib->ui32PDEMask) << psMMUAttrib->ui32PTEAlignShift,
							 ui32PTE & ~psMMUAttrib->ui32PDEMask);
					if(eErr != PVRSRV_OK)
					{
						return eErr;
					}
					PDumpOSWriteString2(hScript, ui32Flags | PDUMP_FLAGS_CONTINUOUS);
#endif
				}
				else
				{
#if !defined(FIX_HW_BRN_31620)
					PVR_ASSERT((ui32PTE & psMMUAttrib->ui32PTEValid) == 0UL);
#endif
					eErr = PDumpOSBufprintf(hScript,
							ui32MaxLenScript,
							 "WRW :%s:PA_%08X%08X:0x%08X 0x%08X%08X\r\n",
							 psMMUAttrib->sDevId.pszPDumpDevName,
							 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag1,
							 (sDevPAddr.uiAddr + ui32Offset) & ~ui32PageMask,
							 (sDevPAddr.uiAddr + ui32Offset) & ui32PageMask,
							 (ui32PTE << psMMUAttrib->ui32PTEAlignShift),
							 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag2);
					if(eErr != PVRSRV_OK)
					{
						return eErr;
					}
					PDumpOSWriteString2(hScript, ui32Flags | PDUMP_FLAGS_CONTINUOUS);
				}
			}
		}

		/* update details for next page */

		/* page offset 0 after first page dump */
		ui32PageOffset = 0;
		/* bytes left over */
		ui32Bytes -= ui32BlockBytes;
		/* advance the cpuVaddr */
		pui8LinAddr += ui32BlockBytes;
		/* update the file write offset */
		ui32ParamOutPos += ui32BlockBytes;
	}

	return PVRSRV_OK;
}

PVRSRV_ERROR PDumpPDDevPAddrKM(PVRSRV_KERNEL_MEM_INFO *psMemInfo,
							   IMG_UINT32 ui32Offset,
							   IMG_DEV_PHYADDR sPDDevPAddr,
							   IMG_HANDLE hUniqueTag1,
							   IMG_HANDLE hUniqueTag2)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32 ui32PageByteOffset;
	IMG_DEV_VIRTADDR sDevVAddr;
	IMG_DEV_VIRTADDR sDevVPageAddr;
	IMG_DEV_PHYADDR sDevPAddr;
	IMG_UINT32 ui32Flags = PDUMP_FLAGS_CONTINUOUS;
	IMG_UINT32 ui32ParamOutPos;
	PDUMP_MMU_ATTRIB *psMMUAttrib;
	IMG_UINT32 ui32PageMask; /* mask for the physical page backing the PT */

	PDUMP_GET_SCRIPT_AND_FILE_STRING();

	if (!PDumpOSJTInitialised())
	{
		return PVRSRV_ERROR_PDUMP_NOT_AVAILABLE;
	}

	psMMUAttrib = ((BM_BUF*)psMemInfo->sMemBlk.hBuffer)->pMapping->pBMHeap->psMMUAttrib;
	ui32PageMask = psMMUAttrib->ui32PTSize - 1;

	ui32ParamOutPos = PDumpOSGetStreamOffset(PDUMP_STREAM_PARAM2);

	/* Write the PD phys addr to the param stream up front */
	if(!PDumpOSWriteString(PDumpOSGetStream(PDUMP_STREAM_PARAM2),
						(IMG_UINT8 *)&sPDDevPAddr,
						sizeof(IMG_DEV_PHYADDR),
						ui32Flags))
	{
		return PVRSRV_ERROR_PDUMP_BUFFER_FULL;
	}

	if (PDumpOSGetParamFileNum() == 0)
	{
		eErr = PDumpOSSprintf(pszFileName, ui32MaxLenFileName, "%%0%%.prm");
	}
	else
	{
		eErr = PDumpOSSprintf(pszFileName, ui32MaxLenFileName, "%%0%%_%u.prm", PDumpOSGetParamFileNum());
	}
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	/* Write a comment indicating the PD phys addr write, so that the offsets
	 * into the param stream increase in correspondence with the number of bytes
	 * written. */
	eErr = PDumpOSBufprintf(hScript,
			ui32MaxLenScript,
			"-- LDB :%s:PA_0x%08X%08X:0x%08X 0x%08X 0x%08X %s\r\n",
			psMMUAttrib->sDevId.pszPDumpDevName,
			(IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag1,
			sPDDevPAddr.uiAddr & ~ui32PageMask,
			sPDDevPAddr.uiAddr & ui32PageMask,
			sizeof(IMG_DEV_PHYADDR),
			ui32ParamOutPos,
			pszFileName);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	sDevVAddr = psMemInfo->sDevVAddr;
	ui32PageByteOffset = sDevVAddr.uiAddr & ui32PageMask;

	sDevVPageAddr.uiAddr = sDevVAddr.uiAddr - ui32PageByteOffset;
	PVR_ASSERT((sDevVPageAddr.uiAddr & 0xFFF) == 0);

	BM_GetPhysPageAddr(psMemInfo, sDevVPageAddr, &sDevPAddr);
	sDevPAddr.uiAddr += ui32PageByteOffset + ui32Offset;

	if ((sPDDevPAddr.uiAddr & psMMUAttrib->ui32PDEMask) != 0UL)
	{
#if defined(SGX_FEATURE_36BIT_MMU)
		eErr = PDumpOSBufprintf(hScript,
				ui32MaxLenScript,
				 "WRW :%s:$1 :%s:PA_%08X%08X:0x0\r\n",
				 psMMUAttrib->sDevId.pszPDumpDevName,
				 psMMUAttrib->sDevId.pszPDumpDevName,
				 (IMG_UINT32)hUniqueTag2,
				 sPDDevPAddr.uiAddr);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
		PDumpOSWriteString2(hScript, ui32Flags);

		eErr = PDumpOSBufprintf(hScript, ui32MaxLenScript, "AND  :%s:$2 :%s:$1 0xFFFFFFFF\r\n",
					psMMUAttrib->sDevId.pszPDumpDevName,
					psMMUAttrib->sDevId.pszPDumpDevName);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
		PDumpOSWriteString2(hScript, ui32Flags);

		eErr = PDumpOSBufprintf(hScript,
				ui32MaxLenScript,
				 "WRW :%s:PA_%08X%08X:0x%08X :%s:$2\r\n",
				 psMMUAttrib->sDevId.pszPDumpDevName,
				 (IMG_UINT32)hUniqueTag1,
				 (sDevPAddr.uiAddr) & ~(psMMUAttrib->ui32DataPageMask),
				 (sDevPAddr.uiAddr) & (psMMUAttrib->ui32DataPageMask),
				 psMMUAttrib->sDevId.pszPDumpDevName);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
		PDumpOSWriteString2(hScript, ui32Flags);

		eErr = PDumpOSBufprintf(hScript, ui32MaxLenScript, "SHR :%s:$2 :%s:$1 0x20\r\n",
				psMMUAttrib->sDevId.pszPDumpDevName,
				psMMUAttrib->sDevId.pszPDumpDevName);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
		PDumpOSWriteString2(hScript, ui32Flags);

		eErr = PDumpOSBufprintf(hScript,
				ui32MaxLenScript,
				 "WRW :%s:PA_%08X%08X:0x%08X :%s:$2\r\n",
				 psMMUAttrib->sDevId.pszPDumpDevName,
				 (IMG_UINT32)hUniqueTag1,
				 (sDevPAddr.uiAddr + 4) & ~(psMMUAttrib->ui32DataPageMask),
				 (sDevPAddr.uiAddr + 4) & (psMMUAttrib->ui32DataPageMask),
				 psMMUAttrib->sDevId.pszPDumpDevName);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
		PDumpOSWriteString2(hScript, ui32Flags);
#else
		eErr = PDumpOSBufprintf(hScript,
				 ui32MaxLenScript,
				 "WRW :%s:PA_%08X%08X:0x%08X :%s:PA_%08X%08X:0x%08X\r\n",
				 psMMUAttrib->sDevId.pszPDumpDevName,
				 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag1,
				 sDevPAddr.uiAddr & ~ui32PageMask,
				 sDevPAddr.uiAddr & ui32PageMask,
				 psMMUAttrib->sDevId.pszPDumpDevName,
				 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag2,
				 sPDDevPAddr.uiAddr & psMMUAttrib->ui32PDEMask,
				 sPDDevPAddr.uiAddr & ~psMMUAttrib->ui32PDEMask);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
#endif
	}
	else
	{
		PVR_ASSERT(!(sDevPAddr.uiAddr & psMMUAttrib->ui32PTEValid));
		eErr = PDumpOSBufprintf(hScript,
				 ui32MaxLenScript,
				 "WRW :%s:PA_%08X%08X:0x%08X 0x%08X\r\n",
				 psMMUAttrib->sDevId.pszPDumpDevName,
				 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag1,
				 sDevPAddr.uiAddr & ~ui32PageMask,
				 sDevPAddr.uiAddr & ui32PageMask,
				 sPDDevPAddr.uiAddr);
		if(eErr != PVRSRV_OK)
		{
			return eErr;
		}
	}
	PDumpOSWriteString2(hScript, ui32Flags);

	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : PDumpCommentKM
 * Inputs         : pszComment, ui32Flags
 * Outputs        : None
 * Returns        : None
 * Description    : Dumps a comment
**************************************************************************/
PVRSRV_ERROR PDumpCommentKM(IMG_CHAR *pszComment, IMG_UINT32 ui32Flags)
{
	PVRSRV_ERROR eErr;
	IMG_CHAR pszCommentPrefix[] = "-- "; /* prefix for comments */
#if defined(PDUMP_DEBUG_OUTFILES)
	IMG_CHAR pszTemp[256];
#endif
	IMG_UINT32 ui32LenCommentPrefix;
	PDUMP_GET_SCRIPT_STRING();
	PDUMP_DBG(("PDumpCommentKM"));
#if defined(PDUMP_DEBUG_OUTFILES)
	/* include comments in the "extended" init phase.
	 * default is to ignore them.
	 */
	ui32Flags |= ( _PDumpIsPersistent() ) ? PDUMP_FLAGS_PERSISTENT : 0;
#endif
	/* Put \r \n sequence at the end if it isn't already there */
	PDumpOSVerifyLineEnding(pszComment, ui32MaxLen);

	/* Length of string excluding terminating NULL character */
	ui32LenCommentPrefix = PDumpOSBuflen(pszCommentPrefix, sizeof(pszCommentPrefix));

	/* Ensure output file is available for writing */
	/* FIXME: is this necessary? */
	if (!PDumpOSWriteString(PDumpOSGetStream(PDUMP_STREAM_SCRIPT2),
			  (IMG_UINT8*)pszCommentPrefix,
			  ui32LenCommentPrefix,
			  ui32Flags))
	{
#if defined(PDUMP_DEBUG_OUTFILES)
		if(ui32Flags & PDUMP_FLAGS_CONTINUOUS)
		{
			PVR_DPF((PVR_DBG_WARNING, "Incomplete comment, %d: %s (continuous set)",
					 g_ui32EveryLineCounter, pszComment));
			return PVRSRV_ERROR_PDUMP_BUFFER_FULL;
		}
		else if(ui32Flags & PDUMP_FLAGS_PERSISTENT)
		{
			PVR_DPF((PVR_DBG_WARNING, "Incomplete comment, %d: %s (persistent set)",
					 g_ui32EveryLineCounter, pszComment));
			return PVRSRV_ERROR_CMD_NOT_PROCESSED;
		}
		else
		{
			PVR_DPF((PVR_DBG_WARNING, "Incomplete comment, %d: %s",
					 g_ui32EveryLineCounter, pszComment));
			return PVRSRV_ERROR_CMD_NOT_PROCESSED;
		}
#else
		PVR_DPF((PVR_DBG_WARNING, "Incomplete comment, %s",
					 pszComment));
		return PVRSRV_ERROR_CMD_NOT_PROCESSED;
#endif
	}

#if defined(PDUMP_DEBUG_OUTFILES)
	/* Prefix comment with PID and line number */
	eErr = PDumpOSSprintf(pszTemp, 256, "%d-%d %s",
		_PDumpGetPID(),
		g_ui32EveryLineCounter,
		pszComment);

	/* Append the comment to the script stream */
	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "%s",
		pszTemp);
#else
	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "%s",
		pszComment);
#endif
	if( (eErr != PVRSRV_OK) &&
		(eErr != PVRSRV_ERROR_PDUMP_BUF_OVERFLOW))
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);
	return PVRSRV_OK;
}

/**************************************************************************
 * Function Name  : PDumpCommentWithFlags
 * Inputs         : psPDev - PDev for PDump device
 *				  : pszFormat - format string for comment
 *				  : ... - args for format string
 * Outputs        : None
 * Returns        : None
 * Description    : PDumps a comments
**************************************************************************/
PVRSRV_ERROR PDumpCommentWithFlags(IMG_UINT32 ui32Flags, IMG_CHAR * pszFormat, ...)
{
	PVRSRV_ERROR eErr;
	PDUMP_va_list ap;
	PDUMP_GET_MSG_STRING();

	/* Construct the string */
	PDUMP_va_start(ap, pszFormat);
	eErr = PDumpOSVSprintf(pszMsg, ui32MaxLen, pszFormat, ap);
	PDUMP_va_end(ap);

	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	return PDumpCommentKM(pszMsg, ui32Flags);
}

/**************************************************************************
 * Function Name  : PDumpComment
 * Inputs         : psPDev - PDev for PDump device
 *				  : pszFormat - format string for comment
 *				  : ... - args for format string
 * Outputs        : None
 * Returns        : None
 * Description    : PDumps a comments
**************************************************************************/
PVRSRV_ERROR PDumpComment(IMG_CHAR *pszFormat, ...)
{
	PVRSRV_ERROR eErr;
	PDUMP_va_list ap;
	PDUMP_GET_MSG_STRING();

	/* Construct the string */
	PDUMP_va_start(ap, pszFormat);
	eErr = PDumpOSVSprintf(pszMsg, ui32MaxLen, pszFormat, ap);
	PDUMP_va_end(ap);

	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	return PDumpCommentKM(pszMsg, PDUMP_FLAGS_CONTINUOUS);
}

/**************************************************************************
 * Function Name  : PDumpDriverInfoKM
 * Inputs         : pszString, ui32Flags
 * Outputs        : None
 * Returns        : None
 * Description    : Dumps a comment
**************************************************************************/
PVRSRV_ERROR PDumpDriverInfoKM(IMG_CHAR *pszString, IMG_UINT32 ui32Flags)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32	ui32MsgLen;
	PDUMP_GET_MSG_STRING();

	/* Construct the string */
	eErr = PDumpOSSprintf(pszMsg, ui32MaxLen, "%s", pszString);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	/* Put \r \n sequence at the end if it isn't already there */
	PDumpOSVerifyLineEnding(pszMsg, ui32MaxLen);
	ui32MsgLen = PDumpOSBuflen(pszMsg, ui32MaxLen);

	if	(!PDumpOSWriteString(PDumpOSGetStream(PDUMP_STREAM_DRIVERINFO),
						  (IMG_UINT8*)pszMsg,
						  ui32MsgLen,
						  ui32Flags))
	{
		if	(ui32Flags & PDUMP_FLAGS_CONTINUOUS)
		{
			return PVRSRV_ERROR_PDUMP_BUFFER_FULL;
		}
		else
		{
			return PVRSRV_ERROR_CMD_NOT_PROCESSED;
		}
	}
	return PVRSRV_OK;
}

/*!
******************************************************************************

 @Function	PDumpBitmapKM

 @Description

 Dumps a bitmap from device memory to a file

 @Input    psDevId
 @Input    pszFileName
 @Input    ui32FileOffset
 @Input    ui32Width
 @Input    ui32Height
 @Input    ui32StrideInBytes
 @Input    sDevBaseAddr
 @Input    ui32Size
 @Input    ePixelFormat
 @Input    eMemFormat
 @Input    ui32PDumpFlags

 @Return   PVRSRV_ERROR			:

******************************************************************************/
PVRSRV_ERROR PDumpBitmapKM(	PVRSRV_DEVICE_NODE *psDeviceNode,
							IMG_CHAR *pszFileName,
							IMG_UINT32 ui32FileOffset,
							IMG_UINT32 ui32Width,
							IMG_UINT32 ui32Height,
							IMG_UINT32 ui32StrideInBytes,
							IMG_DEV_VIRTADDR sDevBaseAddr,
							IMG_HANDLE hDevMemContext,
							IMG_UINT32 ui32Size,
							PDUMP_PIXEL_FORMAT ePixelFormat,
							PDUMP_MEM_FORMAT eMemFormat,
							IMG_UINT32 ui32PDumpFlags)
{
	PVRSRV_DEVICE_IDENTIFIER *psDevId = &psDeviceNode->sDevId;
	IMG_UINT32 ui32MMUContextID;
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();

	if ( _PDumpIsPersistent() )
	{
		return PVRSRV_OK;
	}

	PDumpCommentWithFlags(ui32PDumpFlags, "\r\n-- Dump bitmap of render\r\n");

	/* find MMU context ID */
	ui32MMUContextID = psDeviceNode->pfnMMUGetContextID( hDevMemContext );

	eErr = PDumpOSBufprintf(hScript,
				ui32MaxLen,
				"SII %s %s.bin :%s:v%x:0x%08X 0x%08X 0x%08X 0x%08X 0x%08X 0x%08X 0x%08X 0x%08X\r\n",
				pszFileName,
				pszFileName,
				psDevId->pszPDumpDevName,
				ui32MMUContextID,
				sDevBaseAddr.uiAddr,
				ui32Size,
				ui32FileOffset,
				ePixelFormat,
				ui32Width,
				ui32Height,
				ui32StrideInBytes,
				eMemFormat);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	PDumpOSWriteString2( hScript, ui32PDumpFlags);
	return PVRSRV_OK;
}

/*!
******************************************************************************

 @Function	PDumpReadRegKM

 @Description

 Dumps a read from a device register to a file

 @Input    psConnection 		: connection info
 @Input    pszFileName
 @Input    ui32FileOffset
 @Input    ui32Address
 @Input    ui32Size
 @Input    ui32PDumpFlags

 @Return   PVRSRV_ERROR			:

******************************************************************************/
PVRSRV_ERROR PDumpReadRegKM		(	IMG_CHAR *pszPDumpRegName,
									IMG_CHAR *pszFileName,
									IMG_UINT32 ui32FileOffset,
									IMG_UINT32 ui32Address,
									IMG_UINT32 ui32Size,
									IMG_UINT32 ui32PDumpFlags)
{
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();

	PVR_UNREFERENCED_PARAMETER(ui32Size);

	eErr = PDumpOSBufprintf(hScript,
			ui32MaxLen,
			"SAB :%s:0x%08X 0x%08X %s\r\n",
			pszPDumpRegName,
			ui32Address,
			ui32FileOffset,
			pszFileName);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	PDumpOSWriteString2( hScript, ui32PDumpFlags);

	return PVRSRV_OK;
}

/*****************************************************************************
 @name		PDumpTestNextFrame
 @brief		Tests whether the next frame will be pdumped
 @param		ui32CurrentFrame
 @return	bFrameDumped
*****************************************************************************/
IMG_BOOL PDumpTestNextFrame(IMG_UINT32 ui32CurrentFrame)
{
	IMG_BOOL	bFrameDumped;

	/*
		Try dumping a string
	*/
	(IMG_VOID) PDumpSetFrameKM(ui32CurrentFrame + 1);
	bFrameDumped = PDumpIsCaptureFrameKM();
	(IMG_VOID) PDumpSetFrameKM(ui32CurrentFrame);

	return bFrameDumped;
}

/*****************************************************************************
 @name		PDumpSignatureRegister
 @brief		Dumps a single signature register
 @param 	psDevId - device ID
 @param 	ui32Address	- The register address
 @param		ui32Size - The amount of data to be dumped in bytes
 @param		pui32FileOffset - Offset of dump in output file
 @param		ui32Flags - Flags
 @return	none
*****************************************************************************/
static PVRSRV_ERROR PDumpSignatureRegister	(PVRSRV_DEVICE_IDENTIFIER *psDevId,
									 IMG_CHAR	*pszFileName,
									 IMG_UINT32		ui32Address,
									 IMG_UINT32		ui32Size,
									 IMG_UINT32		*pui32FileOffset,
									 IMG_UINT32		ui32Flags)
{
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();

	eErr = PDumpOSBufprintf(hScript,
			ui32MaxLen,
			"SAB :%s:0x%08X 0x%08X %s\r\n",
			psDevId->pszPDumpRegName,
			ui32Address,
			*pui32FileOffset,
			pszFileName);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	PDumpOSWriteString2(hScript, ui32Flags);
	*pui32FileOffset += ui32Size;
	return PVRSRV_OK;
}

/*****************************************************************************
 @name		PDumpRegisterRange
 @brief		Dumps a list of signature registers to a file
 @param		psDevId - device ID
 @param		pszFileName - target filename for dump
 @param		pui32Registers - register list
 @param		ui32NumRegisters - number of regs to dump
 @param		pui32FileOffset - file offset
 @param		ui32Size - size of write in bytes
 @param		ui32Flags - pdump flags
 @return	none
 *****************************************************************************/
static IMG_VOID PDumpRegisterRange(PVRSRV_DEVICE_IDENTIFIER *psDevId,
									IMG_CHAR *pszFileName,
									IMG_UINT32 *pui32Registers,
									IMG_UINT32  ui32NumRegisters,
									IMG_UINT32 *pui32FileOffset,
									IMG_UINT32	ui32Size,
									IMG_UINT32	ui32Flags)
{
	IMG_UINT32 i;
	for (i = 0; i < ui32NumRegisters; i++)
	{
		PDumpSignatureRegister(psDevId, pszFileName, pui32Registers[i], ui32Size, pui32FileOffset, ui32Flags);
	}
}

/*****************************************************************************
 @name		PDump3DSignatureRegisters
 @brief		Dumps the signature registers for 3D modules...
 @param		psDevId - device ID info
 @param		pui32Registers - register list
 @param		ui32NumRegisters - number of regs to dump
 @return	Error
*****************************************************************************/
PVRSRV_ERROR PDump3DSignatureRegisters(PVRSRV_DEVICE_IDENTIFIER *psDevId,
										IMG_UINT32 ui32DumpFrameNum,
										IMG_BOOL bLastFrame,
										IMG_UINT32 *pui32Registers,
										IMG_UINT32 ui32NumRegisters)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32	ui32FileOffset, ui32Flags;

	PDUMP_GET_FILE_STRING();

	ui32Flags = bLastFrame ? PDUMP_FLAGS_LASTFRAME : 0;
	ui32FileOffset = 0;

	PDumpCommentWithFlags(ui32Flags, "\r\n-- Dump 3D signature registers\r\n");
	eErr = PDumpOSSprintf(pszFileName, ui32MaxLen, "out%u_3d.sig", ui32DumpFrameNum);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	PDumpRegisterRange(psDevId,
						pszFileName,
						pui32Registers,
						ui32NumRegisters,
						&ui32FileOffset,
						sizeof(IMG_UINT32),
						ui32Flags);

	return PVRSRV_OK;
}

/*****************************************************************************
 @name		PDumpTASignatureRegisters
 @brief		Dumps the TA signature registers
 @param		psDevId - device id info
 @param		ui32DumpFrameNum - frame number
 @param		ui32TAKickCount - TA kick counter
 @param		bLastFrame
 @param		pui32Registers - register list
 @param		ui32NumRegisters - number of regs to dump
 @return	Error
*****************************************************************************/
PVRSRV_ERROR PDumpTASignatureRegisters	(PVRSRV_DEVICE_IDENTIFIER *psDevId,
			 IMG_UINT32 ui32DumpFrameNum,
			 IMG_UINT32	ui32TAKickCount,
			 IMG_BOOL	bLastFrame,
			 IMG_UINT32 *pui32Registers,
			 IMG_UINT32 ui32NumRegisters)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32	ui32FileOffset, ui32Flags;

	PDUMP_GET_FILE_STRING();

	ui32Flags = bLastFrame ? PDUMP_FLAGS_LASTFRAME : 0;
	ui32FileOffset = ui32TAKickCount * ui32NumRegisters * sizeof(IMG_UINT32);

	PDumpCommentWithFlags(ui32Flags, "\r\n-- Dump TA signature registers\r\n");
	eErr = PDumpOSSprintf(pszFileName, ui32MaxLen, "out%u_ta.sig", ui32DumpFrameNum);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	PDumpRegisterRange(psDevId,
						pszFileName, 
						pui32Registers, 
						ui32NumRegisters, 
						&ui32FileOffset, 
						sizeof(IMG_UINT32), 
						ui32Flags);
	return PVRSRV_OK;
}

/*****************************************************************************
 @name		PDumpCounterRegisters
 @brief		Dumps the performance counters
 @param		psDevId - device id info
 @param		ui32DumpFrameNum - frame number
 @param		bLastFrame
 @param		pui32Registers - register list
 @param		ui32NumRegisters - number of regs to dump
 @return	Error
*****************************************************************************/
PVRSRV_ERROR PDumpCounterRegisters (PVRSRV_DEVICE_IDENTIFIER *psDevId,
								IMG_UINT32 ui32DumpFrameNum,
								IMG_BOOL	bLastFrame,
								IMG_UINT32 *pui32Registers,
								IMG_UINT32 ui32NumRegisters)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32	ui32FileOffset, ui32Flags;

	PDUMP_GET_FILE_STRING();

	ui32Flags = bLastFrame ? PDUMP_FLAGS_LASTFRAME : 0UL;
	ui32FileOffset = 0UL;

	PDumpCommentWithFlags(ui32Flags, "\r\n-- Dump counter registers\r\n");
	eErr = PDumpOSSprintf(pszFileName, ui32MaxLen, "out%u.perf", ui32DumpFrameNum);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	PDumpRegisterRange(psDevId,
						pszFileName,
						pui32Registers,
						ui32NumRegisters,
						&ui32FileOffset,
						sizeof(IMG_UINT32),
						ui32Flags);

	return PVRSRV_OK;
}

/*****************************************************************************
 @name		PDumpRegRead
 @brief		Dump signature register read to script
 @param		pszPDumpDevName - pdump device name
 @param		ui32RegOffset - register offset
 @param		ui32Flags - pdump flags
 @return	Error
*****************************************************************************/
PVRSRV_ERROR PDumpRegRead(IMG_CHAR *pszPDumpRegName,
							const IMG_UINT32 ui32RegOffset,
							IMG_UINT32 ui32Flags)
{
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();

	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "RDW :%s:0x%X\r\n",
							pszPDumpRegName, 
							ui32RegOffset);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);
	return PVRSRV_OK;
}

/*****************************************************************************
 @name		PDumpSaveMemKM
 @brief		Save device memory to a file
 @param		psDevId
 @param		pszFileName
 @param		ui32FileOffset
 @param		sDevBaseAddr
 @param		ui32Size
 @param		ui32PDumpFlags
 @return	Error
*****************************************************************************/
PVRSRV_ERROR PDumpSaveMemKM (PVRSRV_DEVICE_IDENTIFIER *psDevId,
							 IMG_CHAR			*pszFileName,
							 IMG_UINT32			ui32FileOffset,
							 IMG_DEV_VIRTADDR	sDevBaseAddr,
							 IMG_UINT32 		ui32Size,
							 IMG_UINT32			ui32MMUContextID,
							 IMG_UINT32 		ui32PDumpFlags)
{
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();
	
	eErr = PDumpOSBufprintf(hScript,
							ui32MaxLen,
							"SAB :%s:v%x:0x%08X 0x%08X 0x%08X %s.bin\r\n",
							psDevId->pszPDumpDevName,
							ui32MMUContextID,
							sDevBaseAddr.uiAddr,
							ui32Size,
							ui32FileOffset,
							pszFileName);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}

	PDumpOSWriteString2(hScript, ui32PDumpFlags);
	return PVRSRV_OK;
}

/*****************************************************************************
 @name		PDumpCycleCountRegRead
 @brief		Dump counter register read to script
 @param		ui32RegOffset - register offset
 @param		bLastFrame
 @return	Error
*****************************************************************************/
PVRSRV_ERROR PDumpCycleCountRegRead(PVRSRV_DEVICE_IDENTIFIER *psDevId,
									const IMG_UINT32 ui32RegOffset,
									IMG_BOOL bLastFrame)
{
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();

	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "RDW :%s:0x%X\r\n", 
							psDevId->pszPDumpRegName,
							ui32RegOffset);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, bLastFrame ? PDUMP_FLAGS_LASTFRAME : 0);
	return PVRSRV_OK;
}


/*!
******************************************************************************

 @Function	PDumpSignatureBuffer

 @Description

 Dumps a signature registers buffer

 @Return   PVRSRV_ERROR

******************************************************************************/
PVRSRV_ERROR PDumpSignatureBuffer (PVRSRV_DEVICE_IDENTIFIER *psDevId,
								   IMG_CHAR			*pszFileName,
								   IMG_CHAR			*pszBufferType,
								   IMG_UINT32		ui32FileOffset,
								   IMG_DEV_VIRTADDR	sDevBaseAddr,
								   IMG_UINT32 		ui32Size,
								   IMG_UINT32		ui32MMUContextID,
								   IMG_UINT32 		ui32PDumpFlags)
{
	PDumpCommentWithFlags(ui32PDumpFlags, "\r\n-- Dump microkernel %s signature Buffer\r\n",
						  pszBufferType);
	PDumpCommentWithFlags(ui32PDumpFlags, "Buffer format (sizes in 32-bit words):\r\n");
	PDumpCommentWithFlags(ui32PDumpFlags, "\tNumber of signatures per sample (1)\r\n");
	PDumpCommentWithFlags(ui32PDumpFlags, "\tNumber of samples (1)\r\n");
	PDumpCommentWithFlags(ui32PDumpFlags, "\tSignature register offsets (1 * number of signatures)\r\n");
	PDumpCommentWithFlags(ui32PDumpFlags, "\tSignature sample values (number of samples * number of signatures)\r\n");
	PDumpCommentWithFlags(ui32PDumpFlags, "Note: If buffer is full, last sample is final state after test completed\r\n");
	return PDumpSaveMemKM(psDevId, pszFileName, ui32FileOffset, sDevBaseAddr, ui32Size,
						  ui32MMUContextID, ui32PDumpFlags);
}


/*!
******************************************************************************

 @Function	PDumpHWPerfCBKM

 @Description

 Dumps the HW Perf Circular Buffer

 @Return   PVRSRV_ERROR

******************************************************************************/
PVRSRV_ERROR PDumpHWPerfCBKM (PVRSRV_DEVICE_IDENTIFIER *psDevId,
							  IMG_CHAR			*pszFileName,
							  IMG_UINT32		ui32FileOffset,
							  IMG_DEV_VIRTADDR	sDevBaseAddr,
							  IMG_UINT32 		ui32Size,
							  IMG_UINT32		ui32MMUContextID,
							  IMG_UINT32 		ui32PDumpFlags)
{
	PDumpCommentWithFlags(ui32PDumpFlags, "\r\n-- Dump Hardware Performance Circular Buffer\r\n");
	return PDumpSaveMemKM(psDevId, pszFileName, ui32FileOffset, sDevBaseAddr, ui32Size,
						  ui32MMUContextID, ui32PDumpFlags);
}


/*****************************************************************************
 FUNCTION	: PDumpCBP

 PURPOSE	: Dump CBP command to script

 PARAMETERS	:

 RETURNS	: None
*****************************************************************************/
PVRSRV_ERROR PDumpCBP(PPVRSRV_KERNEL_MEM_INFO		psROffMemInfo,
			  IMG_UINT32					ui32ROffOffset,
			  IMG_UINT32					ui32WPosVal,
			  IMG_UINT32					ui32PacketSize,
			  IMG_UINT32					ui32BufferSize,
			  IMG_UINT32					ui32Flags,
			  IMG_HANDLE					hUniqueTag)
{
	PVRSRV_ERROR eErr;
	IMG_UINT32			ui32PageOffset;
	IMG_UINT8			*pui8LinAddr;
	IMG_DEV_VIRTADDR	sDevVAddr;
	IMG_DEV_PHYADDR		sDevPAddr;
	IMG_DEV_VIRTADDR 	sDevVPageAddr;
    //IMG_CPU_PHYADDR     CpuPAddr;
	PDUMP_MMU_ATTRIB *psMMUAttrib;

	PDUMP_GET_SCRIPT_STRING();

	psMMUAttrib = ((BM_BUF*)psROffMemInfo->sMemBlk.hBuffer)->pMapping->pBMHeap->psMMUAttrib;

	/* Check the offset and size don't exceed the bounds of the allocation */
	PVR_ASSERT((ui32ROffOffset + sizeof(IMG_UINT32)) <= psROffMemInfo->uAllocSize);

	pui8LinAddr = psROffMemInfo->pvLinAddrKM;
	sDevVAddr = psROffMemInfo->sDevVAddr;

	/* Advance addresses by offset */
	pui8LinAddr += ui32ROffOffset;
	sDevVAddr.uiAddr += ui32ROffOffset;

	/*
		query the buffer manager for the physical pages that back the
		virtual address
	*/
	PDumpOSCPUVAddrToPhysPages(psROffMemInfo->sMemBlk.hOSMemHandle,
			ui32ROffOffset,
			pui8LinAddr,
			psMMUAttrib->ui32DataPageMask,
			&ui32PageOffset);

	/* calculate the DevV page address */
	sDevVPageAddr.uiAddr = sDevVAddr.uiAddr - ui32PageOffset;

	PVR_ASSERT((sDevVPageAddr.uiAddr & 0xFFF) == 0);

	/* get the physical page address based on the device virtual address */
	BM_GetPhysPageAddr(psROffMemInfo, sDevVPageAddr, &sDevPAddr);

	/* convert DevP page address to byte address */
	sDevPAddr.uiAddr += ui32PageOffset;

	eErr = PDumpOSBufprintf(hScript,
			 ui32MaxLen,
			 "CBP :%s:PA_%08X%08X:0x%08X 0x%08X 0x%08X 0x%08X\r\n",
			 psMMUAttrib->sDevId.pszPDumpDevName,
			 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
			 sDevPAddr.uiAddr & ~(psMMUAttrib->ui32DataPageMask),
			 sDevPAddr.uiAddr & (psMMUAttrib->ui32DataPageMask),
			 ui32WPosVal,
			 ui32PacketSize,
			 ui32BufferSize);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);
	return PVRSRV_OK;
}


/**************************************************************************
 * Function Name  : PDumpIDLWithFlags
 * Inputs         : Idle time in clocks
 * Outputs        : None
 * Returns        : Error
 * Description    : Dump IDL command to script
**************************************************************************/
PVRSRV_ERROR PDumpIDLWithFlags(IMG_UINT32 ui32Clocks, IMG_UINT32 ui32Flags)
{
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();
	PDUMP_DBG(("PDumpIDLWithFlags"));

	eErr = PDumpOSBufprintf(hScript, ui32MaxLen, "IDL %u\r\n", ui32Clocks);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, ui32Flags);
	return PVRSRV_OK;
}


/**************************************************************************
 * Function Name  : PDumpIDL
 * Inputs         : Idle time in clocks
 * Outputs        : None
 * Returns        : Error
 * Description    : Dump IDL command to script
**************************************************************************/
PVRSRV_ERROR PDumpIDL(IMG_UINT32 ui32Clocks)
{
	return PDumpIDLWithFlags(ui32Clocks, PDUMP_FLAGS_CONTINUOUS);
}

/**************************************************************************
 * Function Name  : PDumpMemUM
 * Inputs         : pvAltLinAddrUM
 *				  : pvLinAddrUM
 *				  : psMemInfo
 *				  : ui32Offset
 *				  : ui32Bytes
 *				  : ui32Flags
 *				  : hUniqueTag
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Dump user mode memory
**************************************************************************/
PVRSRV_ERROR PDumpMemUM(PVRSRV_PER_PROCESS_DATA *psPerProc,
						IMG_PVOID pvAltLinAddrUM,
						IMG_PVOID pvLinAddrUM,
						PVRSRV_KERNEL_MEM_INFO *psMemInfo,
						IMG_UINT32 ui32Offset,
						IMG_UINT32 ui32Bytes,
						IMG_UINT32 ui32Flags,
						IMG_HANDLE hUniqueTag)
{
	IMG_VOID *pvAddrUM;
	IMG_VOID *pvAddrKM;
	PVRSRV_ERROR eError;

	if (psMemInfo->pvLinAddrKM != IMG_NULL && pvAltLinAddrUM == IMG_NULL)
	{
		/*
		 * There is a kernel virtual address for the memory that is
		 * being dumped, and no alternate user mode linear address.
		 */
		return PDumpMemKM(IMG_NULL,
					   psMemInfo,
					   ui32Offset,
					   ui32Bytes,
					   ui32Flags,
					   hUniqueTag);
	}

	pvAddrUM = (pvAltLinAddrUM != IMG_NULL) ? pvAltLinAddrUM : ((pvLinAddrUM != IMG_NULL) ? VPTR_PLUS(pvLinAddrUM, ui32Offset) : IMG_NULL);

	pvAddrKM = GetTempBuffer();

	/*
	 * The memory to be dumped needs to be copied in from
	 * the client.  Dump the memory, a buffer at a time.
	 */
	PVR_ASSERT(pvAddrUM != IMG_NULL && pvAddrKM != IMG_NULL);
	if (pvAddrUM == IMG_NULL || pvAddrKM == IMG_NULL)
	{
		PVR_DPF((PVR_DBG_ERROR, "PDumpMemUM: Nothing to dump"));
		return PVRSRV_ERROR_INVALID_PARAMS;
	}

	if (ui32Bytes > PDUMP_TEMP_BUFFER_SIZE)
	{
		PDumpCommentWithFlags(ui32Flags, "Dumping 0x%08x bytes of memory, in blocks of 0x%08x bytes", ui32Bytes, (IMG_UINT32)PDUMP_TEMP_BUFFER_SIZE);
	}

	if (psMemInfo->ui32Flags & PVRSRV_MEM_SPARSE)
	{
		/*
			In case of sparse mappings we can't just copy the full range as not
			all pages are valid, instead we walk a page at a time only dumping
			if the a page exists at that address
		*/
		IMG_UINT32 ui32BytesRemain = ui32Bytes;
		IMG_UINT32 ui32InPageStart = ui32Offset & (~HOST_PAGEMASK);
		IMG_UINT32 ui32PageOffset = ui32Offset & (HOST_PAGEMASK);
		IMG_UINT32 ui32BytesToCopy = MIN(HOST_PAGESIZE() - ui32InPageStart, ui32BytesRemain);

		do
		{
			if (BM_MapPageAtOffset(BM_MappingHandleFromBuffer(psMemInfo->sMemBlk.hBuffer), ui32PageOffset))
			{
				eError = OSCopyFromUser(psPerProc,
							   pvAddrKM,
							   pvAddrUM,
							   ui32BytesToCopy);
				if (eError != PVRSRV_OK)
				{
					PVR_DPF((PVR_DBG_ERROR, "PDumpMemUM: OSCopyFromUser failed (%d)", eError));
					return eError;
				}

				/*
					At this point we know we're dumping a valid page so call
					the internal function
				*/
				eError = _PDumpMemIntKM(pvAddrKM,
										psMemInfo,
										ui32PageOffset + ui32InPageStart,
										ui32BytesToCopy,
										ui32Flags,
										hUniqueTag);
		
				if (eError != PVRSRV_OK)
				{
					/*
					 * If writing fails part way through, then some
					 * investigation is needed.
					 */
					if (ui32BytesToCopy != 0)
					{
						PVR_DPF((PVR_DBG_ERROR, "PDumpMemUM: PDumpMemKM failed (%d)", eError));
					}
					PVR_ASSERT(ui32BytesToCopy == 0);
					return eError;
				}
			}

			VPTR_INC(pvAddrUM, ui32BytesToCopy);
			ui32BytesRemain -= ui32BytesToCopy;
			ui32InPageStart = 0;
			ui32PageOffset += HOST_PAGESIZE();
		} while(ui32BytesRemain);
	}
	else
	{
		IMG_UINT32 ui32CurrentOffset = ui32Offset;
		IMG_UINT32 ui32BytesDumped;

		for (ui32BytesDumped = 0; ui32BytesDumped < ui32Bytes;)
		{
			IMG_UINT32 ui32BytesToDump = MIN(PDUMP_TEMP_BUFFER_SIZE, ui32Bytes - ui32BytesDumped);
	
			eError = OSCopyFromUser(psPerProc,
						   pvAddrKM,
						   pvAddrUM,
						   ui32BytesToDump);
			if (eError != PVRSRV_OK)
			{
				PVR_DPF((PVR_DBG_ERROR, "PDumpMemUM: OSCopyFromUser failed (%d)", eError));
				return eError;
			}
	
			eError = PDumpMemKM(pvAddrKM,
						   psMemInfo,
						   ui32CurrentOffset,
						   ui32BytesToDump,
						   ui32Flags,
						   hUniqueTag);
	
			if (eError != PVRSRV_OK)
			{
				/*
				 * If writing fails part way through, then some
				 * investigation is needed.
				 */
				if (ui32BytesDumped != 0)
				{
					PVR_DPF((PVR_DBG_ERROR, "PDumpMemUM: PDumpMemKM failed (%d)", eError));
				}
				PVR_ASSERT(ui32BytesDumped == 0);
				return eError;
			}
	
			VPTR_INC(pvAddrUM, ui32BytesToDump);
			ui32CurrentOffset += ui32BytesToDump;
			ui32BytesDumped += ui32BytesToDump;
		}
	}

	return PVRSRV_OK;
}


/**************************************************************************
 * Function Name  : _PdumpAllocMMUContext
 * Inputs         : pui32MMUContextID
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : pdump util to allocate MMU contexts
**************************************************************************/
static PVRSRV_ERROR _PdumpAllocMMUContext(IMG_UINT32 *pui32MMUContextID)
{
	IMG_UINT32 i;

	/* there are MAX_PDUMP_MMU_CONTEXTS contexts available, find one */
	for(i=0; i<MAX_PDUMP_MMU_CONTEXTS; i++)
	{
		if((gui16MMUContextUsage & (1U << i)) == 0)
		{
			/* mark in use */
			gui16MMUContextUsage |= 1U << i;
			*pui32MMUContextID = i;
			return PVRSRV_OK;
		}
	}

	PVR_DPF((PVR_DBG_ERROR, "_PdumpAllocMMUContext: no free MMU context ids"));

	return PVRSRV_ERROR_MMU_CONTEXT_NOT_FOUND;
}


/**************************************************************************
 * Function Name  : _PdumpFreeMMUContext
 * Inputs         : ui32MMUContextID
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : pdump util to free MMU contexts
**************************************************************************/
static PVRSRV_ERROR _PdumpFreeMMUContext(IMG_UINT32 ui32MMUContextID)
{
	if(ui32MMUContextID < MAX_PDUMP_MMU_CONTEXTS)
	{
		/* free the id */
		gui16MMUContextUsage &= ~(1U << ui32MMUContextID);
		return PVRSRV_OK;
	}

	PVR_DPF((PVR_DBG_ERROR, "_PdumpFreeMMUContext: MMU context ids invalid"));

	return PVRSRV_ERROR_MMU_CONTEXT_NOT_FOUND;
}


/**************************************************************************
 * Function Name  : PDumpSetMMUContext
 * Inputs         :
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Set MMU Context
**************************************************************************/
PVRSRV_ERROR PDumpSetMMUContext(PVRSRV_DEVICE_TYPE eDeviceType,
								IMG_CHAR *pszMemSpace,
								IMG_UINT32 *pui32MMUContextID,
								IMG_UINT32 ui32MMUType,
								IMG_HANDLE hUniqueTag1,
								IMG_HANDLE hOSMemHandle, 
								IMG_VOID *pvPDCPUAddr)
{
	IMG_UINT8 *pui8LinAddr = (IMG_UINT8 *)pvPDCPUAddr;
	IMG_CPU_PHYADDR sCpuPAddr;
	IMG_DEV_PHYADDR sDevPAddr;
	IMG_UINT32 ui32MMUContextID;
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();

	eErr = _PdumpAllocMMUContext(&ui32MMUContextID);
	if(eErr != PVRSRV_OK)
	{
		PVR_DPF((PVR_DBG_ERROR, "PDumpSetMMUContext: _PdumpAllocMMUContext failed: %d", eErr));
		return eErr;
	}

	/* derive the DevPAddr */
	/* FIXME: if we used OSMemHandleToCPUPAddr() here, we could lose the lin addr arg */
	sCpuPAddr = OSMapLinToCPUPhys(hOSMemHandle, pui8LinAddr);
	sDevPAddr = SysCpuPAddrToDevPAddr(eDeviceType, sCpuPAddr);
	/* and round to 4k page */
	sDevPAddr.uiAddr &= ~((PVRSRV_4K_PAGE_SIZE) -1);

	eErr = PDumpOSBufprintf(hScript,
						ui32MaxLen, 
						"MMU :%s:v%d %d :%s:PA_%08X%08X\r\n",
						pszMemSpace,
						ui32MMUContextID,
						ui32MMUType,
						pszMemSpace,
						(IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag1,
						sDevPAddr.uiAddr);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, PDUMP_FLAGS_CONTINUOUS);

	/* return the MMU Context ID */
	*pui32MMUContextID = ui32MMUContextID;

	return PVRSRV_OK;
}


/**************************************************************************
 * Function Name  : PDumpClearMMUContext
 * Inputs         :
 * Outputs        : None
 * Returns        : PVRSRV_ERROR
 * Description    : Clear MMU Context
**************************************************************************/
PVRSRV_ERROR PDumpClearMMUContext(PVRSRV_DEVICE_TYPE eDeviceType,
								IMG_CHAR *pszMemSpace,
								IMG_UINT32 ui32MMUContextID,
								IMG_UINT32 ui32MMUType)
{
	PVRSRV_ERROR eErr;
	PDUMP_GET_SCRIPT_STRING();
	PVR_UNREFERENCED_PARAMETER(eDeviceType);
	PVR_UNREFERENCED_PARAMETER(ui32MMUType);

	/* FIXME: Propagate error from PDumpComment once it's supported on
	 * all OSes and platforms
	 */
	PDumpComment("Clear MMU Context for memory space %s\r\n", pszMemSpace);
	eErr = PDumpOSBufprintf(hScript,
						ui32MaxLen, 
						"MMU :%s:v%d\r\n",
						pszMemSpace,
						ui32MMUContextID);
	if(eErr != PVRSRV_OK)
	{
		return eErr;
	}
	PDumpOSWriteString2(hScript, PDUMP_FLAGS_CONTINUOUS);

	eErr = _PdumpFreeMMUContext(ui32MMUContextID);
	if(eErr != PVRSRV_OK)
	{
		PVR_DPF((PVR_DBG_ERROR, "PDumpClearMMUContext: _PdumpFreeMMUContext failed: %d", eErr));
		return eErr;
	}

	return PVRSRV_OK;
}

/*****************************************************************************
 FUNCTION	: PDumpStoreMemToFile
    
 PURPOSE	: Dumps a given addr:size to a file

 PARAMETERS	:

 RETURNS	: 
*****************************************************************************/
PVRSRV_ERROR PDumpStoreMemToFile(PDUMP_MMU_ATTRIB *psMMUAttrib,
						         IMG_CHAR *pszFileName,
								 IMG_UINT32 ui32FileOffset, 
								 PVRSRV_KERNEL_MEM_INFO *psMemInfo,
								 IMG_UINT32 uiAddr, 
								 IMG_UINT32 ui32Size,
								 IMG_UINT32 ui32PDumpFlags,
								 IMG_HANDLE hUniqueTag)
{
	IMG_DEV_PHYADDR		sDevPAddr;
	IMG_DEV_VIRTADDR	sDevVPageAddr;
	IMG_UINT32			ui32PageOffset;

	PDUMP_GET_SCRIPT_STRING();

	/*
		query the buffer manager for the physical pages that back the
		virtual address
	*/
	ui32PageOffset = (IMG_UINT32)((IMG_UINTPTR_T)psMemInfo->pvLinAddrKM & psMMUAttrib->ui32DataPageMask);
	
	/* calculate the DevV page address */
	sDevVPageAddr.uiAddr = uiAddr - ui32PageOffset;
	
	/* get the physical page address based on the device virtual address */
	BM_GetPhysPageAddr(psMemInfo, sDevVPageAddr, &sDevPAddr);
	
	/* convert DevP page address to byte address */
	sDevPAddr.uiAddr += ui32PageOffset;

	PDumpOSBufprintf(hScript,
			 ui32MaxLen,
			 "SAB :%s:PA_%08X%08X:0x%08X 0x%08X 0x%08X %s\r\n",
			 psMMUAttrib->sDevId.pszPDumpDevName,
			 (IMG_UINT32)(IMG_UINTPTR_T)hUniqueTag,
			 sDevPAddr.uiAddr & ~psMMUAttrib->ui32DataPageMask,
			 sDevPAddr.uiAddr & psMMUAttrib->ui32DataPageMask,
			 ui32Size,
			 ui32FileOffset,
			 pszFileName);

	PDumpOSWriteString2(hScript, ui32PDumpFlags);
	
	return PVRSRV_OK;	
}

/*****************************************************************************
 FUNCTION	: PDumpRegBasedCBP
    
 PURPOSE	: Dump CBP command to script

 PARAMETERS	:
			  
 RETURNS	: None
*****************************************************************************/
PVRSRV_ERROR PDumpRegBasedCBP(IMG_CHAR		*pszPDumpRegName,
							  IMG_UINT32	ui32RegOffset,
							  IMG_UINT32	ui32WPosVal,
							  IMG_UINT32	ui32PacketSize,
							  IMG_UINT32	ui32BufferSize,
							  IMG_UINT32	ui32Flags)
{
	PDUMP_GET_SCRIPT_STRING();

	PDumpOSBufprintf(hScript,
			 ui32MaxLen,
			 "CBP :%s:0x%08X 0x%08X 0x%08X 0x%08X\r\n",
			 pszPDumpRegName,
			 ui32RegOffset,
			 ui32WPosVal,
			 ui32PacketSize,
			 ui32BufferSize);
	PDumpOSWriteString2(hScript, ui32Flags);
	
	return PVRSRV_OK;		
}


/****************************************************
 * Non-uitron code here.
 * For example, code communicating with dbg driver.
 ***************************************************/
/* PRQA S 5087 1 */ /* include file needed here */
#include "syscommon.h"

/**************************************************************************
 * Function Name  : PDumpConnectionNotify
 * Description    : Called by the debugdrv to tell Services that pdump has
 * 					connected
 *					NOTE: No debugdrv on uitron.
 **************************************************************************/
IMG_EXPORT IMG_VOID PDumpConnectionNotify(IMG_VOID)
{
	SYS_DATA			*psSysData;
	PVRSRV_DEVICE_NODE	*psThis;
	PVR_DPF((PVR_DBG_WARNING, "PDump has connected."));
	
	/* Loop over all known devices */
	SysAcquireData(&psSysData);
	
	psThis = psSysData->psDeviceNodeList;
	while (psThis)
	{
		if (psThis->pfnPDumpInitDevice)
		{
			/* Reset pdump according to connected device */
			psThis->pfnPDumpInitDevice(psThis);
		}
		psThis = psThis->psNext;
	}
}

/*****************************************************************************
 * Function Name  : DbgWrite
 * Inputs         : psStream - debug stream to write to
 					pui8Data - buffer
 					ui32BCount - buffer length
 					ui32Flags - flags, e.g. continuous, LF
 * Outputs        : None
 * Returns        : Bytes written
 * Description    : Write a block of data to a debug stream
 *					NOTE: No debugdrv on uitron.
 *****************************************************************************/
IMG_UINT32 DbgWrite(PDBG_STREAM psStream, IMG_UINT8 *pui8Data, IMG_UINT32 ui32BCount, IMG_UINT32 ui32Flags)
{
	IMG_UINT32	ui32BytesWritten = 0;
	IMG_UINT32	ui32Off = 0;
	PDBG_STREAM_CONTROL psCtrl = psStream->psCtrl;

	/* Return immediately if marked as "never" */
	if ((ui32Flags & PDUMP_FLAGS_NEVER) != 0)
	{
		return ui32BCount;
	}
	
#if defined(SUPPORT_PDUMP_MULTI_PROCESS)
	/* Return if process is not marked for pdumping, unless it's persistent.
	 */
	if ( (_PDumpIsProcessActive() == IMG_FALSE ) &&
		 ((ui32Flags & PDUMP_FLAGS_PERSISTENT) == 0) )
	{
		return ui32BCount;
	}
#endif

	/* Send persistent data first ...
	 * If we're still initialising the params will be captured to the
	 * init stream in the call to pfnDBGDrivWrite2 below.
	 */
	if ( ((ui32Flags & PDUMP_FLAGS_PERSISTENT) != 0) && (psCtrl->bInitPhaseComplete) )
	{
		while (ui32BCount > 0)
		{
			/*
				Params marked as persistent should be appended to the init phase.
				For example window system mem mapping of the primary surface.
			*/
			ui32BytesWritten = PDumpOSDebugDriverWrite(	psStream,
														PDUMP_WRITE_MODE_PERSISTENT,
														&pui8Data[ui32Off], ui32BCount, 1, 0);

			if (ui32BytesWritten == 0)
			{
				PDumpOSReleaseExecution();
			}

			if (ui32BytesWritten != 0xFFFFFFFFU)
			{
				ui32Off += ui32BytesWritten;
				ui32BCount -= ui32BytesWritten;
			}
			else
			{
				PVR_DPF((PVR_DBG_ERROR, "DbgWrite: Failed to send persistent data"));
				if( (psCtrl->ui32Flags & DEBUG_FLAGS_READONLY) != 0)
				{
					/* suspend pdump to prevent flooding kernel log buffer */
					PDumpSuspendKM();
				}
				return 0xFFFFFFFFU;
			}
		}
		
		/* reset buffer counters */
		ui32BCount = ui32Off; ui32Off = 0; ui32BytesWritten = 0;
	}

	while (((IMG_UINT32) ui32BCount > 0) && (ui32BytesWritten != 0xFFFFFFFFU))
	{
		if ((ui32Flags & PDUMP_FLAGS_CONTINUOUS) != 0)
		{
			/*
				If pdump client (or its equivalent) isn't running then throw continuous data away.
			*/
			if (((psCtrl->ui32CapMode & DEBUG_CAPMODE_FRAMED) != 0) &&
				 (psCtrl->ui32Start == 0xFFFFFFFFU) &&
				 (psCtrl->ui32End == 0xFFFFFFFFU) &&
				  psCtrl->bInitPhaseComplete)
			{
				ui32BytesWritten = ui32BCount;
			}
			else
			{
				ui32BytesWritten = PDumpOSDebugDriverWrite(	psStream, 
															PDUMP_WRITE_MODE_CONTINUOUS,
															&pui8Data[ui32Off], ui32BCount, 1, 0);
			}
		}
		else
		{
			if (ui32Flags & PDUMP_FLAGS_LASTFRAME)
			{
				IMG_UINT32	ui32DbgFlags;
	
				ui32DbgFlags = 0;
				if (ui32Flags & PDUMP_FLAGS_RESETLFBUFFER)
				{
					ui32DbgFlags |= WRITELF_FLAGS_RESETBUF;
				}
	
				ui32BytesWritten = PDumpOSDebugDriverWrite(	psStream,
															PDUMP_WRITE_MODE_LASTFRAME,
															&pui8Data[ui32Off], ui32BCount, 1, ui32DbgFlags);
			}
			else
			{
				ui32BytesWritten = PDumpOSDebugDriverWrite(	psStream, 
															PDUMP_WRITE_MODE_BINCM,
															&pui8Data[ui32Off], ui32BCount, 1, 0);
			}
		}

		/*
			If the debug driver's buffers are full so no data could be written then yield
			execution so pdump can run and empty them.
		*/
		if (ui32BytesWritten == 0)
		{
			PDumpOSReleaseExecution();
		}

		if (ui32BytesWritten != 0xFFFFFFFFU)
		{
			ui32Off += ui32BytesWritten;
			ui32BCount -= ui32BytesWritten;
		}

		/* loop exits when i) all data is written, or ii) an unrecoverable error occurs */
	}

	return ui32BytesWritten;
}



#else	/* defined(PDUMP) */
/* disable warning about empty module */
#endif	/* defined(PDUMP) */
/*****************************************************************************
 End of file (pdump_common.c)
*****************************************************************************/