summaryrefslogtreecommitdiff
path: root/drivers/gpu/drm/img/img-rogue/services/server/env/linux/physmem_osmem_linux.c
blob: e6bef8d19c545eb844f223bee34eaf8b8bfa9b5f (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
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
/*************************************************************************/ /*!
@File
@Title          Implementation of PMR functions for OS managed memory
@Copyright      Copyright (c) Imagination Technologies Ltd. All Rights Reserved
@Description    Part of the memory management.  This module is responsible for
                implementing the function callbacks for physical memory borrowed
                from that normally managed by the operating system.
@License        Dual MIT/GPLv2

The contents of this file are subject to the MIT license as set out below.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 ("GPL") in which case the provisions
of GPL are applicable instead of those above.

If you wish to allow use of your version of this file only under the terms of
GPL, and not to allow others to use your version of this file under the terms
of the MIT license, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by GPL as set
out in the file called "GPL-COPYING" included in this distribution. If you do
not delete the provisions above, a recipient may use your version of this file
under the terms of either the MIT license or GPL.

This License is also included in this distribution in the file called
"MIT-COPYING".

EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /**************************************************************************/
#include <linux/version.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/highmem.h>
#include <linux/mm_types.h>
#include <linux/vmalloc.h>
#include <linux/gfp.h>
#include <linux/sched.h>
#include <linux/atomic.h>

#if defined(CONFIG_X86)
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4,12,0))
#include <asm/set_memory.h>
#else
#include <asm/cacheflush.h>
#endif
#endif

/* include/ */
#include "rgx_heaps.h"
#include "img_types.h"
#include "img_defs.h"
#include "pvr_debug.h"
#include "pvrsrv_error.h"
#include "pvrsrv_memallocflags.h"
#include "rgx_pdump_panics.h"
/* services/server/include/ */
#include "allocmem.h"
#include "osfunc.h"
#include "pdump_km.h"
#include "pmr.h"
#include "pmr_impl.h"
#include "cache_km.h"
#include "devicemem_server_utils.h"
#include "pvr_vmap.h"
#include "physheap.h"
#if defined(PVRSRV_PHYSMEM_CPUMAP_HISTORY)
#include "physmem_cpumap_history.h"
#endif

/* ourselves */
#include "physmem_osmem.h"
#include "physmem_osmem_linux.h"

#if defined(PVRSRV_ENABLE_PROCESS_STATS)
#include "process_stats.h"
#if !defined(PVRSRV_ENABLE_MEMORY_STATS)
#include "hash.h"
#endif
#endif

#include "kernel_compatibility.h"

#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0))
static IMG_UINT32 g_uiMaxOrder = PVR_LINUX_PHYSMEM_MAX_ALLOC_ORDER_NUM;
#else
/* split_page not available on older kernels */
#undef PVR_LINUX_PHYSMEM_MAX_ALLOC_ORDER_NUM
#define PVR_LINUX_PHYSMEM_MAX_ALLOC_ORDER_NUM 0
static IMG_UINT32 g_uiMaxOrder;
#endif

/*
	These corresponds to the MMU min/max page sizes and associated PTE
	alignment that can be used on the device for an allocation. It is
	4KB (min) and 2MB (max) respectively.
*/
#define PVR_MIN_PHYSMEM_CONTIG_ALLOC_LOG2PGSZ	RGX_HEAP_4KB_PAGE_SHIFT
#define PVR_MAX_PHYSMEM_CONTIG_ALLOC_LOG2PGSZ	RGX_HEAP_2MB_PAGE_SHIFT

/* Defines how many pages should be mapped at once to the kernel */
#define PVR_LINUX_PHYSMEM_MAX_KMAP_PAGES 1024 /* 4 MB */

/*
	These are used to get/set/mask lower-order bits in a dma_addr_t
	to provide side-band information associated with that address.
	These includes whether the address was obtained via alloc_page
	or dma_alloc and if address came allocated pre-aligned or an
	adjustment was made manually to aligned it.
*/
#define DMA_SET_ADJUSTED_ADDR(x)		((x) | ((dma_addr_t)0x02))
#define DMA_IS_ADDR_ADJUSTED(x)			((x) & ((dma_addr_t)0x02))
#define DMA_SET_ALLOCPG_ADDR(x)			((x) | ((dma_addr_t)0x01))
#define DMA_IS_ALLOCPG_ADDR(x)			((x) & ((dma_addr_t)0x01))
#define DMA_GET_ALIGN_ADJUSTMENT(x)		((x>>2) & ((dma_addr_t)0x3ff))
#define DMA_SET_ALIGN_ADJUSTMENT(x,y)	((x) | (((dma_addr_t)y)<<0x02))
#define DMA_GET_ADDR(x)					(((dma_addr_t)x) & ((dma_addr_t)~0xfff))
#define DMA_VADDR_NOT_IN_USE			0xCAFEF00DDEADBEEFULL

#define PVRSRV_ZERO_VALUE 0

typedef struct _PMR_OSPAGEARRAY_DATA_ {
	/* Device for which this allocation has been made */
	PVRSRV_DEVICE_NODE *psDevNode;
	/* The pid that made this allocation */
	IMG_PID uiPid;

	/*
	 * iNumOSPagesAllocated:
	 * Number of pages allocated in this PMR so far.
	 * This allows for up to (2^31 - 1) pages. With 4KB pages, that's 8TB of memory for each PMR.
	 */
	IMG_INT32 iNumOSPagesAllocated;

	/*
	 * uiTotalNumOSPages:
	 * Total number of pages supported by this PMR. (Fixed as of now due the fixed Page table array size)
	 *  number of "pages" (a.k.a. macro pages, compound pages, higher order pages, etc...)
	 */
	IMG_UINT32 uiTotalNumOSPages;

	/*
	  uiLog2AllocPageSize;

	  size of each "page" -- this would normally be the same as
	  PAGE_SHIFT, but we support the idea that we may allocate pages
	  in larger chunks for better contiguity, using order>0 in the
	  call to alloc_pages()
	*/
	IMG_UINT32 uiLog2AllocPageSize;

	/*
	  ui64DmaMask;
	*/
	IMG_UINT64 ui64DmaMask;

	/*
	  For non DMA/CMA allocation, pagearray references the pages
	  thus allocated; one entry per compound page when compound
	  pages are used. In addition, for DMA/CMA allocations, we
	  track the returned cpu virtual and device bus address.
	*/
	struct page **pagearray;
	dma_addr_t *dmaphysarray;
	void **dmavirtarray;


#define FLAG_ZERO              (0U)
#define FLAG_POISON_ON_FREE    (1U)
#define FLAG_POISON_ON_ALLOC   (2U)
#define FLAG_ONDEMAND          (3U)

#define FLAG_IS_CMA            (5U)
#define FLAG_UNSET_MEMORY_TYPE (6U)

	/*
	 * Allocation flags related to the pages:
	 * Zero              - Should we Zero memory on alloc
	 * Poison on free    - Should we Poison the memory on free.
	 * Poison on alloc   - Should we Poison the memory on alloc.
	 * On demand         - Is the allocation on Demand i.e Do we defer allocation to time of use.
	 * CMA               - Is CMA memory allocated via DMA framework
	 * Unset Memory Type - Upon free do we need to revert the cache type before return to OS
	 * */
	IMG_UINT32 ui32AllocFlags;

	/*
	  The cache mode of the PMR. Additionally carrying the CPU-Cache-Clean
	  flag, advising us to do cache maintenance on behalf of the caller.
	  Boolean used to track if we need to revert the cache attributes
	  of the pages used in this allocation. Depends on OS/architecture.
	*/
	IMG_UINT32 ui32CPUCacheFlags;
	/*
	 * In CMA allocation path, algorithm can allocate double the size of
	 * requested allocation size to satisfy the alignment. In this case
	 * the additional pages allocated are tracked through this additional
	 * variable and are accounted for in the memory statistics */
	IMG_UINT32 ui32CMAAdjustedPageCount;

#if defined(PVRSRV_PHYSMEM_CPUMAP_HISTORY)
	/*
	  Handle on the parent PMR
	 */
	void *hPMR;
#endif

} PMR_OSPAGEARRAY_DATA;

/***********************************
 * Page pooling for uncached pages *
 ***********************************/

static INLINE void
_FreeOSPage_CMA(struct device *dev,
				size_t alloc_size,
				IMG_UINT32 uiOrder,
				void *virt_addr,
				dma_addr_t dev_addr,
				struct page *psPage);

static void
_FreeOSPage(IMG_UINT32 uiOrder,
			IMG_BOOL bUnsetMemoryType,
			struct page *psPage);

static PVRSRV_ERROR
_FreeOSPages(PMR_OSPAGEARRAY_DATA *psPageArrayData,
			IMG_UINT32 *pai32FreeIndices,
			IMG_UINT32 ui32FreePageCount);

static PVRSRV_ERROR
_FreePagesFromPoolUnlocked(IMG_UINT32 uiMaxPagesToFree,
						   IMG_UINT32 *puiPagesFreed);

/* A struct for our page pool holding an array of zeroed (!) pages.
 * We always put units of page arrays to the pool but are
 * able to take individual pages */
typedef	struct
{
	/* Linkage for page pool LRU list */
	struct list_head sPagePoolItem;

	/* How many items are still in the page array */
	IMG_UINT32 uiItemsRemaining;
	/* Array of the actual pages */
	struct page **ppsPageArray;

} LinuxPagePoolEntry;

/* CleanupThread structure to put allocation in page pool */
typedef struct
{
	PVRSRV_CLEANUP_THREAD_WORK sCleanupWork;
	IMG_UINT32 ui32CPUCacheMode;
	LinuxPagePoolEntry *psPoolEntry;
} LinuxCleanupData;


/* Caches to hold page pool and page array structures */
static struct kmem_cache *g_psLinuxPagePoolCache;
static struct kmem_cache *g_psLinuxPageArray;

/* Track what is live, all protected by pool lock.
 * x86 needs two page pools because we have to change the memory attributes
 * of the pages which is expensive due to an implicit flush.
 * See set_pages_array_uc/wc/wb. */
static IMG_UINT32 g_ui32PagePoolUCCount;
#if defined(CONFIG_X86)
static IMG_UINT32 g_ui32PagePoolWCCount;
#endif
/* Tracks asynchronous tasks currently accessing the page pool.
 * It is incremented if a defer free task
 * is created. Both will decrement the value when they finished the work.
 * The atomic prevents piling up of deferred work in case the deferred thread
 * cannot keep up with the application.*/
static ATOMIC_T g_iPoolCleanTasks;
/* We don't want too many asynchronous threads trying to access the page pool
 * at the same time */
#define PVR_LINUX_PHYSMEM_MAX_ASYNC_CLEAN_TASKS 128

/* Defines how many pages the page cache should hold. */
#if defined(PVR_LINUX_PHYSMEM_MAX_POOL_PAGES)
static const IMG_UINT32 g_ui32PagePoolMaxEntries = PVR_LINUX_PHYSMEM_MAX_POOL_PAGES;
#else
static const IMG_UINT32 g_ui32PagePoolMaxEntries;
#endif

/*	We double check if we would exceed this limit if we are below MAX_POOL_PAGES
	and want to add an allocation to the pool.
	This prevents big allocations being given back to the OS just because they
	exceed the MAX_POOL_PAGES limit even though the pool is currently empty. */
#if defined(PVR_LINUX_PHYSMEM_MAX_EXCESS_POOL_PAGES)
static const IMG_UINT32 g_ui32PagePoolMaxExcessEntries = PVR_LINUX_PHYSMEM_MAX_EXCESS_POOL_PAGES;
#else
static const IMG_UINT32 g_ui32PagePoolMaxExcessEntries;
#endif

#if defined(CONFIG_X86)
#define PHYSMEM_OSMEM_NUM_OF_POOLS 2
static const IMG_UINT32 g_aui32CPUCacheFlags[PHYSMEM_OSMEM_NUM_OF_POOLS] = {
	PVRSRV_MEMALLOCFLAG_CPU_UNCACHED,
	PVRSRV_MEMALLOCFLAG_CPU_UNCACHED_WC
};
#else
#define PHYSMEM_OSMEM_NUM_OF_POOLS 1
static const IMG_UINT32 g_aui32CPUCacheFlags[PHYSMEM_OSMEM_NUM_OF_POOLS] = {
	PVRSRV_MEMALLOCFLAG_CPU_UNCACHED
};
#endif

/* Global structures we use to manage the page pool */
static DEFINE_MUTEX(g_sPagePoolMutex);

/* List holding the page array pointers: */
static LIST_HEAD(g_sPagePoolList_WC);
static LIST_HEAD(g_sPagePoolList_UC);

#if defined(DEBUG) && defined(SUPPORT_VALIDATION)
/* Global structure to manage GPU memory leak */
static DEFINE_MUTEX(g_sUMALeakMutex);
static IMG_UINT32 g_ui32UMALeakCounter = 0;
#endif

static IMG_BOOL g_bInitialisedOnAlloc = IMG_FALSE;

static inline IMG_BOOL
_ShouldInitMem(IMG_UINT32 ui32AllocFlags)
{
	return BIT_ISSET(ui32AllocFlags, FLAG_ZERO) && !g_bInitialisedOnAlloc;
}

static inline IMG_UINT32
_PagesInPoolUnlocked(void)
{
	IMG_UINT32 uiCnt = g_ui32PagePoolUCCount;
#if defined(CONFIG_X86)
	uiCnt += g_ui32PagePoolWCCount;
#endif
	return uiCnt;
}

static inline void
_PagePoolLock(void)
{
	mutex_lock(&g_sPagePoolMutex);
}

static inline int
_PagePoolTrylock(void)
{
	return mutex_trylock(&g_sPagePoolMutex);
}

static inline void
_PagePoolUnlock(void)
{
	mutex_unlock(&g_sPagePoolMutex);
}

static inline IMG_BOOL
_GetPoolListHead(IMG_UINT32 ui32CPUCacheFlags,
				 struct list_head **ppsPoolHead,
				 IMG_UINT32 **ppuiCounter)
{
	switch (PVRSRV_CPU_CACHE_MODE(ui32CPUCacheFlags))
	{
		case PVRSRV_MEMALLOCFLAG_CPU_UNCACHED_WC:
#if defined(CONFIG_X86)
		/*
			For x86 we need to keep different lists for uncached
			and write-combined as we must always honour the PAT
			setting which cares about this difference.
		*/

			*ppsPoolHead = &g_sPagePoolList_WC;
			*ppuiCounter = &g_ui32PagePoolWCCount;
			break;
#endif

		case PVRSRV_MEMALLOCFLAG_CPU_UNCACHED:
			*ppsPoolHead = &g_sPagePoolList_UC;
			*ppuiCounter = &g_ui32PagePoolUCCount;
			break;

		default:
			PVR_DPF((PVR_DBG_ERROR,
					"%s: Unknown CPU caching mode. "
					 "Using default UC pool.",
					 __func__));
			*ppsPoolHead = &g_sPagePoolList_UC;
			*ppuiCounter = &g_ui32PagePoolUCCount;
			PVR_ASSERT(0);
			return IMG_FALSE;
	}
	return IMG_TRUE;
}

static struct shrinker g_sShrinker;

/* Returning the number of pages that still reside in the page pool. */
static unsigned long
_GetNumberOfPagesInPoolUnlocked(void)
{
	return _PagesInPoolUnlocked();
}

/* Linux shrinker function that informs the OS about how many pages we are caching and
 * it is able to reclaim. */
static unsigned long
_CountObjectsInPagePool(struct shrinker *psShrinker, struct shrink_control *psShrinkControl)
{
	int remain;

	PVR_ASSERT(psShrinker == &g_sShrinker);
	(void)psShrinker;
	(void)psShrinkControl;

	/* In order to avoid possible deadlock use mutex_trylock in place of mutex_lock */
	if (_PagePoolTrylock() == 0)
		return 0;
	remain = _GetNumberOfPagesInPoolUnlocked();
	_PagePoolUnlock();

	return remain;
}

/* Linux shrinker function to reclaim the pages from our page pool */
static unsigned long
_ScanObjectsInPagePool(struct shrinker *psShrinker, struct shrink_control *psShrinkControl)
{
	unsigned long uNumToScan = psShrinkControl->nr_to_scan;
	IMG_UINT32 uiPagesFreed;

	PVR_ASSERT(psShrinker == &g_sShrinker);
	(void)psShrinker;

	/* In order to avoid possible deadlock use mutex_trylock in place of mutex_lock */
	if (_PagePoolTrylock() == 0)
		return SHRINK_STOP;

	_FreePagesFromPoolUnlocked(uNumToScan,
							   &uiPagesFreed);
	uNumToScan -= uiPagesFreed;

#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,12,0))
	{
		int remain;
		remain = _GetNumberOfPagesInPoolUnlocked();
		_PagePoolUnlock();
		return remain;
	}
#else
	/* Returning the number of pages freed during the scan */
	_PagePoolUnlock();
	return psShrinkControl->nr_to_scan - uNumToScan;
#endif
}

#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,12,0))
static int
_ShrinkPagePool(struct shrinker *psShrinker, struct shrink_control *psShrinkControl)
{
	if (psShrinkControl->nr_to_scan != 0)
	{
		return _ScanObjectsInPagePool(psShrinker, psShrinkControl);
	}
	else
	{
		/* No pages are being reclaimed so just return the page count */
		return _CountObjectsInPagePool(psShrinker, psShrinkControl);
	}
}

static struct shrinker g_sShrinker =
{
	.shrink = _ShrinkPagePool,
	.seeks = DEFAULT_SEEKS
};
#else
static struct shrinker g_sShrinker =
{
	.count_objects = _CountObjectsInPagePool,
	.scan_objects = _ScanObjectsInPagePool,
	.seeks = DEFAULT_SEEKS
};
#endif

/* Register the shrinker so Linux can reclaim cached pages */
void LinuxInitPhysmem(void)
{
	g_psLinuxPageArray = kmem_cache_create("pvr-pa", sizeof(PMR_OSPAGEARRAY_DATA), 0, 0, NULL);

	g_psLinuxPagePoolCache = kmem_cache_create("pvr-pp", sizeof(LinuxPagePoolEntry), 0, 0, NULL);
	if (g_psLinuxPagePoolCache)
	{
		/* Only create the shrinker if we created the cache OK */
		register_shrinker(&g_sShrinker, "pvr-pp");
	}

	OSAtomicWrite(&g_iPoolCleanTasks, 0);

#if (LINUX_VERSION_CODE >= KERNEL_VERSION(5,3,0))
/* Check both config and modparam setting */
#if PVRSRV_USE_LINUX_CONFIG_INIT_ON_ALLOC == 1
	g_bInitialisedOnAlloc = want_init_on_alloc(0x0);

/* Assume modparam setting not in use on system */
#elif PVRSRV_USE_LINUX_CONFIG_INIT_ON_ALLOC == 2
#   if defined(CONFIG_INIT_ON_ALLOC_DEFAULT_ON)
	g_bInitialisedOnAlloc = IMG_TRUE;
#   else
	g_bInitialisedOnAlloc = IMG_FALSE;
#   endif

/* Ignore both config and modparam settings */
#else
	g_bInitialisedOnAlloc = IMG_FALSE;
#endif
#endif
}

/* Unregister the shrinker and remove all pages from the pool that are still left */
void LinuxDeinitPhysmem(void)
{
	IMG_UINT32 uiPagesFreed;

	if (OSAtomicRead(&g_iPoolCleanTasks) > 0)
	{
		PVR_DPF((PVR_DBG_WARNING, "Still deferred cleanup tasks running "
				"while deinitialising memory subsystem."));
	}

	_PagePoolLock();
	if (_FreePagesFromPoolUnlocked(IMG_UINT32_MAX, &uiPagesFreed) != PVRSRV_OK)
	{
		PVR_DPF((PVR_DBG_ERROR, "Unable to free all pages from page pool when "
				"deinitialising memory subsystem."));
		PVR_ASSERT(0);
	}

	PVR_ASSERT(_PagesInPoolUnlocked() == 0);

	/* Free the page cache */
	kmem_cache_destroy(g_psLinuxPagePoolCache);

	unregister_shrinker(&g_sShrinker);
	_PagePoolUnlock();

	kmem_cache_destroy(g_psLinuxPageArray);
}

static void EnableOOMKiller(void)
{
	current->flags &= ~PF_DUMPCORE;
}

static void DisableOOMKiller(void)
{
	/* PF_DUMPCORE is treated by the VM as if the OOM killer was disabled.
	 *
	 * As oom_killer_disable() is an inline, non-exported function, we
	 * can't use it from a modular driver. Furthermore, the OOM killer
	 * API doesn't look thread safe, which 'current' is.
	 */
	WARN_ON(current->flags & PF_DUMPCORE);
	current->flags |= PF_DUMPCORE;
}

/* Prints out the addresses in a page array for debugging purposes
 * Define PHYSMEM_OSMEM_DEBUG_DUMP_PAGE_ARRAY locally to activate: */
/* #define PHYSMEM_OSMEM_DEBUG_DUMP_PAGE_ARRAY 1 */
static inline void
_DumpPageArray(struct page **pagearray, IMG_UINT32 uiPagesToPrint)
{
#if defined(PHYSMEM_OSMEM_DEBUG_DUMP_PAGE_ARRAY)
	IMG_UINT32 i;
	if (pagearray)
	{
		printk("Array %p:\n", pagearray);
		for (i = 0; i < uiPagesToPrint; i++)
		{
			printk("%p | ", (pagearray)[i]);
		}
		printk("\n");
	}
	else
	{
		printk("Array is NULL:\n");
	}
#else
	PVR_UNREFERENCED_PARAMETER(pagearray);
	PVR_UNREFERENCED_PARAMETER(uiPagesToPrint);
#endif
}

/* Debugging function that dumps out the number of pages for every
 * page array that is currently in the page pool.
 * Not defined by default. Define locally to activate feature: */
/* #define PHYSMEM_OSMEM_DEBUG_DUMP_PAGE_POOL 1 */
static void
_DumpPoolStructure(void)
{
#if defined(PHYSMEM_OSMEM_DEBUG_DUMP_PAGE_POOL)
	LinuxPagePoolEntry *psPagePoolEntry, *psTempPoolEntry;
	struct list_head *psPoolHead = NULL;
	IMG_UINT32 j;
	IMG_UINT32 *puiCounter;

	printk("\n");
	/* Empty all pools */
	for (j = 0; j < PHYSMEM_OSMEM_NUM_OF_POOLS; j++)
	{

		printk("pool = %u\n", j);

		/* Get the correct list for this caching mode */
		if (!_GetPoolListHead(g_aui32CPUCacheFlags[j], &psPoolHead, &puiCounter))
		{
			break;
		}

		list_for_each_entry_safe(psPagePoolEntry,
								 psTempPoolEntry,
								 psPoolHead,
								 sPagePoolItem)
		{
			printk("%u | ", psPagePoolEntry->uiItemsRemaining);
		}
		printk("\n");
	}
#endif
}

/* Free a certain number of pages from the page pool.
 * Mainly used in error paths or at deinitialisation to
 * empty the whole pool. */
static PVRSRV_ERROR
_FreePagesFromPoolUnlocked(IMG_UINT32 uiMaxPagesToFree,
						   IMG_UINT32 *puiPagesFreed)
{
	PVRSRV_ERROR eError = PVRSRV_OK;
	LinuxPagePoolEntry *psPagePoolEntry, *psTempPoolEntry;
	struct list_head *psPoolHead = NULL;
	IMG_UINT32 i, j;
	IMG_UINT32 *puiCounter;

	*puiPagesFreed = uiMaxPagesToFree;

	/* Empty all pools */
	for (j = 0; j < PHYSMEM_OSMEM_NUM_OF_POOLS; j++)
	{

		/* Get the correct list for this caching mode */
		if (!_GetPoolListHead(g_aui32CPUCacheFlags[j], &psPoolHead, &puiCounter))
		{
			break;
		}

		/* Free the pages and remove page arrays from the pool if they are exhausted */
		list_for_each_entry_safe(psPagePoolEntry,
								 psTempPoolEntry,
								 psPoolHead,
								 sPagePoolItem)
		{
			IMG_UINT32 uiItemsToFree;
			struct page **ppsPageArray;

			/* Check if we are going to free the whole page array or just parts */
			if (psPagePoolEntry->uiItemsRemaining <= uiMaxPagesToFree)
			{
				uiItemsToFree = psPagePoolEntry->uiItemsRemaining;
				ppsPageArray = psPagePoolEntry->ppsPageArray;
			}
			else
			{
				uiItemsToFree = uiMaxPagesToFree;
				ppsPageArray = &(psPagePoolEntry->ppsPageArray[psPagePoolEntry->uiItemsRemaining - uiItemsToFree]);
			}

#if defined(CONFIG_X86)
			/* Set the correct page caching attributes on x86 */
			if (!PVRSRV_CHECK_CPU_CACHED(g_aui32CPUCacheFlags[j]))
			{
				int ret;
				ret = set_pages_array_wb(ppsPageArray, uiItemsToFree);
				if (ret)
				{
					PVR_DPF((PVR_DBG_ERROR,
							 "%s: Failed to reset page attributes",
							 __func__));
					eError = PVRSRV_ERROR_FAILED_TO_FREE_PAGES;
					goto e_exit;
				}
			}
#endif

			/* Free the actual pages */
			for (i = 0; i < uiItemsToFree; i++)
			{
				__free_pages(ppsPageArray[i], 0);
				ppsPageArray[i] = NULL;
			}

			/* Reduce counters */
			uiMaxPagesToFree -= uiItemsToFree;
			*puiCounter -= uiItemsToFree;
			psPagePoolEntry->uiItemsRemaining -= uiItemsToFree;

#if defined(PVRSRV_ENABLE_PROCESS_STATS)
			/*
			 * MemStats usually relies on having the bridge lock held, however
			 * the page pool code may call PVRSRVStatsIncrMemAllocPoolStat and
			 * PVRSRVStatsDecrMemAllocPoolStat without the bridge lock held, so
			 * the page pool lock is used to ensure these calls are mutually
			 * exclusive
			 */
			PVRSRVStatsDecrMemAllocPoolStat(PAGE_SIZE * uiItemsToFree);
#endif

			/* Is this pool entry exhausted, delete it */
			if (psPagePoolEntry->uiItemsRemaining == 0)
			{
				OSFreeMemNoStats(psPagePoolEntry->ppsPageArray);
				list_del(&psPagePoolEntry->sPagePoolItem);
				kmem_cache_free(g_psLinuxPagePoolCache, psPagePoolEntry);
			}

			/* Return if we have all our pages */
			if (uiMaxPagesToFree == 0)
			{
				goto e_exit;
			}
		}
	}

e_exit:
	*puiPagesFreed -= uiMaxPagesToFree;
	_DumpPoolStructure();
	return eError;
}

/* Get a certain number of pages from the page pool and
 * copy them directly into a given page array. */
static void
_GetPagesFromPoolUnlocked(IMG_UINT32 ui32CPUCacheFlags,
						  IMG_UINT32 uiMaxNumPages,
						  struct page **ppsPageArray,
						  IMG_UINT32 *puiNumReceivedPages)
{
	LinuxPagePoolEntry *psPagePoolEntry, *psTempPoolEntry;
	struct list_head *psPoolHead = NULL;
	IMG_UINT32 i;
	IMG_UINT32 *puiCounter;

	*puiNumReceivedPages = 0;

	/* Get the correct list for this caching mode */
	if (!_GetPoolListHead(ui32CPUCacheFlags, &psPoolHead, &puiCounter))
	{
		return;
	}

	/* Check if there are actually items in the list */
	if (list_empty(psPoolHead))
	{
		return;
	}

	PVR_ASSERT(*puiCounter > 0);

	/* Receive pages from the pool */
	list_for_each_entry_safe(psPagePoolEntry,
							 psTempPoolEntry,
							 psPoolHead,
							 sPagePoolItem)
	{
		/* Get the pages from this pool entry */
		for (i = psPagePoolEntry->uiItemsRemaining; i != 0 && *puiNumReceivedPages < uiMaxNumPages; i--)
		{
			ppsPageArray[*puiNumReceivedPages] = psPagePoolEntry->ppsPageArray[i-1];
			(*puiNumReceivedPages)++;
			psPagePoolEntry->uiItemsRemaining--;
		}

		/* Is this pool entry exhausted, delete it */
		if (psPagePoolEntry->uiItemsRemaining == 0)
		{
			OSFreeMemNoStats(psPagePoolEntry->ppsPageArray);
			list_del(&psPagePoolEntry->sPagePoolItem);
			kmem_cache_free(g_psLinuxPagePoolCache, psPagePoolEntry);
		}

		/* Return if we have all our pages */
		if (*puiNumReceivedPages == uiMaxNumPages)
		{
			goto exit_ok;
		}
	}

exit_ok:

	/* Update counters */
	*puiCounter -= *puiNumReceivedPages;

#if defined(PVRSRV_ENABLE_PROCESS_STATS)
	/* MemStats usually relies on having the bridge lock held, however
	 * the page pool code may call PVRSRVStatsIncrMemAllocPoolStat and
	 * PVRSRVStatsDecrMemAllocPoolStat without the bridge lock held, so
	 * the page pool lock is used to ensure these calls are mutually
	 * exclusive
	 */
	PVRSRVStatsDecrMemAllocPoolStat(PAGE_SIZE * (*puiNumReceivedPages));
#endif

	_DumpPoolStructure();
	return;
}

/* Same as _GetPagesFromPoolUnlocked but handles locking and
 * checks first whether pages from the pool are a valid option. */
static inline void
_GetPagesFromPoolLocked(PVRSRV_DEVICE_NODE *psDevNode,
						IMG_UINT32 ui32CPUCacheFlags,
						IMG_UINT32 uiPagesToAlloc,
						IMG_UINT32 uiOrder,
						IMG_BOOL bZero,
						struct page **ppsPageArray,
						IMG_UINT32 *puiPagesFromPool)
{
#if defined(PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES)
	PVR_UNREFERENCED_PARAMETER(bZero);
#else
	/* Don't get pages from pool if it doesn't provide zeroed pages */
	if (bZero)
	{
		return;
	}
#endif

	/* The page pool stores only order 0 pages. If we need zeroed memory we
	 * directly allocate from the OS because it is faster than
	 * doing it within the driver. */
	if (uiOrder == 0 &&
	    !PVRSRV_CHECK_CPU_CACHED(ui32CPUCacheFlags))
	{

		_PagePoolLock();
		_GetPagesFromPoolUnlocked(ui32CPUCacheFlags,
								  uiPagesToAlloc,
								  ppsPageArray,
								  puiPagesFromPool);
		_PagePoolUnlock();
	}

	return;
}

/* Takes a page array and maps it into the kernel to write zeros */
static PVRSRV_ERROR
_MemsetPageArray(IMG_UINT32 uiNumToClean,
                 struct page **ppsCleanArray,
                 pgprot_t pgprot,
		IMG_UINT8 ui8Pattern, int rv_cache)
{
	IMG_CPU_VIRTADDR pvAddr;
	IMG_UINT32 uiMaxPagesToMap = MIN(PVR_LINUX_PHYSMEM_MAX_KMAP_PAGES,
	                                 uiNumToClean);

	/* Map and fill the pages with zeros.
	 * For large page arrays do it PVR_LINUX_PHYSMEM_MAX_KMAP_SIZE
	 * at a time. */
	while (uiNumToClean != 0)
	{
		IMG_UINT32 uiToClean = MIN(uiNumToClean, uiMaxPagesToMap);

		if (rv_cache) {
			pvAddr = pvr_vmap_cached(ppsCleanArray, uiToClean, VM_WRITE, pgprot);
		} else {
			pvAddr = pvr_vmap(ppsCleanArray, uiToClean, VM_WRITE, pgprot);
		}
		if (!pvAddr)
		{
			if (uiMaxPagesToMap <= 1)
			{
				PVR_DPF((PVR_DBG_ERROR,
				        "%s: Out of vmalloc memory, unable to map pages for %s.",
				        __func__,
				        ui8Pattern == PVRSRV_ZERO_VALUE ? "zeroing" : "poisoning"));
				return PVRSRV_ERROR_OUT_OF_MEMORY;
			}
			else
			{
				/* Halve the pages to map at once and try again. */
				uiMaxPagesToMap = uiMaxPagesToMap >> 1;
				continue;
			}
		}

		if (pgprot_val(pgprot) == pgprot_val(pgprot_noncached(PAGE_KERNEL)))
		{
			/* this is most likely unnecessary as all pages must be 8-bytes
			 * aligned so there unaligned access is impossible */
			OSDeviceMemSet(pvAddr, ui8Pattern, PAGE_SIZE * uiToClean);
		}
		else if (pgprot_val(pgprot) == pgprot_val(pgprot_writecombine(PAGE_KERNEL)))
		{
			OSCachedMemSetWMB(pvAddr, ui8Pattern, PAGE_SIZE * uiToClean);
		}
		else
		{
			OSCachedMemSet(pvAddr, ui8Pattern, PAGE_SIZE * uiToClean);
		}
		pvr_vunmap(pvAddr, uiToClean, pgprot);

		ppsCleanArray = &(ppsCleanArray[uiToClean]);
		uiNumToClean -= uiToClean;
	}

	return PVRSRV_OK;
}

static PVRSRV_ERROR
_CleanupThread_CleanPages(void *pvData)
{
	LinuxCleanupData *psCleanupData = (LinuxCleanupData*) pvData;
	LinuxPagePoolEntry *psPagePoolEntry = psCleanupData->psPoolEntry;
	struct list_head *psPoolHead = NULL;
	IMG_UINT32 *puiCounter = NULL;
#if defined(PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES)
	PVRSRV_ERROR eError;
	pgprot_t pgprot;
	IMG_UINT32 i;
#endif /* defined(PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES) */

	/* Get the correct pool for this caching mode. */
	_GetPoolListHead(psCleanupData->ui32CPUCacheMode , &psPoolHead, &puiCounter);

#if defined(PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES)
	switch (PVRSRV_CPU_CACHE_MODE(psCleanupData->ui32CPUCacheMode))
	{
		case PVRSRV_MEMALLOCFLAG_CPU_UNCACHED:
#if defined(CONFIG_X86)
			/* For x86 we can only map with the same attributes
			 * as in the PAT settings*/
			pgprot = pgprot_noncached(PAGE_KERNEL);
			break;
#endif

		case PVRSRV_MEMALLOCFLAG_CPU_UNCACHED_WC:
			pgprot = pgprot_writecombine(PAGE_KERNEL);
			break;

		default:
			PVR_DPF((PVR_DBG_ERROR,
					"%s: Unknown caching mode to set page protection flags.",
					__func__));
			eError = PVRSRV_ERROR_INVALID_PARAMS;
			goto eExit;
	}

	/* Map and fill the pages with zeros.
	 * For large page arrays do it PVR_LINUX_PHYSMEM_MAX_KMAP_SIZE
	 * at a time. */
	eError = _MemsetPageArray(psPagePoolEntry->uiItemsRemaining,
	                          psPagePoolEntry->ppsPageArray,
				pgprot, PVRSRV_ZERO_VALUE, 0);
	if (eError != PVRSRV_OK)
	{
		goto eExit;
	}
#endif /* defined(PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES) */

	/* Lock down pool and add item */
	_PagePoolLock();

	/* Pool counters were already updated so don't do it here again*/

	/* The pages are all zeroed so return them to the pool. */
	list_add_tail(&psPagePoolEntry->sPagePoolItem, psPoolHead);

	_DumpPoolStructure();

#if defined(PVRSRV_ENABLE_PROCESS_STATS)
	/* Calling PVRSRVStatsIncrMemAllocPoolStat and PVRSRVStatsDecrMemAllocPoolStat
	 * inside page pool lock ensures that the stat reflects the state of the pool. */
	PVRSRVStatsIncrMemAllocPoolStat(PAGE_SIZE * psPagePoolEntry->uiItemsRemaining);
#endif

	_PagePoolUnlock();

	OSFreeMem(pvData);
	OSAtomicDecrement(&g_iPoolCleanTasks);

	return PVRSRV_OK;

#if defined(PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES)
eExit:
	/* we failed to zero the pages so return the error so we can
	 * retry during the next spin */
	if ((psCleanupData->sCleanupWork.ui32RetryCount - 1) > 0)
	{
		return eError;
	}

	/* this was the last retry, give up and free pages to OS */
	PVR_DPF((PVR_DBG_ERROR,
			"%s: Deferred task error, freeing pages to OS.",
			__func__));
	_PagePoolLock();

	*puiCounter -= psPagePoolEntry->uiItemsRemaining;

	_PagePoolUnlock();

	for (i = 0; i < psCleanupData->psPoolEntry->uiItemsRemaining; i++)
	{
		_FreeOSPage(0, IMG_TRUE, psPagePoolEntry->ppsPageArray[i]);
	}
	OSFreeMemNoStats(psPagePoolEntry->ppsPageArray);
	kmem_cache_free(g_psLinuxPagePoolCache, psPagePoolEntry);
	OSFreeMem(psCleanupData);

	OSAtomicDecrement(&g_iPoolCleanTasks);

	return PVRSRV_OK;
#endif /* defined(PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES) */
}


/* Put page array to the page pool.
 * Handles locking and checks whether the pages are
 * suitable to be stored in the pool. */
static inline IMG_BOOL
_PutPagesToPoolLocked(IMG_UINT32 ui32CPUCacheFlags,
					  struct page **ppsPageArray,
					  IMG_UINT32 uiOrder,
					  IMG_UINT32 uiNumPages)
{
	LinuxCleanupData *psCleanupData;
	PVRSRV_CLEANUP_THREAD_WORK *psCleanupThreadFn;
#if defined(SUPPORT_PHYSMEM_TEST)
	PVRSRV_DATA *psPVRSRVData = PVRSRVGetPVRSRVData();
#endif

	if (uiOrder == 0 &&
		!PVRSRV_CHECK_CPU_CACHED(ui32CPUCacheFlags))
	{
		IMG_UINT32 uiEntries;
		IMG_UINT32 *puiCounter;
		struct list_head *psPoolHead;


		_PagePoolLock();

		uiEntries = _PagesInPoolUnlocked();

		/* Check for number of current page pool entries and whether
		 * we have other asynchronous tasks in-flight */
		if ( (uiEntries < g_ui32PagePoolMaxEntries) &&
		     ((uiEntries + uiNumPages) <
		      (g_ui32PagePoolMaxEntries + g_ui32PagePoolMaxExcessEntries) ))
		{
			if (OSAtomicIncrement(&g_iPoolCleanTasks) <=
					PVR_LINUX_PHYSMEM_MAX_ASYNC_CLEAN_TASKS)
			{
#if defined(SUPPORT_PHYSMEM_TEST)
				if (!psPVRSRVData->hCleanupThread)
				{
					goto eDecrement;
				}
#endif

				psCleanupData = OSAllocMem(sizeof(*psCleanupData));

				if (!psCleanupData)
				{
					PVR_DPF((PVR_DBG_ERROR,
							 "%s: Failed to get memory for deferred page pool cleanup. "
							 "Trying to free pages immediately",
							 __func__));
					goto eDecrement;
				}

				psCleanupThreadFn = &psCleanupData->sCleanupWork;
				psCleanupData->ui32CPUCacheMode = ui32CPUCacheFlags;
				psCleanupData->psPoolEntry = kmem_cache_alloc(g_psLinuxPagePoolCache, GFP_KERNEL);

				if (!psCleanupData->psPoolEntry)
				{
					PVR_DPF((PVR_DBG_ERROR,
							 "%s: Failed to get memory for deferred page pool cleanup. "
							 "Trying to free pages immediately",
							 __func__));
					goto eFreeCleanupData;
				}

				if (!_GetPoolListHead(ui32CPUCacheFlags, &psPoolHead, &puiCounter))
				{
					PVR_DPF((PVR_DBG_ERROR,
							 "%s: Failed to get correct page pool",
							 __func__));
					goto eFreePoolEntry;
				}

				/* Increase counter here to avoid deferred cleanup tasks piling up */
				*puiCounter = *puiCounter + uiNumPages;

				psCleanupData->psPoolEntry->ppsPageArray = ppsPageArray;
				psCleanupData->psPoolEntry->uiItemsRemaining = uiNumPages;

				psCleanupThreadFn->pfnFree = _CleanupThread_CleanPages;
				psCleanupThreadFn->pvData = psCleanupData;
				psCleanupThreadFn->bDependsOnHW = IMG_FALSE;
				CLEANUP_THREAD_SET_RETRY_COUNT(psCleanupThreadFn,
				                               CLEANUP_THREAD_RETRY_COUNT_DEFAULT);

				/* We must not hold the pool lock when calling AddWork because it might call us back to
				 * free pooled pages directly when unloading the driver	 */
				_PagePoolUnlock();

				PVRSRVCleanupThreadAddWork(psCleanupThreadFn);


			}
			else
			{
				goto eDecrement;
			}

		}
		else
		{
			goto eUnlock;
		}
	}
	else
	{
		goto eExitFalse;
	}

	return IMG_TRUE;

eFreePoolEntry:
	OSFreeMem(psCleanupData->psPoolEntry);
eFreeCleanupData:
	OSFreeMem(psCleanupData);
eDecrement:
	OSAtomicDecrement(&g_iPoolCleanTasks);
eUnlock:
	_PagePoolUnlock();
eExitFalse:
	return IMG_FALSE;
}

/* Get the GFP flags that we pass to the page allocator */
static inline gfp_t
_GetGFPFlags(IMG_BOOL bZero,
             PVRSRV_DEVICE_NODE *psDevNode)
{
	struct device *psDev = psDevNode->psDevConfig->pvOSDevice;
	gfp_t gfp_flags = GFP_USER | __GFP_NOWARN | __GFP_NOMEMALLOC;

#if defined(PVR_LINUX_PHYSMEM_USE_HIGHMEM_ONLY)
	/* Force use of HIGHMEM */
	gfp_flags |= __GFP_HIGHMEM;

	PVR_UNREFERENCED_PARAMETER(psDev);
#else
	if (psDev)
	{
#if defined(CONFIG_64BIT) || defined(CONFIG_ARM_LPAE) || defined(CONFIG_X86_PAE)
		if (*psDev->dma_mask > DMA_BIT_MASK(32))
		{
			/* If our system is able to handle large addresses use highmem */
			gfp_flags |= __GFP_HIGHMEM;
		}
		else if (*psDev->dma_mask == DMA_BIT_MASK(32))
		{
			/* Limit to 32 bit.
			 * Achieved by setting __GFP_DMA32 for 64 bit systems */
			gfp_flags |= __GFP_DMA32;
		}
		else
		{
			/* Limit to size of DMA zone. */
			gfp_flags |= __GFP_DMA;
		}
#else
		if (*psDev->dma_mask < DMA_BIT_MASK(32))
		{
			gfp_flags |= __GFP_DMA;
		}
		else
		{
			gfp_flags |= __GFP_HIGHMEM;
		}
#endif /* if defined(CONFIG_64BIT) || defined(CONFIG_ARM_LPAE) || defined(CONFIG_X86_PAE) */
	}

#endif /* if defined(PVR_LINUX_PHYSMEM_USE_HIGHMEM_ONLY) */

	if (bZero)
	{
		gfp_flags |= __GFP_ZERO;
	}

	return gfp_flags;
}

/*
 * @Function _PoisonDevicePage
 *
 * @Description  Poisons a device page. In normal case the device page has the
 *               same size as the OS page and so the ui32DevPageOrder will be
 *               equal to 0 and page argument will point to one OS page
 *               structure. In case of Non4K pages the order will be greater
 *               than 0 and page argument will point to an array of OS
 *               allocated pages.
 *
 * @Input psDevNode          pointer to the device object
 * @Input page               array of the pages allocated by from the OS
 * @Input ui32DevPageOrder   order of the page (same as the one used to allocate
 *                           the page array by alloc_pages())
 * @Input ui32CPUCacheFlags  CPU cache flags applied to the page
 * @Input ui8PoisonValue     value used to poison the page
 */
static void
_PoisonDevicePage(PVRSRV_DEVICE_NODE *psDevNode,
                  struct page *page,
                  IMG_UINT32 ui32DevPageOrder,
                  IMG_UINT32 ui32CPUCacheFlags,
                  IMG_BYTE ui8PoisonValue)
{
	IMG_UINT32 ui32OsPageIdx;

	for (ui32OsPageIdx = 0;
	     ui32OsPageIdx < (1U << ui32DevPageOrder);
	     ui32OsPageIdx++)
	{
		struct page *current_page = page + ui32OsPageIdx;
		IMG_CPU_PHYADDR sCPUPhysAddrStart = {page_to_phys(current_page)};
		IMG_CPU_PHYADDR sCPUPhysAddrEnd = {sCPUPhysAddrStart.uiAddr + PAGE_SIZE};

		void *kvaddr = kmap_atomic(current_page);

		/* kmap_atomic maps pages as cached so it's safe to use OSCachedMemSet
		 * here (also pages are always 8 bytes aligned anyway) */
		OSCachedMemSet(kvaddr, ui8PoisonValue, PAGE_SIZE);

		OSCPUCacheFlushRangeKM(psDevNode, kvaddr, kvaddr + PAGE_SIZE,
		                       sCPUPhysAddrStart, sCPUPhysAddrEnd);

		kunmap_atomic(kvaddr);
	}
}

/* Allocate and initialise the structure to hold the metadata of the allocation */
static PVRSRV_ERROR
_AllocOSPageArray(PVRSRV_DEVICE_NODE *psDevNode,
				  PMR_SIZE_T uiSize,
				  IMG_UINT32 ui32NumPhysChunks,
				  IMG_UINT32 ui32NumVirtChunks,
				  IMG_UINT32 uiLog2AllocPageSize,
				  IMG_UINT32 ui32AllocFlags,
				  IMG_UINT32 ui32CPUCacheFlags,
				  IMG_PID uiPid,
				  PMR_OSPAGEARRAY_DATA **ppsPageArrayDataPtr)
{
	PVRSRV_ERROR eError;
	IMG_UINT32 uiNumOSPageSizeVirtPages;
	IMG_UINT32 uiNumDevPageSizeVirtPages;
	PMR_OSPAGEARRAY_DATA *psPageArrayData;
	IMG_UINT64 ui64DmaMask = 0;
	PVR_UNREFERENCED_PARAMETER(ui32NumPhysChunks);

	/* Use of cast below is justified by the assertion that follows to
	 * prove that no significant bits have been truncated */
	uiNumOSPageSizeVirtPages = (IMG_UINT32) (((uiSize - 1) >> PAGE_SHIFT) + 1);
	PVR_ASSERT(((PMR_SIZE_T) uiNumOSPageSizeVirtPages << PAGE_SHIFT) == uiSize);

	uiNumDevPageSizeVirtPages = uiNumOSPageSizeVirtPages >> (uiLog2AllocPageSize - PAGE_SHIFT);

	/* Allocate the struct to hold the metadata */
	psPageArrayData = kmem_cache_alloc(g_psLinuxPageArray, GFP_KERNEL);
	if (psPageArrayData == NULL)
	{
		PVR_DPF((PVR_DBG_ERROR,
				 "%s: OS refused the memory allocation for the private data.",
				 __func__));
		eError = PVRSRV_ERROR_OUT_OF_MEMORY;
		goto e_freed_none;
	}

	/*
	 * Allocate the page array
	 *
	 * We avoid tracking this memory because this structure might go into the page pool.
	 * The OS can drain the pool asynchronously and when doing that we have to avoid
	 * any potential deadlocks.
	 *
	 * In one scenario the process stats vmalloc hash table lock is held and then
	 * the oom-killer softirq is trying to call _ScanObjectsInPagePool(), it must not
	 * try to acquire the vmalloc hash table lock again.
	 */
	psPageArrayData->pagearray = OSAllocZMemNoStats(sizeof(struct page *) * uiNumDevPageSizeVirtPages);
	if (psPageArrayData->pagearray == NULL)
	{
		eError = PVRSRV_ERROR_OUT_OF_MEMORY;
		goto e_free_kmem_cache;
	}
	else
	{
		if (BIT_ISSET(ui32AllocFlags, FLAG_IS_CMA))
		{
			/* Allocate additional DMA/CMA cpu kernel virtual address & device bus address array state */
			psPageArrayData->dmavirtarray = OSAllocZMemNoStats(sizeof(void*) * uiNumDevPageSizeVirtPages);
			if (psPageArrayData->dmavirtarray == NULL)
			{
				eError = PVRSRV_ERROR_OUT_OF_MEMORY;
				goto e_free_pagearray;
			}

			psPageArrayData->dmaphysarray = OSAllocZMemNoStats(sizeof(dma_addr_t) * uiNumDevPageSizeVirtPages);
			if (psPageArrayData->dmaphysarray == NULL)
			{
				eError = PVRSRV_ERROR_OUT_OF_MEMORY;
				goto e_free_cpuvirtaddrarray;
			}
		}
	}

	if (psDevNode->psDevConfig && psDevNode->psDevConfig->pvOSDevice)
	{
		struct device *psDev = psDevNode->psDevConfig->pvOSDevice;
		ui64DmaMask = *psDev->dma_mask;
	}

	/* Init metadata */
	psPageArrayData->psDevNode = psDevNode;
	psPageArrayData->uiPid = uiPid;
	psPageArrayData->iNumOSPagesAllocated = 0;
	psPageArrayData->uiTotalNumOSPages = uiNumOSPageSizeVirtPages;
	psPageArrayData->uiLog2AllocPageSize = uiLog2AllocPageSize;
	psPageArrayData->ui64DmaMask = ui64DmaMask;
	psPageArrayData->ui32AllocFlags = ui32AllocFlags;
	psPageArrayData->ui32CPUCacheFlags = ui32CPUCacheFlags;
	psPageArrayData->ui32CMAAdjustedPageCount = 0;

	*ppsPageArrayDataPtr = psPageArrayData;
	return PVRSRV_OK;

/* Error path */
e_free_cpuvirtaddrarray:
	OSFreeMemNoStats(psPageArrayData->dmavirtarray);

e_free_pagearray:
	OSFreeMemNoStats(psPageArrayData->pagearray);

e_free_kmem_cache:
	kmem_cache_free(g_psLinuxPageArray, psPageArrayData);
	PVR_DPF((PVR_DBG_ERROR,
			 "%s: OS refused the memory allocation for the page pointer table. "
			 "Did you ask for too much?",
			 __func__));

e_freed_none:
	PVR_ASSERT(eError != PVRSRV_OK);
	return eError;
}

static inline void
_ApplyCacheMaintenance(PVRSRV_DEVICE_NODE *psDevNode,
					   struct page **ppsPage,
					   IMG_UINT32 uiNumPages)
{
	void * pvAddr;

	if (OSCPUCacheOpAddressType() == OS_CACHE_OP_ADDR_TYPE_VIRTUAL)
	{
		pgprot_t pgprot = PAGE_KERNEL;

		IMG_UINT32 uiNumToClean = uiNumPages;
		struct page **ppsCleanArray = ppsPage;

		/* Map and flush page.
		 * For large page arrays do it PVR_LINUX_PHYSMEM_MAX_KMAP_SIZE
		 * at a time. */
		while (uiNumToClean != 0)
		{
			IMG_UINT32 uiToClean = MIN(PVR_LINUX_PHYSMEM_MAX_KMAP_PAGES,
			                           uiNumToClean);
			IMG_CPU_PHYADDR sUnused =
				{ IMG_CAST_TO_CPUPHYADDR_UINT(0xCAFEF00DDEADBEEFULL) };

			pvAddr = pvr_vmap(ppsCleanArray, uiToClean, VM_MAP, pgprot);
			if (!pvAddr)
			{
				PVR_DPF((PVR_DBG_ERROR,
						"Unable to flush page cache for new allocation, skipping flush."));
				return;
			}

			CacheOpExec(psDevNode,
						pvAddr,
						pvAddr + PAGE_SIZE,
						sUnused,
						sUnused,
						PVRSRV_CACHE_OP_FLUSH);

			pvr_vunmap(pvAddr, uiToClean, pgprot);
			ppsCleanArray = &(ppsCleanArray[uiToClean]);
			uiNumToClean -= uiToClean;
		}
	}
	else
	{
		IMG_UINT32 ui32Idx;

		for (ui32Idx = 0; ui32Idx < uiNumPages; ++ui32Idx)
		{
			IMG_CPU_PHYADDR sCPUPhysAddrStart, sCPUPhysAddrEnd;

			pvAddr = kmap(ppsPage[ui32Idx]);
			sCPUPhysAddrStart.uiAddr = page_to_phys(ppsPage[ui32Idx]);
			sCPUPhysAddrEnd.uiAddr = sCPUPhysAddrStart.uiAddr + PAGE_SIZE;

			/* If we're zeroing, we need to make sure the cleared memory is pushed out
			 * of the cache before the cache lines are invalidated */
			CacheOpExec(psDevNode,
						pvAddr,
						pvAddr + PAGE_SIZE,
						sCPUPhysAddrStart,
						sCPUPhysAddrEnd,
						PVRSRV_CACHE_OP_FLUSH);

			kunmap(ppsPage[ui32Idx]);
		}
	}
}

/* Change the caching attribute of pages on x86 systems and takes care of
 * cache maintenance. This function is supposed to be called once for pages that
 * came from alloc_pages(). It expects an array of OS page sized pages!
 *
 * Flush/Invalidate pages in case the allocation is not cached. Necessary to
 * remove pages from the cache that might be flushed later and corrupt memory. */
static inline PVRSRV_ERROR
_ApplyOSPagesAttribute(PVRSRV_DEVICE_NODE *psDevNode,
					   struct page **ppsPage,
					   IMG_UINT32 uiNumPages,
					   IMG_BOOL bFlush,
					   IMG_UINT32 ui32CPUCacheFlags)
{
	PVRSRV_ERROR eError = PVRSRV_OK;
	IMG_BOOL bCPUCached = PVRSRV_CHECK_CPU_CACHED(ui32CPUCacheFlags);
	IMG_BOOL bCPUUncached = PVRSRV_CHECK_CPU_UNCACHED(ui32CPUCacheFlags);
	IMG_BOOL bCPUWriteCombine = PVRSRV_CHECK_CPU_WRITE_COMBINE(ui32CPUCacheFlags);

	if (ppsPage != NULL && uiNumPages != 0)
	{
#if defined(CONFIG_X86)
		/* On x86 we have to set page cache attributes for non-cached pages.
		 * The call is implicitly taking care of all flushing/invalidating
		 * and therefore we can skip the usual cache maintenance after this. */
		if (bCPUUncached || bCPUWriteCombine)
		{
			/* On x86 if we already have a mapping (e.g. low memory) we need to change the mode of
				current mapping before we map it ourselves	*/
			int ret = IMG_FALSE;

			switch (PVRSRV_CPU_CACHE_MODE(ui32CPUCacheFlags))
			{
				case PVRSRV_MEMALLOCFLAG_CPU_UNCACHED:
					ret = set_pages_array_uc(ppsPage, uiNumPages);
					if (ret)
					{
						eError = PVRSRV_ERROR_UNABLE_TO_SET_CACHE_MODE;
						PVR_DPF((PVR_DBG_ERROR, "Setting Linux page caching mode to UC failed, returned %d", ret));
					}
					break;

				case PVRSRV_MEMALLOCFLAG_CPU_UNCACHED_WC:
					ret = set_pages_array_wc(ppsPage, uiNumPages);
					if (ret)
					{
						eError = PVRSRV_ERROR_UNABLE_TO_SET_CACHE_MODE;
						PVR_DPF((PVR_DBG_ERROR, "Setting Linux page caching mode to WC failed, returned %d", ret));
					}
					break;

				case PVRSRV_MEMALLOCFLAG_CPU_CACHED:
					break;

				default:
					break;
			}
		}
		else
#endif
		{
			if ( bFlush ||
				 bCPUUncached || bCPUWriteCombine ||
				 (bCPUCached && PVRSRV_CHECK_CPU_CACHE_CLEAN(ui32CPUCacheFlags)) )
			{
				/*  We can be given pages which still remain in the cache.
					In order to make sure that the data we write through our mappings
					doesn't get overwritten by later cache evictions we invalidate the
					pages that are given to us.

					Note:
					This still seems to be true if we request cold pages, it's just less
					likely to be in the cache. */
				_ApplyCacheMaintenance(psDevNode,
									   ppsPage,
									   uiNumPages);
			}
		}
	}

	return eError;
}

/* Same as _AllocOSPage except it uses DMA framework to perform allocation.
 * uiPageIndex is expected to be the pagearray index where to store the higher order page. */
static PVRSRV_ERROR
_AllocOSPage_CMA(PMR_OSPAGEARRAY_DATA *psPageArrayData,
				gfp_t gfp_flags,
				IMG_UINT32 ui32AllocOrder,
				IMG_UINT32 ui32MinOrder,
				IMG_UINT32 uiPageIndex)
{
	void *virt_addr;
	struct page *page;
	dma_addr_t bus_addr;
	IMG_UINT32 uiAllocIsMisaligned;
	size_t alloc_size = PAGE_SIZE << ui32AllocOrder;
	struct device *dev = psPageArrayData->psDevNode->psDevConfig->pvOSDevice;
	PVR_ASSERT(ui32AllocOrder == ui32MinOrder);

	do
	{
		DisableOOMKiller();
#if defined(PVR_LINUX_PHYSMEM_SUPPRESS_DMA_AC)
		virt_addr = NULL;
#else
		virt_addr = dma_alloc_coherent(dev, alloc_size, &bus_addr, gfp_flags);
#endif
		if (virt_addr == NULL)
		{
			/* The idea here is primarily to support some older kernels with
			   broken or non-functioning DMA/CMA implementations (< Linux-3.4)
			   and to also handle DMA/CMA allocation failures by attempting a
			   normal page allocation though we expect dma_alloc_coherent()
			   already attempts this internally also before failing but
			   nonetheless it does no harm to retry the allocation ourselves */
			page = alloc_pages(gfp_flags, ui32AllocOrder);
			if (page)
			{
				/* Taint bus_addr as alloc_page, needed when freeing;
				   also acquire the low memory page address only, this
				   prevents mapping possible high memory pages into
				   kernel virtual address space which might exhaust
				   the VMALLOC address space */
				bus_addr = DMA_SET_ALLOCPG_ADDR(page_to_phys(page));
				virt_addr = (void*)(uintptr_t) DMA_VADDR_NOT_IN_USE;
			}
			else
			{
				EnableOOMKiller();
				return PVRSRV_ERROR_OUT_OF_MEMORY;
			}
		}
		else
		{
#if !defined(CONFIG_ARM) && !defined(CONFIG_ARM64)
			page = pfn_to_page(bus_addr >> PAGE_SHIFT);
#else
			/* Assumes bus address space is identical to physical address space */
			page = phys_to_page(bus_addr);
#endif
		}
		EnableOOMKiller();

		/* Physical allocation alignment works/hidden behind the scene transparently,
		   we do this here if the allocated buffer address does not meet its alignment
		   requirement by over-allocating using the next power-2 order and reporting
		   aligned-adjusted values back to meet the requested alignment constraint.
		   Evidently we waste memory by doing this so should only do so if we do not
		   initially meet the alignment constraint. */
		uiAllocIsMisaligned = DMA_GET_ADDR(bus_addr) & ((PAGE_SIZE<<ui32MinOrder)-1);
		if (uiAllocIsMisaligned || ui32AllocOrder > ui32MinOrder)
		{
			IMG_BOOL bUsedAllocPages = DMA_IS_ALLOCPG_ADDR(bus_addr);
			if (ui32AllocOrder == ui32MinOrder)
			{
				if (bUsedAllocPages)
				{
					__free_pages(page, ui32AllocOrder);
				}
				else
				{
					dma_free_coherent(dev, alloc_size, virt_addr, bus_addr);
				}

				ui32AllocOrder = ui32AllocOrder + 1;
				alloc_size = PAGE_SIZE << ui32AllocOrder;

				PVR_ASSERT(uiAllocIsMisaligned != 0);
			}
			else
			{
				size_t align_adjust = PAGE_SIZE << ui32MinOrder;

				/* Adjust virtual/bus addresses to meet alignment */
				bus_addr = bUsedAllocPages ? page_to_phys(page) : bus_addr;
				align_adjust = PVR_ALIGN((size_t)bus_addr, align_adjust);
				align_adjust -= (size_t)bus_addr;

				if (align_adjust)
				{
					if (bUsedAllocPages)
					{
						page += align_adjust >> PAGE_SHIFT;
						bus_addr = DMA_SET_ALLOCPG_ADDR(page_to_phys(page));
						virt_addr = (void*)(uintptr_t) DMA_VADDR_NOT_IN_USE;
					}
					else
					{
						bus_addr += align_adjust;
						virt_addr += align_adjust;
#if !defined(CONFIG_ARM) && !defined(CONFIG_ARM64)
						page = pfn_to_page(bus_addr >> PAGE_SHIFT);
#else
						/* Assumes bus address space is identical to physical address space */
						page = phys_to_page(bus_addr);
#endif
					}

					/* Store adjustments in PAGE_SIZE counts */
					align_adjust = align_adjust >> PAGE_SHIFT;
					bus_addr = DMA_SET_ALIGN_ADJUSTMENT(bus_addr, align_adjust);
				}

				/* Taint bus_addr due to over-allocation, allows us to free
				 * memory correctly */
				bus_addr = DMA_SET_ADJUSTED_ADDR(bus_addr);
				uiAllocIsMisaligned = 0;
			}
		}
	} while (uiAllocIsMisaligned);

	/* Convert OSPageSize-based index into DevicePageSize-based index */
	psPageArrayData->ui32CMAAdjustedPageCount += (alloc_size - (PAGE_SIZE << ui32AllocOrder ));

	psPageArrayData->dmavirtarray[uiPageIndex] = virt_addr;
	psPageArrayData->dmaphysarray[uiPageIndex] = bus_addr;
	psPageArrayData->pagearray[uiPageIndex] = page;

	return PVRSRV_OK;
}

/* Allocate a page of order uiAllocOrder and stores it in the page array ppsPage at
 * position uiPageIndex.
 *
 * If the order is higher than 0, it splits the page into multiples and
 * stores them at position uiPageIndex to uiPageIndex+(1<<uiAllocOrder).
 *
 * This function is supposed to be used for uiMinOrder == 0 only! */
static PVRSRV_ERROR
_AllocOSPage(PMR_OSPAGEARRAY_DATA *psPageArrayData,
			gfp_t gfp_flags,
			IMG_UINT32 uiAllocOrder,
			IMG_UINT32 uiMinOrder,
			IMG_UINT32 uiPageIndex)
{
	struct page *psPage;
	IMG_UINT32 ui32Count;

	/* Parameter check. If it fails we write into the wrong places in the array. */
	PVR_ASSERT(uiMinOrder == 0);

	/* Allocate the page */
	DisableOOMKiller();
	psPage = alloc_pages(gfp_flags, uiAllocOrder);
	EnableOOMKiller();

	if (psPage == NULL)
	{
		return PVRSRV_ERROR_OUT_OF_MEMORY;
	}

#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0))
	/* In case we need to, split the higher order page;
	   this should only be used for order-0 allocations
	   as higher order allocations should use DMA/CMA */
	if (uiAllocOrder != 0)
	{
		split_page(psPage, uiAllocOrder);
	}
#endif

	/* Store the page (or multiple split pages) in the page array */
	for (ui32Count = 0; ui32Count < (1 << uiAllocOrder); ui32Count++)
	{
		psPageArrayData->pagearray[uiPageIndex + ui32Count] = &(psPage[ui32Count]);
	}

	return PVRSRV_OK;
}

#if defined(PVRSRV_ENABLE_PROCESS_STATS)
#if defined(PVRSRV_ENABLE_MEMORY_STATS)

static inline void _AddMemAllocRecord_UmaPages(PMR_OSPAGEARRAY_DATA *psPageArrayData,
                                               struct page *psPage)
{
	IMG_CPU_PHYADDR sCPUPhysAddr = { page_to_phys(psPage) };
	PVRSRVStatsAddMemAllocRecord(PVRSRV_MEM_ALLOC_TYPE_ALLOC_UMA_PAGES,
	                             NULL, sCPUPhysAddr,
	                             1 << psPageArrayData->uiLog2AllocPageSize,
	                             psPageArrayData->uiPid
	                             DEBUG_MEMSTATS_VALUES);
}

static inline void _RemoveMemAllocRecord_UmaPages(PMR_OSPAGEARRAY_DATA *psPageArrayData,
                                                  struct page *psPage)
{
	PVRSRVStatsRemoveMemAllocRecord(PVRSRV_MEM_ALLOC_TYPE_ALLOC_UMA_PAGES,
	                                (IMG_UINT64) page_to_phys(psPage),
	                                psPageArrayData->uiPid);
}

#else /* defined(PVRSRV_ENABLE_MEMORY_STATS) */

static inline void _IncrMemAllocStat_UmaPages(size_t uiSize, IMG_PID uiPid)
{
	PVRSRVStatsIncrMemAllocStat(PVRSRV_MEM_ALLOC_TYPE_ALLOC_UMA_PAGES,
	                            uiSize, uiPid);
}

static inline void _DecrMemAllocStat_UmaPages(size_t uiSize, IMG_PID uiPid)
{
	PVRSRVStatsDecrMemAllocStat(PVRSRV_MEM_ALLOC_TYPE_ALLOC_UMA_PAGES,
	                            uiSize, uiPid);
}

#endif /* defined(PVRSRV_ENABLE_MEMORY_STATS) */
#endif /* defined(PVRSRV_ENABLE_PROCESS_STATS) */

/* Allocation of OS pages: We may allocate 2^N order pages at a time for two reasons.
 *
 * Firstly to support device pages which are larger than OS. By asking the OS for 2^N
 * order OS pages at a time we guarantee the device page is contiguous.
 *
 * Secondly for performance where we may ask for 2^N order pages to reduce the number
 * of calls to alloc_pages, and thus reduce time for huge allocations.
 *
 * Regardless of page order requested, we need to break them down to track _OS pages.
 * The maximum order requested is increased if all max order allocations were successful.
 * If any request fails we reduce the max order.
 */
static PVRSRV_ERROR
_AllocOSPages_Fast(PMR_OSPAGEARRAY_DATA *psPageArrayData)
{
	PVRSRV_ERROR eError;
	IMG_UINT32 uiArrayIndex = 0;
	IMG_UINT32 ui32Order;
	IMG_UINT32 ui32MinOrder = psPageArrayData->uiLog2AllocPageSize - PAGE_SHIFT;
	IMG_BOOL bIncreaseMaxOrder = IMG_TRUE;

	IMG_UINT32 ui32NumPageReq;
	IMG_UINT32 uiOSPagesToAlloc;
	IMG_UINT32 uiDevPagesFromPool = 0;

	gfp_t gfp_flags = _GetGFPFlags(ui32MinOrder ? _ShouldInitMem(psPageArrayData->ui32AllocFlags) : IMG_FALSE, /* Zero all pages later as batch */
	                                      psPageArrayData->psDevNode);
	gfp_t ui32GfpFlags;
	gfp_t ui32HighOrderGfpFlags = ((gfp_flags & ~__GFP_RECLAIM) | __GFP_NORETRY);

	struct page **ppsPageArray = psPageArrayData->pagearray;
	struct page **ppsPageAttributeArray = NULL;

	uiOSPagesToAlloc = psPageArrayData->uiTotalNumOSPages;

	/* Try to get pages from the pool since it is faster;
	   the page pool currently only supports zero-order pages
	   thus currently excludes all DMA/CMA allocated memory.
	   _ShouldInitMem() must not be used for bZero argument since it only
	   applies to new pages allocated from the kernel.  */
	_GetPagesFromPoolLocked(psPageArrayData->psDevNode,
							psPageArrayData->ui32CPUCacheFlags,
							uiOSPagesToAlloc,
							ui32MinOrder,
							BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_ZERO),
							ppsPageArray,
							&uiDevPagesFromPool);

	uiArrayIndex = uiDevPagesFromPool;

	if ((uiOSPagesToAlloc - uiDevPagesFromPool) < PVR_LINUX_HIGHORDER_ALLOCATION_THRESHOLD)
	{	/* Small allocations: ask for one device page at a time */
		ui32Order = ui32MinOrder;
		bIncreaseMaxOrder = IMG_FALSE;
	}
	else
	{
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0))
		/* Large zero-order or none zero-order allocations, ask for
		   MAX(max-order, min-order) order pages at a time; alloc
		   failures throttles this down to ZeroOrder allocations */
		ui32Order = MAX(g_uiMaxOrder, ui32MinOrder);
#else
		/* Because split_page() is not available on older kernels
		   we cannot mix-and-match any-order pages in the PMR;
		   only same-order pages must be present in page array.
		   So we unconditionally force it to use ui32MinOrder on
		   these older kernels */
		ui32Order = ui32MinOrder;
#if defined(DEBUG)
		if (! BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
		{
			/* Check that this is zero */
			PVR_ASSERT(! ui32Order);
		}
#endif
#endif
	}

	/* Only if asking for more contiguity than we actually need, let it fail */
	ui32GfpFlags = (ui32Order > ui32MinOrder) ? ui32HighOrderGfpFlags : gfp_flags;
	ui32NumPageReq = (1 << ui32Order);

	while (uiArrayIndex < uiOSPagesToAlloc)
	{
		IMG_UINT32 ui32PageRemain = uiOSPagesToAlloc - uiArrayIndex;

		while (ui32NumPageReq > ui32PageRemain)
		{
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0))
			/* Pages to request is larger than that remaining
			   so ask for less so never over allocate */
			ui32Order = MAX(ui32Order >> 1, ui32MinOrder);
#else
			/* Pages to request is larger than that remaining so
			   do nothing thus over allocate as we do not support
			   mix/match of any-order pages in PMR page-array in
			   older kernels (simplifies page free logic) */
			PVR_ASSERT(ui32Order == ui32MinOrder);
#endif
			ui32NumPageReq = (1 << ui32Order);
			ui32GfpFlags = (ui32Order > ui32MinOrder) ? ui32HighOrderGfpFlags : gfp_flags;
		}

		if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
		{
			/* As the DMA/CMA framework rounds-up request to the
			   next power-of-two, we request multiple uiMinOrder
			   pages to satisfy allocation request in order to
			   minimise wasting memory */
			eError = _AllocOSPage_CMA(psPageArrayData,
									  ui32GfpFlags,
									  ui32Order,
									  ui32MinOrder,
									  uiArrayIndex >> ui32MinOrder);
		}
		else
		{
			/* Allocate uiOrder pages at uiArrayIndex */
			eError = _AllocOSPage(psPageArrayData,
								  ui32GfpFlags,
								  ui32Order,
								  ui32MinOrder,
								  uiArrayIndex);
		}

		if (eError == PVRSRV_OK)
		{
			/* Successful request. Move onto next. */
			uiArrayIndex += ui32NumPageReq;
		}
		else
		{
			if (ui32Order > ui32MinOrder)
			{
				/* Last request failed. Let's ask for less next time */
				ui32Order = MAX(ui32Order >> 1, ui32MinOrder);
				bIncreaseMaxOrder = IMG_FALSE;
				ui32NumPageReq = (1 << ui32Order);
				ui32GfpFlags = (ui32Order > ui32MinOrder) ? ui32HighOrderGfpFlags : gfp_flags;
				g_uiMaxOrder = ui32Order;
#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,10,0))
				/* We should not trigger this code path in older kernels,
				   this is enforced by ensuring ui32Order == ui32MinOrder */
				PVR_ASSERT(ui32Order == ui32MinOrder);
#endif
			}
			else
			{
				/* Failed to alloc pages at required contiguity. Failed allocation */
				PVR_DPF((PVR_DBG_ERROR, "%s: %s failed to honour request at %u of %u, flags = %x, order = %u (%s)",
								__func__,
								BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA) ? "dma_alloc_coherent" : "alloc_pages",
								uiArrayIndex,
								uiOSPagesToAlloc,
								ui32GfpFlags,
								ui32Order,
								PVRSRVGetErrorString(eError)));
				eError = PVRSRV_ERROR_PMR_FAILED_TO_ALLOC_PAGES;
				goto e_free_pages;
			}
		}
	}

	if (bIncreaseMaxOrder && (g_uiMaxOrder < PVR_LINUX_PHYSMEM_MAX_ALLOC_ORDER_NUM))
	{	/* All successful allocations on max order. Let's ask for more next time */
		g_uiMaxOrder++;
	}

	/* Construct table of page pointers to apply attributes */
	ppsPageAttributeArray = &ppsPageArray[uiDevPagesFromPool];
	if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
	{
		IMG_UINT32 uiIdx, uiIdy, uiIdz;

		ppsPageAttributeArray = OSAllocMem(sizeof(struct page *) * uiOSPagesToAlloc);
		PVR_LOG_GOTO_IF_NOMEM(ppsPageAttributeArray, eError, e_free_pages);

		for (uiIdx = 0; uiIdx < uiOSPagesToAlloc; uiIdx += ui32NumPageReq)
		{
			uiIdy = uiIdx >> ui32Order;
			for (uiIdz = 0; uiIdz < ui32NumPageReq; uiIdz++)
			{
				ppsPageAttributeArray[uiIdx+uiIdz] = ppsPageArray[uiIdy];
				ppsPageAttributeArray[uiIdx+uiIdz] += uiIdz;
			}
		}
	}

	if (_ShouldInitMem(psPageArrayData->ui32AllocFlags) && ui32MinOrder == 0)
	{
		eError = _MemsetPageArray(uiOSPagesToAlloc - uiDevPagesFromPool,
		                          ppsPageAttributeArray, PAGE_KERNEL,
					PVRSRV_ZERO_VALUE, 0);
		if (eError != PVRSRV_OK)
		{
			PVR_DPF((PVR_DBG_ERROR, "Failed to zero pages (fast)"));
			goto e_free_pages;
		}
	}
	else if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_POISON_ON_ALLOC))
	{
		/* need to call twice because ppsPageArray and ppsPageAttributeArray
		 * can point to different allocations: first for pages obtained from
		 * the pool and then the remaining pages */
		eError = _MemsetPageArray(uiDevPagesFromPool, ppsPageArray, PAGE_KERNEL,
			PVRSRV_POISON_ON_ALLOC_VALUE, 0);
		if (eError != PVRSRV_OK)
		{
			PVR_DPF((PVR_DBG_ERROR, "Failed to poison pages (fast)"));
		}
		eError = _MemsetPageArray(uiOSPagesToAlloc - uiDevPagesFromPool,
		                          ppsPageAttributeArray, PAGE_KERNEL,
						PVRSRV_POISON_ON_ALLOC_VALUE, 0);
		if (eError != PVRSRV_OK)
		{
			PVR_DPF((PVR_DBG_ERROR, "Failed to poison pages (fast)"));
		}

		/* for poisoning need to also flush the pool pages as the 0s have
		 * been overwritten */
		_ApplyCacheMaintenance(psPageArrayData->psDevNode, ppsPageArray,
		                       uiDevPagesFromPool);
	}

	/* Do the cache management as required */
	eError = _ApplyOSPagesAttribute(psPageArrayData->psDevNode,
									ppsPageAttributeArray,
									uiOSPagesToAlloc - uiDevPagesFromPool,
									BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_ZERO) ||
									BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_POISON_ON_ALLOC),
									psPageArrayData->ui32CPUCacheFlags);
	if (eError != PVRSRV_OK)
	{
		PVR_DPF((PVR_DBG_ERROR, "Failed to set page attributes"));
		goto e_free_pages;
	}
	else
	{
		if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
		{
			OSFreeMem(ppsPageAttributeArray);
		}
	}

	/* Update metadata */
	psPageArrayData->iNumOSPagesAllocated = psPageArrayData->uiTotalNumOSPages;

#if defined(PVRSRV_ENABLE_PROCESS_STATS)
	{
#if defined(PVRSRV_ENABLE_MEMORY_STATS)
		IMG_UINT32 ui32NumPages =
		        psPageArrayData->iNumOSPagesAllocated >> ui32MinOrder;
		IMG_UINT32 i;

		for (i = 0; i < ui32NumPages; i++)
		{
			if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
			{
				_AddMemAllocRecord_UmaPages(psPageArrayData, ppsPageArray[i]);
			}
			else
			{
				_AddMemAllocRecord_UmaPages(psPageArrayData, ppsPageArray[i << ui32MinOrder]);
			}
		}
#else /* defined(PVRSRV_ENABLE_MEMORY_STATS) */
		_IncrMemAllocStat_UmaPages(((uiOSPagesToAlloc * PAGE_SIZE)+(psPageArrayData->ui32CMAAdjustedPageCount)),
		                           psPageArrayData->uiPid);
#endif /* defined(PVRSRV_ENABLE_MEMORY_STATS) */
	}
#endif /* defined(PVRSRV_ENABLE_PROCESS_STATS) */

	return PVRSRV_OK;

/* Error path */
e_free_pages:
	{
		IMG_UINT32 ui32PageToFree;

		if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
		{
			IMG_UINT32 uiDevArrayIndex = uiArrayIndex >> ui32Order;
			IMG_UINT32 uiDevPageSize = PAGE_SIZE << ui32Order;
			PVR_ASSERT(ui32Order == ui32MinOrder);

			if (ppsPageAttributeArray)
			{
				OSFreeMem(ppsPageAttributeArray);
			}

			for (ui32PageToFree = 0; ui32PageToFree < uiDevArrayIndex; ui32PageToFree++)
			{
				_FreeOSPage_CMA(psPageArrayData->psDevNode->psDevConfig->pvOSDevice,
								uiDevPageSize,
								ui32MinOrder,
								psPageArrayData->dmavirtarray[ui32PageToFree],
								psPageArrayData->dmaphysarray[ui32PageToFree],
								ppsPageArray[ui32PageToFree]);
				psPageArrayData->dmaphysarray[ui32PageToFree]= (dma_addr_t)0;
				psPageArrayData->dmavirtarray[ui32PageToFree] = NULL;
				ppsPageArray[ui32PageToFree] = NULL;
			}
		}
		else
		{
			/* Free the pages we got from the pool */
			for (ui32PageToFree = 0; ui32PageToFree < uiDevPagesFromPool; ui32PageToFree++)
			{
				_FreeOSPage(ui32MinOrder,
							BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_UNSET_MEMORY_TYPE),
							ppsPageArray[ui32PageToFree]);
				ppsPageArray[ui32PageToFree] = NULL;
			}

			for (ui32PageToFree = uiDevPagesFromPool; ui32PageToFree < uiArrayIndex; ui32PageToFree++)
			{
				_FreeOSPage(ui32MinOrder, IMG_FALSE, ppsPageArray[ui32PageToFree]);
				ppsPageArray[ui32PageToFree] = NULL;
			}
		}

		return eError;
	}
}

static INLINE PVRSRV_ERROR
_CheckIfIndexInRange(IMG_UINT32 ui32Index, IMG_UINT32 *pui32Indices, IMG_UINT32 ui32Limit)
{
	if (pui32Indices[ui32Index] >= ui32Limit)
	{
		PVR_DPF((PVR_DBG_ERROR, "%s: Given alloc index %u at %u is larger than page array %u.",
		        __func__, pui32Indices[ui32Index], ui32Index, ui32Limit));
		return PVRSRV_ERROR_DEVICEMEM_OUT_OF_RANGE;
	}

	return PVRSRV_OK;
}

static INLINE PVRSRV_ERROR
_CheckIfPageNotAllocated(IMG_UINT32 ui32Index, IMG_UINT32 *pui32Indices, struct page **ppsPageArray)
{
	if (ppsPageArray[pui32Indices[ui32Index]] != NULL)
	{
		PVR_DPF((PVR_DBG_ERROR, "%s: Mapping number %u at page array index %u already exists. "
		        "Page struct %p", __func__, pui32Indices[ui32Index], ui32Index,
		        ppsPageArray[pui32Indices[ui32Index]]));
		return PVRSRV_ERROR_PMR_MAPPING_ALREADY_EXISTS;
	}

	return PVRSRV_OK;
}

/* Allocation of OS pages: This function is used for sparse allocations.
 *
 * Sparse allocations provide only a proportion of sparse physical backing within the total
 * virtual range. */
static PVRSRV_ERROR
_AllocOSPages_Sparse(PMR_OSPAGEARRAY_DATA *psPageArrayData,
					 IMG_UINT32 *puiAllocIndices,
					 IMG_UINT32 uiDevPagesToAlloc)
{
	PVRSRV_ERROR eError;
	IMG_UINT32 i;
	struct page **ppsPageArray = psPageArrayData->pagearray;
	IMG_UINT32 uiOrder = psPageArrayData->uiLog2AllocPageSize - PAGE_SHIFT;
	IMG_UINT32 uiDevPagesFromPool = 0;
	IMG_UINT32 uiOSPagesToAlloc = uiDevPagesToAlloc * (1 << uiOrder);
	IMG_UINT32 uiDevPagesAllocated = psPageArrayData->uiTotalNumOSPages >> uiOrder;
	const IMG_UINT32 ui32AllocFlags = psPageArrayData->ui32AllocFlags;
	gfp_t ui32GfpFlags = _GetGFPFlags(uiOrder ? _ShouldInitMem(ui32AllocFlags) : IMG_FALSE, /* Zero pages later as batch */
									  psPageArrayData->psDevNode);

	/* We use this page array to receive pages from the pool and then reuse it afterwards to
	 * store pages that need their cache attribute changed on x86 */
	struct page **ppsTempPageArray;
	IMG_UINT32 uiTempPageArrayIndex = 0;

	/* Allocate the temporary page array that we need here to receive pages
	 * from the pool and to store pages that need their caching attributes changed.
	 * Allocate number of OS pages to be able to use the attribute function later. */
	ppsTempPageArray = OSAllocMem(sizeof(struct page*) * uiOSPagesToAlloc);
	PVR_LOG_GOTO_IF_NOMEM(ppsTempPageArray, eError, e_exit);

	/* Check the requested number of pages if they fit in the page array */
	if (uiDevPagesAllocated <
	        ((psPageArrayData->iNumOSPagesAllocated >> uiOrder) + uiDevPagesToAlloc))
	{
		PVR_DPF((PVR_DBG_ERROR,
				 "%s: Trying to allocate more pages (Order %u) than this buffer can handle, "
				 "Request + Allocated < Max! Request %u, Allocated %u, Max %u.",
				 __func__,
				 uiOrder,
				 uiDevPagesToAlloc,
				 psPageArrayData->iNumOSPagesAllocated >> uiOrder,
				 uiDevPagesAllocated));
		eError = PVRSRV_ERROR_PMR_BAD_MAPPINGTABLE_SIZE;
		goto e_free_temp_array;
	}

	/* Try to get pages from the pool since it is faster. The pages from pool are going to be
	 * allocated only if:
	 * - PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES == 1 && uiOrder == 0
	 * - PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES == 0 && uiOrder == 0 &&
	 *   !(BIT_ISSET(ui32AllocFlags, FLAG_ZERO))
	 * _ShouldInitMem() must not be used for bZero argument since it only
	 * applies to new pages allocated from the kernel.  */
	_GetPagesFromPoolLocked(psPageArrayData->psDevNode,
							psPageArrayData->ui32CPUCacheFlags,
							uiDevPagesToAlloc,
							uiOrder,
							BIT_ISSET(ui32AllocFlags, FLAG_ZERO),
							ppsTempPageArray,
							&uiDevPagesFromPool);

	/* In general device pages can have higher order than 0 but page pool always provides only 0
	 * order pages so they can be assigned to the OS pages values (in other words if we're
	 * allocating non-4k pages uiDevPagesFromPool will always be 0) */
	uiTempPageArrayIndex = uiDevPagesFromPool;

	/* Move pages we got from the pool to the array. */
	for (i = 0; i < uiDevPagesFromPool; i++)
	{
		eError = _CheckIfIndexInRange(i, puiAllocIndices, uiDevPagesAllocated);
		PVR_GOTO_IF_ERROR(eError, e_free_pool_pages);
		eError = _CheckIfPageNotAllocated(i, puiAllocIndices, ppsPageArray);
		PVR_GOTO_IF_ERROR(eError, e_free_pool_pages);

		ppsPageArray[puiAllocIndices[i]] = ppsTempPageArray[i];
	}

	/* Allocate pages from the OS */
	for (i = uiDevPagesFromPool; i < uiDevPagesToAlloc; i++)
	{
		eError = _CheckIfIndexInRange(i, puiAllocIndices, uiDevPagesAllocated);
		PVR_GOTO_IF_ERROR(eError, e_free_pages);
		eError = _CheckIfPageNotAllocated(i, puiAllocIndices, ppsPageArray);
		PVR_GOTO_IF_ERROR(eError, e_free_pages);

		/* Allocated pages and assign them the array. */
		if (BIT_ISSET(ui32AllocFlags, FLAG_IS_CMA))
		{
			/* As the DMA/CMA framework rounds-up request to the
			   next power-of-two, we request multiple uiMinOrder
			   pages to satisfy allocation request in order to
			   minimise wasting memory */
			eError = _AllocOSPage_CMA(psPageArrayData,
									  ui32GfpFlags,
									  uiOrder,
									  uiOrder,
									  puiAllocIndices[i]);
			if (eError != PVRSRV_OK)
			{
				PVR_DPF((PVR_DBG_ERROR, "Failed to alloc CMA pages"));
				goto e_free_pages;
			}
		}
		else
		{
			DisableOOMKiller();
			ppsPageArray[puiAllocIndices[i]] = alloc_pages(ui32GfpFlags, uiOrder);
			EnableOOMKiller();
		}

		if (ppsPageArray[puiAllocIndices[i]] != NULL)
		{
			/* Append pages to the temporary array so it's easier to process
			 * them later on. */

			if (BIT_ISSET(ui32AllocFlags, FLAG_IS_CMA))
			{
				IMG_UINT32 idx;
				struct page *psPageAddr;

				psPageAddr = ppsPageArray[puiAllocIndices[i]];

				/* "divide" CMA pages into OS pages if they have higher order */
				for (idx = 0; idx < (1 << uiOrder); idx++)
				{
					ppsTempPageArray[uiTempPageArrayIndex + idx] = psPageAddr;
					psPageAddr++;
				}
				uiTempPageArrayIndex += (1 << uiOrder);
			}
			else
			{
				ppsTempPageArray[uiTempPageArrayIndex] = ppsPageArray[puiAllocIndices[i]];
				uiTempPageArrayIndex++;
			}
		}
		else
		{
			/* Failed to alloc pages at required contiguity. Failed allocation */
			PVR_DPF((PVR_DBG_ERROR,
			        "%s: alloc_pages failed to honour request at %u of %u, flags = %x, order = %u",
			        __func__, i, uiDevPagesToAlloc, ui32GfpFlags, uiOrder));
			eError = PVRSRV_ERROR_PMR_FAILED_TO_ALLOC_PAGES;
			goto e_free_pages;
		}
	}

	if (_ShouldInitMem(ui32AllocFlags) && uiOrder == 0)
	{
		/* At this point this array contains pages allocated from the page pool at its start
		 * and pages allocated from the OS after that.
		 * If there are pages from the pool here they must be zeroed already hence we don't have
		 * to do it again. This is because if PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES is enabled pool pages
		 * are zeroed in the cleanup thread. If it's disabled they aren't, and in that case we never
		 * allocate pages with FLAG_ZERO from the pool. This is why those pages need to be zeroed
		 * here.
		 * All of the above is true for the 0 order pages. For higher order we never allocated from
		 * the pool and those pages are allocated already zeroed from the OS.
		 * Long story short we can always skip pages allocated from the pool because they are either
		 * zeroed or we didn't allocate any of them. */
		eError = _MemsetPageArray(uiTempPageArrayIndex - uiDevPagesFromPool,
		                          &ppsTempPageArray[uiDevPagesFromPool],
					PAGE_KERNEL, PVRSRV_ZERO_VALUE, 0);
		PVR_LOG_GOTO_IF_FALSE(eError == PVRSRV_OK, "failed to zero pages (sparse)", e_free_pages);
	}
	else if (BIT_ISSET(ui32AllocFlags, FLAG_POISON_ON_ALLOC))
	{
		/* Here we need to poison all of the pages regardless if they were
		 * allocated from the pool or from the system. */
		eError = _MemsetPageArray(uiTempPageArrayIndex, ppsTempPageArray,
					PAGE_KERNEL, PVRSRV_POISON_ON_ALLOC_VALUE, 0);
		PVR_LOG_IF_FALSE(eError == PVRSRV_OK, "failed to poison pages (sparse)");

		/* We need to flush the cache for the poisoned pool pages here. The flush for the pages
		 * allocated from the system is done below because we also need to add appropriate cache
		 * attributes to them. Pages allocated from the pool already come with correct caching
		 * mode. */
		_ApplyCacheMaintenance(psPageArrayData->psDevNode, ppsTempPageArray, uiDevPagesFromPool);
	}

	/* Do the cache management as required */
	eError = _ApplyOSPagesAttribute(psPageArrayData->psDevNode,
	                                &ppsTempPageArray[uiDevPagesFromPool],
	                                uiTempPageArrayIndex - uiDevPagesFromPool,
	                                BIT_ISSET(ui32AllocFlags, FLAG_ZERO) ||
	                                BIT_ISSET(ui32AllocFlags, FLAG_POISON_ON_ALLOC),
	                                psPageArrayData->ui32CPUCacheFlags);
	if (eError != PVRSRV_OK)
	{
		PVR_DPF((PVR_DBG_ERROR, "Failed to set page attributes"));
		goto e_free_pages;
	}

	/* Update metadata */
	psPageArrayData->iNumOSPagesAllocated += uiOSPagesToAlloc;

	/* Free temporary page array */
	OSFreeMem(ppsTempPageArray);

#if defined(PVRSRV_ENABLE_PROCESS_STATS)
#if defined(PVRSRV_ENABLE_MEMORY_STATS)
	for (i = 0; i < uiDevPagesToAlloc; i++)
	{
		_AddMemAllocRecord_UmaPages(psPageArrayData,
		                            ppsPageArray[puiAllocIndices[i]]);
	}
#else
	_IncrMemAllocStat_UmaPages(((uiOSPagesToAlloc * PAGE_SIZE)+(psPageArrayData->ui32CMAAdjustedPageCount)),
	                           psPageArrayData->uiPid);
#endif
#endif

	return PVRSRV_OK;

e_free_pages:
	if (BIT_ISSET(ui32AllocFlags, FLAG_IS_CMA))
	{
		IMG_UINT32 uiDevPageSize = PAGE_SIZE << uiOrder;

		/* Free the pages we just allocated from the CMA */
		for (; i > uiDevPagesFromPool; i--)
		{
			_FreeOSPage_CMA(psPageArrayData->psDevNode->psDevConfig->pvOSDevice,
			                uiDevPageSize,
			                uiOrder,
			                psPageArrayData->dmavirtarray[puiAllocIndices[i-1]],
			                psPageArrayData->dmaphysarray[puiAllocIndices[i-1]],
			                ppsPageArray[puiAllocIndices[i-1]]);
			psPageArrayData->dmaphysarray[puiAllocIndices[i-1]]= (dma_addr_t) 0;
			psPageArrayData->dmavirtarray[puiAllocIndices[i-1]] = NULL;
			ppsPageArray[puiAllocIndices[i-1]] = NULL;
		}
	}
	else
	{
		/* Free the pages we just allocated from the OS */
		for (; i > uiDevPagesFromPool; i--)
		{
			_FreeOSPage(0, IMG_FALSE, ppsPageArray[puiAllocIndices[i-1]]);
			ppsPageArray[puiAllocIndices[i-1]] = NULL;
		}
	}

e_free_pool_pages:
	/* And now free all of the pages we allocated from the pool. */
	for (i = 0; i < uiDevPagesFromPool; i++)
	{
		_FreeOSPage(0, BIT_ISSET(ui32AllocFlags, FLAG_UNSET_MEMORY_TYPE),
		            ppsTempPageArray[i]);

		/* not using _CheckIfIndexInRange() to not print error message */
		if (puiAllocIndices[i] < uiDevPagesAllocated)
		{
			ppsPageArray[puiAllocIndices[i]] = NULL;
		}
	}

e_free_temp_array:
	OSFreeMem(ppsTempPageArray);

e_exit:
	return eError;
}

/* Allocate pages for a given page array.
 *
 * The executed allocation path depends whether an array with allocation
 * indices has been passed or not */
static PVRSRV_ERROR
_AllocOSPages(PMR_OSPAGEARRAY_DATA *psPageArrayData,
			  IMG_UINT32 *puiAllocIndices,
			  IMG_UINT32 uiPagesToAlloc)
{
	PVRSRV_ERROR eError;
	struct page **ppsPageArray;

	/* Parameter checks */
	PVR_ASSERT(NULL != psPageArrayData);
	if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
	{
		PVR_ASSERT(psPageArrayData->dmaphysarray != NULL);
		PVR_ASSERT(psPageArrayData->dmavirtarray != NULL);
	}
	PVR_ASSERT(psPageArrayData->pagearray != NULL);
	PVR_ASSERT(0 <= psPageArrayData->iNumOSPagesAllocated);

	ppsPageArray = psPageArrayData->pagearray;

	/* Go the sparse alloc path if we have an array with alloc indices.*/
	if (puiAllocIndices != NULL)
	{
		eError = _AllocOSPages_Sparse(psPageArrayData,
									  puiAllocIndices,
									  uiPagesToAlloc);
	}
	else
	{
		eError = _AllocOSPages_Fast(psPageArrayData);
	}

	if (eError != PVRSRV_OK)
	{
		goto e_exit;
	}

	_DumpPageArray(ppsPageArray,
	               psPageArrayData->uiTotalNumOSPages >>
	               (psPageArrayData->uiLog2AllocPageSize - PAGE_SHIFT) );

	PVR_DPF((PVR_DBG_MESSAGE, "physmem_osmem_linux.c: allocated OS memory for PMR @0x%p", psPageArrayData));
	return PVRSRV_OK;

e_exit:
	return eError;
}

/* Same as _FreeOSPage except free memory using DMA framework */
static INLINE void
_FreeOSPage_CMA(struct device *dev,
				size_t alloc_size,
				IMG_UINT32 uiOrder,
				void *virt_addr,
				dma_addr_t dev_addr,
				struct page *psPage)
{
	if (DMA_IS_ALLOCPG_ADDR(dev_addr))
	{
#if defined(CONFIG_X86)
		void *pvPageVAddr = page_address(psPage);
		if (pvPageVAddr)
		{
			int ret = set_memory_wb((unsigned long)pvPageVAddr, 1);
			if (ret)
			{
				PVR_DPF((PVR_DBG_ERROR,
						"%s: Failed to reset page attribute",
						__func__));
			}
		}
#endif

		if (DMA_IS_ADDR_ADJUSTED(dev_addr))
		{
			psPage -= DMA_GET_ALIGN_ADJUSTMENT(dev_addr);
			uiOrder += 1;
		}

		__free_pages(psPage, uiOrder);
	}
	else
	{
		if (DMA_IS_ADDR_ADJUSTED(dev_addr))
		{
			size_t align_adjust;

			align_adjust = DMA_GET_ALIGN_ADJUSTMENT(dev_addr);
			alloc_size = alloc_size << 1;

			dev_addr = DMA_GET_ADDR(dev_addr);
			dev_addr -= align_adjust << PAGE_SHIFT;
			virt_addr -= align_adjust << PAGE_SHIFT;
		}

		dma_free_coherent(dev, alloc_size, virt_addr, DMA_GET_ADDR(dev_addr));
	}
}

/* Free a single page back to the OS.
 * Make sure the cache type is set back to the default value.
 *
 * Note:
 * We must _only_ check bUnsetMemoryType in the case where we need to free
 * the page back to the OS since we may have to revert the cache properties
 * of the page to the default as given by the OS when it was allocated. */
static void
_FreeOSPage(IMG_UINT32 uiOrder,
			IMG_BOOL bUnsetMemoryType,
			struct page *psPage)
{

#if defined(CONFIG_X86)
	void *pvPageVAddr;
	pvPageVAddr = page_address(psPage);

	if (pvPageVAddr && bUnsetMemoryType)
	{
		int ret;

		ret = set_memory_wb((unsigned long)pvPageVAddr, 1);
		if (ret)
		{
			PVR_DPF((PVR_DBG_ERROR, "%s: Failed to reset page attribute",
					 __func__));
		}
	}
#else
	PVR_UNREFERENCED_PARAMETER(bUnsetMemoryType);
#endif
	__free_pages(psPage, uiOrder);
}

/* Free the struct holding the metadata */
static void
_FreeOSPagesArray(PMR_OSPAGEARRAY_DATA *psPageArrayData)
{
	PVR_DPF((PVR_DBG_MESSAGE, "physmem_osmem_linux.c: freed OS memory for PMR @0x%p", psPageArrayData));

	/* Check if the page array actually still exists.
	 * It might be the case that has been moved to the page pool */
	if (psPageArrayData->pagearray != NULL)
	{
		OSFreeMemNoStats(psPageArrayData->pagearray);
	}

	kmem_cache_free(g_psLinuxPageArray, psPageArrayData);
}

/* Free all or some pages from a sparse page array */
static PVRSRV_ERROR
_FreeOSPages_Sparse(PMR_OSPAGEARRAY_DATA *psPageArrayData,
					IMG_UINT32 *pai32FreeIndices,
					IMG_UINT32 ui32FreePageCount)
{
	IMG_BOOL bSuccess;
	IMG_UINT32 uiOrder = psPageArrayData->uiLog2AllocPageSize - PAGE_SHIFT;
	IMG_UINT32 uiPageIndex, i, j, uiTempIdx = 0;
	struct page **ppsPageArray = psPageArrayData->pagearray;
	IMG_UINT32 uiNumPages;

	struct page **ppsTempPageArray;
	IMG_UINT32 uiTempArraySize;

	/* We really should have something to free before we call this */
	PVR_ASSERT(psPageArrayData->iNumOSPagesAllocated != 0);

	if (pai32FreeIndices == NULL)
	{
		uiNumPages = psPageArrayData->uiTotalNumOSPages >> uiOrder;
		uiTempArraySize = psPageArrayData->iNumOSPagesAllocated;
	}
	else
	{
		uiNumPages = ui32FreePageCount;
		uiTempArraySize = ui32FreePageCount << uiOrder;
	}

#if defined(PVRSRV_ENABLE_PROCESS_STATS) && defined(PVRSRV_ENABLE_MEMORY_STATS)
	for (i = 0; i < uiNumPages; i++)
	{
		IMG_UINT32 idx = pai32FreeIndices ? pai32FreeIndices[i] : i;

		if (NULL != ppsPageArray[idx])
		{
			_RemoveMemAllocRecord_UmaPages(psPageArrayData, ppsPageArray[idx]);
		}
	}
#endif

	if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_POISON_ON_FREE))
	{
		for (i = 0; i < uiNumPages; i++)
		{
			IMG_UINT32 idx = pai32FreeIndices ? pai32FreeIndices[i] : i;

			if (NULL != ppsPageArray[idx])
			{
				_PoisonDevicePage(psPageArrayData->psDevNode,
				                  ppsPageArray[idx],
				                  uiOrder,
				                  psPageArrayData->ui32CPUCacheFlags,
				                  PVRSRV_POISON_ON_FREE_VALUE);
			}
			else if (pai32FreeIndices != NULL)
			{
				/* Attempt to poison an index not containing a valid page */
				return PVRSRV_ERROR_PMR_FREE_INVALID_CHUNK;
			}
		}
	}

	if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
	{
		IMG_UINT32 uiDevNumPages = uiNumPages;
		IMG_UINT32 uiDevPageSize = 1<<psPageArrayData->uiLog2AllocPageSize;

		for (i = 0; i < uiDevNumPages; i++)
		{
			IMG_UINT32 idx = pai32FreeIndices ? pai32FreeIndices[i] : i;
			if (NULL != ppsPageArray[idx])
			{
				_FreeOSPage_CMA(psPageArrayData->psDevNode->psDevConfig->pvOSDevice,
								uiDevPageSize,
								uiOrder,
								psPageArrayData->dmavirtarray[idx],
								psPageArrayData->dmaphysarray[idx],
								ppsPageArray[idx]);
				psPageArrayData->dmaphysarray[idx] = (dma_addr_t)0;
				psPageArrayData->dmavirtarray[idx] = NULL;
				ppsPageArray[idx] = NULL;
				uiTempIdx++;
			}
			else if (pai32FreeIndices != NULL)
			{
#if defined(PVRSRV_ENABLE_PROCESS_STATS) && !defined(PVRSRV_ENABLE_MEMORY_STATS)
				/* Attempt to keep memstats consistent in event of fail as we have
				 * freed some pages
				 */
				uiTempIdx <<= uiOrder;
				_DecrMemAllocStat_UmaPages(uiTempIdx * PAGE_SIZE,
										   psPageArrayData->uiPid);
#endif
				/* Attempt to free an already free index, could be duplicated free indices */
				return PVRSRV_ERROR_PMR_FREE_INVALID_CHUNK;
			}
		}
		uiTempIdx <<= uiOrder;
	}
	else
	{

		/* OSAllocMemNoStats required because this code may be run without the bridge lock held */
		ppsTempPageArray = OSAllocMemNoStats(sizeof(struct page*) * uiTempArraySize);
		if (ppsTempPageArray == NULL)
		{
			PVR_DPF((PVR_DBG_ERROR, "%s: Failed free_pages metadata allocation", __func__));
			return PVRSRV_ERROR_OUT_OF_MEMORY;
		}

		/* Put pages in a contiguous array so further processing is easier */
		for (i = 0; i < uiNumPages; i++)
		{
			uiPageIndex = pai32FreeIndices ? pai32FreeIndices[i] : i;
			if (NULL != ppsPageArray[uiPageIndex])
			{
				struct page *psPage = ppsPageArray[uiPageIndex];

				for (j = 0; j < (1<<uiOrder); j++)
				{
					ppsTempPageArray[uiTempIdx] = psPage;
					uiTempIdx++;
					psPage++;
				}

				ppsPageArray[uiPageIndex] = NULL;
			}
			else if (pai32FreeIndices != NULL)
			{
				/* Attempt to free an already free index, could be duplicated free indices.
				 * We don't have a need to unwind here as this isn't something we want to
				 * recover from, we do want to try and maintain some consistency with pages we
				 * can free before the error occurred and adjusting the memstats as required.
				 */
				for (i = 0; i < uiTempIdx; i++)
				{
					__free_pages(ppsTempPageArray[i], 0);
				}

#if defined(PVRSRV_ENABLE_PROCESS_STATS) && !defined(PVRSRV_ENABLE_MEMORY_STATS)
				_DecrMemAllocStat_UmaPages(uiTempIdx * PAGE_SIZE,
										   psPageArrayData->uiPid);
#endif

				OSFreeMemNoStats(ppsTempPageArray);
				return PVRSRV_ERROR_PMR_FREE_INVALID_CHUNK;
			}
		}

		/* Try to move the temp page array to the pool */
		bSuccess = _PutPagesToPoolLocked(psPageArrayData->ui32CPUCacheFlags,
										 ppsTempPageArray,
										 0,
										 uiTempIdx);
		if (bSuccess)
		{
			goto exit_ok;
		}

		/* Free pages and reset page caching attributes on x86 */
#if defined(CONFIG_X86)
		if (uiTempIdx != 0 && BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_UNSET_MEMORY_TYPE))
		{
			int iError;
			iError = set_pages_array_wb(ppsTempPageArray, uiTempIdx);

			if (iError)
			{
				PVR_DPF((PVR_DBG_ERROR, "%s: Failed to reset page attributes", __func__));
			}
		}
#endif

		/* Free the pages */
		for (i = 0; i < uiTempIdx; i++)
		{
			__free_pages(ppsTempPageArray[i], 0);
		}

		/* Free the temp page array here if it did not move to the pool */
		OSFreeMemNoStats(ppsTempPageArray);
	}

exit_ok:

#if defined(PVRSRV_ENABLE_PROCESS_STATS) && !defined(PVRSRV_ENABLE_MEMORY_STATS)
	_DecrMemAllocStat_UmaPages(((uiTempIdx * PAGE_SIZE)-(psPageArrayData->ui32CMAAdjustedPageCount)),
	                           psPageArrayData->uiPid);
#endif

	if (pai32FreeIndices && ((uiTempIdx >> uiOrder) != ui32FreePageCount))
	{
		PVR_DPF((PVR_DBG_ERROR, "%s: Probable sparse duplicate indices: ReqFreeCount: %d "
				"ActualFreedCount: %d", __func__, ui32FreePageCount, (uiTempIdx >> uiOrder)));
	}
	/* Update metadata */
	psPageArrayData->iNumOSPagesAllocated -= uiTempIdx;
	PVR_ASSERT(0 <= psPageArrayData->iNumOSPagesAllocated);
	return PVRSRV_OK;
}

/* Free all the pages in a page array */
static PVRSRV_ERROR
_FreeOSPages_Fast(PMR_OSPAGEARRAY_DATA *psPageArrayData)
{
	IMG_BOOL bSuccess;
	IMG_UINT32 i;
	IMG_UINT32 uiNumPages = psPageArrayData->uiTotalNumOSPages;
	IMG_UINT32 uiOrder = psPageArrayData->uiLog2AllocPageSize - PAGE_SHIFT;
	IMG_UINT32 uiDevNumPages = uiNumPages >> uiOrder;
	IMG_UINT32 uiDevPageSize = PAGE_SIZE << uiOrder;
	struct page **ppsPageArray = psPageArrayData->pagearray;

	/* We really should have something to free before we call this */
	PVR_ASSERT(psPageArrayData->iNumOSPagesAllocated != 0);

#if defined(PVRSRV_ENABLE_PROCESS_STATS)
#if defined(PVRSRV_ENABLE_MEMORY_STATS)
	for (i = 0; i < uiDevNumPages; i++)
	{
		if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
		{
			_RemoveMemAllocRecord_UmaPages(psPageArrayData, ppsPageArray[i]);
		}else
		{
			_RemoveMemAllocRecord_UmaPages(psPageArrayData, ppsPageArray[i << uiOrder]);
		}
	}
#else
	_DecrMemAllocStat_UmaPages(((uiNumPages * PAGE_SIZE)-(psPageArrayData->ui32CMAAdjustedPageCount)),
	                           psPageArrayData->uiPid);
#endif
#endif

	if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_POISON_ON_FREE))
	{
		for (i = 0; i < uiDevNumPages; i++)
		{
			_PoisonDevicePage(psPageArrayData->psDevNode,
			                  ppsPageArray[i],
			                  uiOrder,
			                  psPageArrayData->ui32CPUCacheFlags,
			                  PVRSRV_POISON_ON_FREE_VALUE);
		}
	}

	/* Try to move the page array to the pool */
	bSuccess = _PutPagesToPoolLocked(psPageArrayData->ui32CPUCacheFlags,
									 ppsPageArray,
									 uiOrder,
									 uiNumPages);
	if (bSuccess)
	{
		psPageArrayData->pagearray = NULL;
		goto exit_ok;
	}

	if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_IS_CMA))
	{
		for (i = 0; i < uiDevNumPages; i++)
		{
			_FreeOSPage_CMA(psPageArrayData->psDevNode->psDevConfig->pvOSDevice,
							uiDevPageSize,
							uiOrder,
							psPageArrayData->dmavirtarray[i],
							psPageArrayData->dmaphysarray[i],
							ppsPageArray[i]);
			psPageArrayData->dmaphysarray[i] = (dma_addr_t)0;
			psPageArrayData->dmavirtarray[i] = NULL;
			ppsPageArray[i] = NULL;
		}
	}
	else
	{
#if defined(CONFIG_X86)
		if (BIT_ISSET(psPageArrayData->ui32AllocFlags, FLAG_UNSET_MEMORY_TYPE))
		{
			int ret;

			ret = set_pages_array_wb(ppsPageArray, uiNumPages);
			if (ret)
			{
				PVR_DPF((PVR_DBG_ERROR, "%s: Failed to reset page attributes",
						 __func__));
			}
		}
#endif

		for (i = 0; i < uiNumPages; i++)
		{
			_FreeOSPage(uiOrder, IMG_FALSE, ppsPageArray[i]);
			ppsPageArray[i] = NULL;
		}
	}

exit_ok:
	/* Update metadata */
	psPageArrayData->iNumOSPagesAllocated = 0;
	return PVRSRV_OK;
}

/* Free pages from a page array.
 * Takes care of mem stats and chooses correct free path depending on parameters. */
static PVRSRV_ERROR
_FreeOSPages(PMR_OSPAGEARRAY_DATA *psPageArrayData,
			 IMG_UINT32 *pai32FreeIndices,
			 IMG_UINT32 ui32FreePageCount)
{
	PVRSRV_ERROR eError;

	/* Go the sparse or non-sparse path */
	if (psPageArrayData->iNumOSPagesAllocated != psPageArrayData->uiTotalNumOSPages
		|| pai32FreeIndices != NULL)
	{
		eError = _FreeOSPages_Sparse(psPageArrayData,
									 pai32FreeIndices,
									 ui32FreePageCount);
	}
	else
	{
		eError = _FreeOSPages_Fast(psPageArrayData);
	}

	if (eError != PVRSRV_OK)
	{
		PVR_DPF((PVR_DBG_ERROR, "_FreeOSPages_FreePages failed"));
	}

	_DumpPageArray(psPageArrayData->pagearray,
	               psPageArrayData->uiTotalNumOSPages >>
	              (psPageArrayData->uiLog2AllocPageSize - PAGE_SHIFT) );

	return eError;
}

/*
 *
 * Implementation of callback functions
 *
 */

/* Destruction function is called after last reference disappears,
 * but before PMR itself is freed.
 */
static void
PMRFinalizeOSMem(PMR_IMPL_PRIVDATA pvPriv)
{
	PVRSRV_ERROR eError;
	PMR_OSPAGEARRAY_DATA *psOSPageArrayData = pvPriv;

	/* We can't free pages until now. */
	if (psOSPageArrayData->iNumOSPagesAllocated != 0)
	{
#if defined(DEBUG) && defined(SUPPORT_VALIDATION)
		PVRSRV_DATA *psPVRSRVData = PVRSRVGetPVRSRVData();
		IMG_UINT32 ui32UMALeakMax = psPVRSRVData->sMemLeakIntervals.ui32GPU;

		mutex_lock(&g_sUMALeakMutex);

		g_ui32UMALeakCounter++;
		if (ui32UMALeakMax && g_ui32UMALeakCounter >= ui32UMALeakMax)
		{
			g_ui32UMALeakCounter = 0;
			mutex_unlock(&g_sUMALeakMutex);

			PVR_DPF((PVR_DBG_WARNING, "%s: Skipped freeing of PMR 0x%p to trigger memory leak.", __func__, pvPriv));
			return;
		}

		mutex_unlock(&g_sUMALeakMutex);
#endif

		eError = _FreeOSPages(psOSPageArrayData, NULL, 0);
		PVR_LOG_IF_ERROR(eError, "_FreeOSPages");
		PVR_ASSERT(eError == PVRSRV_OK); /* can we do better? */
	}

	_FreeOSPagesArray(psOSPageArrayData);
}

/* Callback function for locking the system physical page addresses.
 * This function must be called before the lookup address func. */
static PVRSRV_ERROR
PMRLockSysPhysAddressesOSMem(PMR_IMPL_PRIVDATA pvPriv)
{
	PVRSRV_ERROR eError;
	PMR_OSPAGEARRAY_DATA *psOSPageArrayData = pvPriv;

	if (BIT_ISSET(psOSPageArrayData->ui32AllocFlags, FLAG_ONDEMAND))
	{
		/* Allocate Memory for deferred allocation */
		eError = _AllocOSPages(psOSPageArrayData, NULL, psOSPageArrayData->uiTotalNumOSPages);
		if (eError != PVRSRV_OK)
		{
			return eError;
		}
	}

	eError = PVRSRV_OK;
	return eError;
}

static PVRSRV_ERROR
PMRUnlockSysPhysAddressesOSMem(PMR_IMPL_PRIVDATA pvPriv)
{
	/* Just drops the refcount. */
	PVRSRV_ERROR eError = PVRSRV_OK;
	PMR_OSPAGEARRAY_DATA *psOSPageArrayData = pvPriv;

	if (BIT_ISSET(psOSPageArrayData->ui32AllocFlags, FLAG_ONDEMAND))
	{
		/* Free Memory for deferred allocation */
		eError = _FreeOSPages(psOSPageArrayData,
							  NULL,
							  0);
		if (eError != PVRSRV_OK)
		{
			return eError;
		}
	}

	PVR_ASSERT(eError == PVRSRV_OK);
	return eError;
}

static INLINE IMG_BOOL IsOffsetValid(const PMR_OSPAGEARRAY_DATA *psOSPageArrayData,
                                     IMG_UINT32 ui32Offset)
{
	return (ui32Offset >> psOSPageArrayData->uiLog2AllocPageSize) <
	    psOSPageArrayData->uiTotalNumOSPages;
}

/* Determine PA for specified offset into page array. */
static IMG_DEV_PHYADDR GetOffsetPA(const PMR_OSPAGEARRAY_DATA *psOSPageArrayData,
                                   IMG_UINT32 ui32Offset)
{
	IMG_UINT32 ui32Log2AllocPageSize = psOSPageArrayData->uiLog2AllocPageSize;
	IMG_UINT32 ui32PageIndex = ui32Offset >> ui32Log2AllocPageSize;
	IMG_UINT32 ui32InPageOffset = ui32Offset - (ui32PageIndex << ui32Log2AllocPageSize);
	IMG_DEV_PHYADDR sPA;

	PVR_ASSERT(ui32InPageOffset < (1U << ui32Log2AllocPageSize));

	sPA.uiAddr = page_to_phys(psOSPageArrayData->pagearray[ui32PageIndex]);
	sPA.uiAddr += ui32InPageOffset;

	return sPA;
}

/* N.B. It is assumed that PMRLockSysPhysAddressesOSMem() is called _before_ this function! */
static PVRSRV_ERROR
PMRSysPhysAddrOSMem(PMR_IMPL_PRIVDATA pvPriv,
					IMG_UINT32 ui32Log2PageSize,
					IMG_UINT32 ui32NumOfPages,
					IMG_DEVMEM_OFFSET_T *puiOffset,
					IMG_BOOL *pbValid,
					IMG_DEV_PHYADDR *psDevPAddr)
{
	const PMR_OSPAGEARRAY_DATA *psOSPageArrayData = pvPriv;
	IMG_UINT32 uiIdx;

	if (psOSPageArrayData->uiLog2AllocPageSize < ui32Log2PageSize)
	{
		PVR_DPF((PVR_DBG_ERROR,
		         "%s: Requested physical addresses from PMR "
		         "for incompatible contiguity %u!",
		         __func__,
		         ui32Log2PageSize));
		return PVRSRV_ERROR_PMR_INCOMPATIBLE_CONTIGUITY;
	}

	for (uiIdx=0; uiIdx < ui32NumOfPages; uiIdx++)
	{
		if (pbValid[uiIdx])
		{
			PVR_LOG_RETURN_IF_FALSE(IsOffsetValid(psOSPageArrayData, puiOffset[uiIdx]),
			                        "puiOffset out of range", PVRSRV_ERROR_OUT_OF_RANGE);

			psDevPAddr[uiIdx] = GetOffsetPA(psOSPageArrayData, puiOffset[uiIdx]);

#if !defined(PVR_LINUX_PHYSMEM_USE_HIGHMEM_ONLY)
			/* this is just a precaution, normally this should be always
			 * available */
			if (psOSPageArrayData->ui64DmaMask)
			{
				if (psDevPAddr[uiIdx].uiAddr > psOSPageArrayData->ui64DmaMask)
				{
					PVR_DPF((PVR_DBG_ERROR, "%s: physical address"
							" (%" IMG_UINT64_FMTSPECX ") out of allowable range"
							" [0; %" IMG_UINT64_FMTSPECX "]", __func__,
							psDevPAddr[uiIdx].uiAddr,
							psOSPageArrayData->ui64DmaMask));
					BUG();
				}
			}
#endif
		}
	}

	return PVRSRV_OK;
}

typedef struct _PMR_OSPAGEARRAY_KERNMAP_DATA_ {
	void *pvBase;
	IMG_UINT32 ui32PageCount;
	pgprot_t PageProps;
#if defined(PVRSRV_PHYSMEM_CPUMAP_HISTORY)
	IMG_UINT32 ui32CpuCacheFlags;
#endif
} PMR_OSPAGEARRAY_KERNMAP_DATA;

static PVRSRV_ERROR
PMRAcquireKernelMappingDataOSMem(PMR_IMPL_PRIVDATA pvPriv,
								 size_t uiOffset,
								 size_t uiSize,
								 void **ppvKernelAddressOut,
								 IMG_HANDLE *phHandleOut,
								 PMR_FLAGS_T ulFlags)
{
	PVRSRV_ERROR eError;
	PMR_OSPAGEARRAY_DATA *psOSPageArrayData = pvPriv;
	void *pvAddress;
	pgprot_t prot = PAGE_KERNEL;
	IMG_UINT32 ui32PageOffset=0;
	size_t uiMapOffset=0;
	IMG_UINT32 ui32PageCount = 0;
	IMG_UINT32 uiLog2AllocPageSize = psOSPageArrayData->uiLog2AllocPageSize;
	IMG_UINT32 uiOSPageShift = OSGetPageShift();
	IMG_UINT32 uiPageSizeDiff = 0;
	struct page **pagearray;
	PMR_OSPAGEARRAY_KERNMAP_DATA *psData;

	int riscv_cache = 0;

	/* For cases device page size greater than the OS page size,
	 * multiple physically contiguous OS pages constitute one device page.
	 * However only the first page address of such an ensemble is stored
	 * as part of the mapping table in the driver. Hence when mapping the PMR
	 * in part/full, all OS pages that constitute the device page
	 * must also be mapped to kernel.
	 *
	 * For the case where device page size less than OS page size,
	 * treat it the same way as the page sizes are equal */
	if (uiLog2AllocPageSize > uiOSPageShift)
	{
		uiPageSizeDiff = uiLog2AllocPageSize - uiOSPageShift;
	}

	/*
		Zero offset and size as a special meaning which means map in the
		whole of the PMR, this is due to fact that the places that call
		this callback might not have access to be able to determine the
		physical size
	*/
	if ((uiOffset == 0) && (uiSize == 0))
	{
		ui32PageOffset = 0;
		uiMapOffset = 0;
		/* Page count = amount of OS pages */
		ui32PageCount = psOSPageArrayData->iNumOSPagesAllocated;
	}
	else
	{
		size_t uiEndoffset;

		ui32PageOffset = uiOffset >> uiLog2AllocPageSize;
		uiMapOffset = uiOffset - (ui32PageOffset << uiLog2AllocPageSize);
		uiEndoffset = uiOffset + uiSize - 1;
		/* Add one as we want the count, not the offset */
		/* Page count = amount of device pages (note uiLog2AllocPageSize being used) */
		ui32PageCount = (uiEndoffset >> uiLog2AllocPageSize) + 1;
		ui32PageCount -= ui32PageOffset;

		/* The OS page count to be mapped might be different if the
		 * OS page size is lesser than the device page size */
		ui32PageCount <<= uiPageSizeDiff;
	}

	switch (PVRSRV_CPU_CACHE_MODE(psOSPageArrayData->ui32CPUCacheFlags))
	{
		case PVRSRV_MEMALLOCFLAG_CPU_UNCACHED:
				prot = pgprot_noncached(prot);
				break;

		case PVRSRV_MEMALLOCFLAG_CPU_UNCACHED_WC:
				prot = pgprot_writecombine(prot);
				break;

		case PVRSRV_MEMALLOCFLAG_CPU_CACHED:
				riscv_cache = 1;
				break;

		default:
				eError = PVRSRV_ERROR_INVALID_PARAMS;
				goto e0;
	}

	if (uiPageSizeDiff)
	{
		/* Each device page can be broken down into ui32SubPageCount OS pages */
		IMG_UINT32 ui32SubPageCount = 1 << uiPageSizeDiff;
		IMG_UINT32 i;
		struct page **psPage = &psOSPageArrayData->pagearray[ui32PageOffset];

		/* Allocate enough memory for the OS page pointers for this mapping */
		pagearray = OSAllocMem(ui32PageCount * sizeof(pagearray[0]));

		if (pagearray == NULL)
		{
			eError = PVRSRV_ERROR_OUT_OF_MEMORY;
			goto e0;
		}

		/* construct array that holds the page pointers that constitute the requested
		 * mapping */
		for (i = 0; i < ui32PageCount; i++)
		{
			IMG_UINT32 ui32OSPageArrayIndex  = i / ui32SubPageCount;
			IMG_UINT32 ui32OSPageArrayOffset = i % ui32SubPageCount;

			/*
			 * The driver only stores OS page pointers for the first OS page
			 * within each device page (psPage[ui32OSPageArrayIndex]).
			 * Get the next OS page structure at device page granularity,
			 * then calculate OS page pointers for all the other pages.
			 */
			pagearray[i] = psPage[ui32OSPageArrayIndex] + ui32OSPageArrayOffset;
		}
	}
	else
	{
		pagearray = &psOSPageArrayData->pagearray[ui32PageOffset];
	}

	psData = OSAllocMem(sizeof(*psData));
	if (psData == NULL)
	{
		eError = PVRSRV_ERROR_OUT_OF_MEMORY;
		goto e1;
	}

	if (riscv_cache) {
		pvAddress = pvr_vmap_cached(pagearray, ui32PageCount, VM_READ | VM_WRITE, prot);
	} else {
		pvAddress = pvr_vmap(pagearray, ui32PageCount, VM_READ | VM_WRITE, prot);
	}
	if (pvAddress == NULL)
	{
		eError = PVRSRV_ERROR_OUT_OF_MEMORY;
		goto e2;
	}

	*ppvKernelAddressOut = pvAddress + uiMapOffset;
	psData->pvBase = pvAddress;
	psData->ui32PageCount = ui32PageCount;
	psData->PageProps = prot;
	*phHandleOut = psData;

	if (uiPageSizeDiff)
	{
		OSFreeMem(pagearray);
	}

#if defined(PVRSRV_PHYSMEM_CPUMAP_HISTORY)
	{
		IMG_CPU_PHYADDR pvAddrPhy;
		pvAddrPhy.uiAddr = IMG_CAST_TO_CPUPHYADDR_UINT(page_to_phys(*pagearray));
		InsertMappingRecord(PMR_GetAnnotation(psOSPageArrayData->hPMR),
							psOSPageArrayData->uiPid,
							pvAddress,
							pvAddrPhy,
							psOSPageArrayData->ui32CPUCacheFlags,
							uiMapOffset,
							ui32PageCount);

		psData->ui32CpuCacheFlags = psOSPageArrayData->ui32CPUCacheFlags;
	}
#endif

	return PVRSRV_OK;
	/*
	  error exit paths follow
	*/
e2:
	OSFreeMem(psData);
e1:
	if (uiPageSizeDiff)
	{
		OSFreeMem(pagearray);
	}
e0:
	PVR_ASSERT(eError != PVRSRV_OK);
	return eError;
}

static void PMRReleaseKernelMappingDataOSMem(PMR_IMPL_PRIVDATA pvPriv,
											 IMG_HANDLE hHandle)
{
	PMR_OSPAGEARRAY_KERNMAP_DATA *psData = hHandle;
	PVR_UNREFERENCED_PARAMETER(pvPriv);

#if defined(PVRSRV_PHYSMEM_CPUMAP_HISTORY)
	{
		IMG_CPU_PHYADDR pvAddrPhy;
		pvAddrPhy.uiAddr = IMG_CAST_TO_CPUPHYADDR_UINT(page_to_phys(vmalloc_to_page(psData->pvBase)));
		InsertUnMappingRecord(psData->pvBase,
				pvAddrPhy,
				psData->ui32CpuCacheFlags,
				psData->ui32PageCount);
	}
#endif

	pvr_vunmap(psData->pvBase, psData->ui32PageCount, psData->PageProps);
	OSFreeMem(psData);
}

/*************************************************************************/ /*!
@Function       PMRChangeSparseMemOSMem
@Description    This function Changes the sparse mapping by allocating and
                freeing of pages. It changes the GPU and CPU maps accordingly.
@Return         PVRSRV_ERROR failure code
*/ /**************************************************************************/
static PVRSRV_ERROR
PMRChangeSparseMemOSMem(PMR_IMPL_PRIVDATA pPriv,
						const PMR *psPMR,
						IMG_UINT32 ui32AllocPageCount,
						IMG_UINT32 *pai32AllocIndices,
						IMG_UINT32 ui32FreePageCount,
						IMG_UINT32 *pai32FreeIndices,
						IMG_UINT32 uiFlags)
{
	PVRSRV_ERROR eError;

	PMR_MAPPING_TABLE *psPMRMapTable = PMR_GetMappingTable(psPMR);
	PMR_OSPAGEARRAY_DATA *psPMRPageArrayData = (PMR_OSPAGEARRAY_DATA *)pPriv;
	struct page **psPageArray = psPMRPageArrayData->pagearray;
	void **psDMAVirtArray = psPMRPageArrayData->dmavirtarray;
	dma_addr_t *psDMAPhysArray = psPMRPageArrayData->dmaphysarray;

	struct page *psPage;
	dma_addr_t psDMAPAddr;
	void *pvDMAVAddr;

	IMG_UINT32 ui32AdtnlAllocPages = 0; /*<! Number of pages to alloc from the OS */
	IMG_UINT32 ui32AdtnlFreePages = 0; /*<! Number of pages to free back to the OS */
	IMG_UINT32 ui32CommonRequestCount = 0; /*<! Number of pages to move position in the page array */
	IMG_UINT32 ui32Loop = 0;
	IMG_UINT32 ui32Index = 0;
	IMG_UINT32 uiAllocpgidx;
	IMG_UINT32 uiFreepgidx;
	IMG_UINT32 uiOrder = psPMRPageArrayData->uiLog2AllocPageSize - PAGE_SHIFT;
	IMG_BOOL bCMA = BIT_ISSET(psPMRPageArrayData->ui32AllocFlags, FLAG_IS_CMA);


	/* Check SPARSE flags and calculate pages to allocate and free */
	if (SPARSE_RESIZE_BOTH == (uiFlags & SPARSE_RESIZE_BOTH))
	{
		ui32CommonRequestCount = (ui32AllocPageCount > ui32FreePageCount) ?
				ui32FreePageCount : ui32AllocPageCount;

		PDUMP_PANIC(PMR_DeviceNode(psPMR), SPARSEMEM_SWAP, "Request to swap alloc & free pages not supported");
	}

	if (SPARSE_RESIZE_ALLOC == (uiFlags & SPARSE_RESIZE_ALLOC))
	{
		ui32AdtnlAllocPages = ui32AllocPageCount - ui32CommonRequestCount;
	}
	else
	{
		ui32AllocPageCount = 0;
	}

	if (SPARSE_RESIZE_FREE == (uiFlags & SPARSE_RESIZE_FREE))
	{
		ui32AdtnlFreePages = ui32FreePageCount - ui32CommonRequestCount;
	}
	else
	{
		ui32FreePageCount = 0;
	}

	if (0 == (ui32CommonRequestCount || ui32AdtnlAllocPages || ui32AdtnlFreePages))
	{
		eError = PVRSRV_ERROR_INVALID_PARAMS;
		PVR_DPF((PVR_DBG_ERROR,
		         "%s: Missing parameters for number of pages to alloc/free",
		         __func__));
		return eError;
	}

	/* The incoming request is classified into two operations independent of
	 * each other: alloc & free pages.
	 * These operations can be combined with two mapping operations as well
	 * which are GPU & CPU space mappings.
	 *
	 * From the alloc and free page requests, the net amount of pages to be
	 * allocated or freed is computed. Pages that were requested to be freed
	 * will be reused to fulfil alloc requests.
	 *
	 * The order of operations is:
	 * 1. Allocate new pages from the OS
	 * 2. Move the free pages from free request to alloc positions.
	 * 3. Free the rest of the pages not used for alloc
	 *
	 * Alloc parameters are validated at the time of allocation
	 * and any error will be handled then. */

	/* Validate the free indices */
	if (ui32FreePageCount)
	{
		if (NULL != pai32FreeIndices){

			for (ui32Loop = 0; ui32Loop < ui32FreePageCount; ui32Loop++)
			{
				uiFreepgidx = pai32FreeIndices[ui32Loop];

				if (uiFreepgidx > (psPMRPageArrayData->uiTotalNumOSPages >> uiOrder))
				{
					eError = PVRSRV_ERROR_DEVICEMEM_OUT_OF_RANGE;
					goto e0;
				}

				if (NULL == psPageArray[uiFreepgidx])
				{
					eError = PVRSRV_ERROR_INVALID_PARAMS;
					PVR_DPF((PVR_DBG_ERROR,
					         "%s: Trying to free non-allocated page",
					         __func__));
					goto e0;
				}
			}
		}
		else
		{
			eError = PVRSRV_ERROR_INVALID_PARAMS;
			PVR_DPF((PVR_DBG_ERROR,
			         "%s: Given non-zero free count but missing indices array",
			         __func__));
			return eError;
		}
	}

	/* Validate the alloc indices */
	for (ui32Loop = ui32AdtnlAllocPages; ui32Loop < ui32AllocPageCount; ui32Loop++)
	{
		uiAllocpgidx = pai32AllocIndices[ui32Loop];

		if (uiAllocpgidx > (psPMRPageArrayData->uiTotalNumOSPages >> uiOrder))
		{
			eError = PVRSRV_ERROR_DEVICEMEM_OUT_OF_RANGE;
			goto e0;
		}

		if (SPARSE_REMAP_MEM != (uiFlags & SPARSE_REMAP_MEM))
		{
			if ((NULL != psPageArray[uiAllocpgidx]) ||
			    (TRANSLATION_INVALID != psPMRMapTable->aui32Translation[uiAllocpgidx]))
			{
				eError = PVRSRV_ERROR_INVALID_PARAMS;
				PVR_DPF((PVR_DBG_ERROR,
				         "%s: Trying to allocate already allocated page again",
				         __func__));
				goto e0;
			}
		}
		else
		{
			if ((NULL == psPageArray[uiAllocpgidx]) ||
			    (TRANSLATION_INVALID == psPMRMapTable->aui32Translation[uiAllocpgidx]) )
			{
				eError = PVRSRV_ERROR_INVALID_PARAMS;
				PVR_DPF((PVR_DBG_ERROR,
				         "%s: Unable to remap memory due to missing page",
				         __func__));
				goto e0;
			}
		}
	}

	ui32Loop = 0;

	/* Allocate new pages from the OS */
	if (0 != ui32AdtnlAllocPages)
	{
			eError = _AllocOSPages(psPMRPageArrayData, pai32AllocIndices, ui32AdtnlAllocPages);
			if (PVRSRV_OK != eError)
			{
				PVR_DPF((PVR_DBG_MESSAGE,
				         "%s: New Addtl Allocation of pages failed",
				         __func__));
				goto e0;
			}

			psPMRMapTable->ui32NumPhysChunks += ui32AdtnlAllocPages;
			/*Mark the corresponding pages of translation table as valid */
			for (ui32Loop = 0; ui32Loop < ui32AdtnlAllocPages; ui32Loop++)
			{
				psPMRMapTable->aui32Translation[pai32AllocIndices[ui32Loop]] = pai32AllocIndices[ui32Loop];
			}
	}


	ui32Index = ui32Loop;

	/* Move the corresponding free pages to alloc request */
	for (ui32Loop = 0; ui32Loop < ui32CommonRequestCount; ui32Loop++, ui32Index++)
	{
		uiAllocpgidx = pai32AllocIndices[ui32Index];
		uiFreepgidx  = pai32FreeIndices[ui32Loop];

		psPage = psPageArray[uiAllocpgidx];
		psPageArray[uiAllocpgidx] = psPageArray[uiFreepgidx];

		if (bCMA)
		{
			pvDMAVAddr = psDMAVirtArray[uiAllocpgidx];
			psDMAPAddr = psDMAPhysArray[uiAllocpgidx];
			psDMAVirtArray[uiAllocpgidx] = psDMAVirtArray[uiFreepgidx];
			psDMAPhysArray[uiAllocpgidx] = psDMAPhysArray[uiFreepgidx];
		}

		/* Is remap mem used in real world scenario? Should it be turned to a
		 *  debug feature? The condition check needs to be out of loop, will be
		 *  done at later point though after some analysis */
		if (SPARSE_REMAP_MEM != (uiFlags & SPARSE_REMAP_MEM))
		{
			psPMRMapTable->aui32Translation[uiFreepgidx] = TRANSLATION_INVALID;
			psPMRMapTable->aui32Translation[uiAllocpgidx] = uiAllocpgidx;
			psPageArray[uiFreepgidx] = NULL;
			if (bCMA)
			{
				psDMAVirtArray[uiFreepgidx] = NULL;
				psDMAPhysArray[uiFreepgidx] = (dma_addr_t)0;
			}
		}
		else
		{
			psPMRMapTable->aui32Translation[uiFreepgidx] = uiFreepgidx;
			psPMRMapTable->aui32Translation[uiAllocpgidx] = uiAllocpgidx;
			psPageArray[uiFreepgidx] = psPage;
			if (bCMA)
			{
				psDMAVirtArray[uiFreepgidx] = pvDMAVAddr;
				psDMAPhysArray[uiFreepgidx] = psDMAPAddr;
			}
		}
	}

	/* Free the additional free pages */
	if (0 != ui32AdtnlFreePages)
	{
		eError = _FreeOSPages(psPMRPageArrayData,
		                      &pai32FreeIndices[ui32Loop],
		                      ui32AdtnlFreePages);
		if (eError != PVRSRV_OK)
		{
			goto e0;
		}
		psPMRMapTable->ui32NumPhysChunks -= ui32AdtnlFreePages;
		while (ui32Loop < ui32FreePageCount)
		{
			psPMRMapTable->aui32Translation[pai32FreeIndices[ui32Loop]] = TRANSLATION_INVALID;
			ui32Loop++;
		}
	}

	eError = PVRSRV_OK;

e0:
	return eError;
}

/*************************************************************************/ /*!
@Function       PMRChangeSparseMemCPUMapOSMem
@Description    This function Changes CPU maps accordingly
@Return         PVRSRV_ERROR failure code
*/ /**************************************************************************/
static
PVRSRV_ERROR PMRChangeSparseMemCPUMapOSMem(PMR_IMPL_PRIVDATA pPriv,
                                           const PMR *psPMR,
                                           IMG_UINT64 sCpuVAddrBase,
                                           IMG_UINT32 ui32AllocPageCount,
                                           IMG_UINT32 *pai32AllocIndices,
                                           IMG_UINT32 ui32FreePageCount,
                                           IMG_UINT32 *pai32FreeIndices)
{
	struct page **psPageArray;
	PMR_OSPAGEARRAY_DATA *psPMRPageArrayData = (PMR_OSPAGEARRAY_DATA *)pPriv;
	IMG_CPU_PHYADDR sCPUPAddr;

	sCPUPAddr.uiAddr = 0;
	psPageArray = psPMRPageArrayData->pagearray;

	return OSChangeSparseMemCPUAddrMap((void **)psPageArray,
	                                   sCpuVAddrBase,
	                                   sCPUPAddr,
	                                   ui32AllocPageCount,
	                                   pai32AllocIndices,
	                                   ui32FreePageCount,
	                                   pai32FreeIndices,
	                                   IMG_FALSE);
}

static PMR_IMPL_FUNCTAB _sPMROSPFuncTab = {
	.pfnLockPhysAddresses = &PMRLockSysPhysAddressesOSMem,
	.pfnUnlockPhysAddresses = &PMRUnlockSysPhysAddressesOSMem,
	.pfnDevPhysAddr = &PMRSysPhysAddrOSMem,
	.pfnAcquireKernelMappingData = &PMRAcquireKernelMappingDataOSMem,
	.pfnReleaseKernelMappingData = &PMRReleaseKernelMappingDataOSMem,
	.pfnReadBytes = NULL,
	.pfnWriteBytes = NULL,
	.pfnChangeSparseMem = &PMRChangeSparseMemOSMem,
	.pfnChangeSparseMemCPUMap = &PMRChangeSparseMemCPUMapOSMem,
	.pfnFinalize = &PMRFinalizeOSMem,
};

/* Wrapper around OS page allocation. */
static PVRSRV_ERROR
DoPageAlloc(PMR_OSPAGEARRAY_DATA *psPrivData,
            IMG_UINT32 *puiAllocIndices,
            IMG_UINT32 ui32NumPhysChunks,
            IMG_UINT32 ui32NumVirtChunks,
            IMG_UINT32 ui32Log2AllocPageSize)
{
	PVRSRV_ERROR eError = PVRSRV_OK;

	/* Do we fill the whole page array or just parts (sparse)? */
	if (ui32NumPhysChunks == ui32NumVirtChunks)
	{
		/* Allocate the physical pages */
		eError = _AllocOSPages(psPrivData,
		                       NULL,
		                       psPrivData->uiTotalNumOSPages >>
		                       (ui32Log2AllocPageSize - PAGE_SHIFT));
	}
	else if (ui32NumPhysChunks != 0)
	{
		/* Allocate the physical pages */
		eError = _AllocOSPages(psPrivData, puiAllocIndices,
		                       ui32NumPhysChunks);
	}

	return eError;
}

static void _EncodeAllocationFlags(IMG_UINT32 uiLog2AllocPageSize,
	                               PVRSRV_MEMALLOCFLAGS_T uiFlags,
	                               IMG_UINT32* ui32AllocFlags)
{

	/*
	 * Use CMA framework if order is greater than OS page size; please note
	 * that OSMMapPMRGeneric() has the same expectation as well.
	 */
	/* IsCMA? */
	if (uiLog2AllocPageSize > PAGE_SHIFT)
	{
		BIT_SET(*ui32AllocFlags, FLAG_IS_CMA);
	}

	/* OnDemand? */
	if (PVRSRV_CHECK_ON_DEMAND(uiFlags))
	{
		BIT_SET(*ui32AllocFlags, FLAG_ONDEMAND);
	}

	/* Zero? */
	if (PVRSRV_CHECK_ZERO_ON_ALLOC(uiFlags))
	{
		BIT_SET(*ui32AllocFlags, FLAG_ZERO);
	}

	/* Poison on alloc? */
	if (PVRSRV_CHECK_POISON_ON_ALLOC(uiFlags))
	{
		BIT_SET(*ui32AllocFlags, FLAG_POISON_ON_ALLOC);
	}

#if defined(DEBUG)
	/* Poison on free? */
	if (PVRSRV_CHECK_POISON_ON_FREE(uiFlags))
	{
		BIT_SET(*ui32AllocFlags, FLAG_POISON_ON_FREE);
	}
#endif

	/* Indicate whether this is an allocation with default caching attribute (i.e cached) or not */
	if (PVRSRV_CHECK_CPU_UNCACHED(uiFlags) ||
		PVRSRV_CHECK_CPU_WRITE_COMBINE(uiFlags))
	{
		BIT_SET(*ui32AllocFlags, FLAG_UNSET_MEMORY_TYPE);
	}

}

void PhysmemGetOSRamMemStats(PHEAP_IMPL_DATA pvImplData,
                                   	   IMG_UINT64 *pui64TotalSize,
                                   	   IMG_UINT64 *pui64FreeSize)
{
	struct sysinfo sMeminfo;
	si_meminfo(&sMeminfo);

	PVR_UNREFERENCED_PARAMETER(pvImplData);

	*pui64TotalSize = sMeminfo.totalram * sMeminfo.mem_unit;
	*pui64FreeSize = sMeminfo.freeram * sMeminfo.mem_unit;

}

PVRSRV_ERROR
PhysmemNewOSRamBackedPMR(PHYS_HEAP *psPhysHeap,
						 CONNECTION_DATA *psConnection,
						 IMG_DEVMEM_SIZE_T uiSize,
						 IMG_UINT32 ui32NumPhysChunks,
						 IMG_UINT32 ui32NumVirtChunks,
						 IMG_UINT32 *puiAllocIndices,
						 IMG_UINT32 uiLog2AllocPageSize,
						 PVRSRV_MEMALLOCFLAGS_T uiFlags,
						 const IMG_CHAR *pszAnnotation,
						 IMG_PID uiPid,
						 PMR **ppsPMRPtr,
						 IMG_UINT32 ui32PDumpFlags)
{
	PVRSRV_ERROR eError;
	PVRSRV_ERROR eError2;
	PMR *psPMR;
	struct _PMR_OSPAGEARRAY_DATA_ *psPrivData;
	PMR_FLAGS_T uiPMRFlags;
	IMG_UINT32 ui32CPUCacheFlags;
	IMG_UINT32 ui32AllocFlags = 0;
	PVRSRV_DEVICE_NODE *psDevNode = PhysHeapDeviceNode(psPhysHeap);

	PVR_UNREFERENCED_PARAMETER(psConnection);

	/*
	 * The host driver (but not guest) can still use this factory for firmware
	 * allocations
	 */
	if (PVRSRV_VZ_MODE_IS(GUEST) && PVRSRV_CHECK_FW_MAIN(uiFlags))
	{
		PVR_ASSERT(0);
		eError = PVRSRV_ERROR_INVALID_PARAMS;
		goto errorOnParam;
	}

	/* Select correct caching mode */
	eError = DevmemCPUCacheMode(psDevNode, uiFlags, &ui32CPUCacheFlags);
	if (eError != PVRSRV_OK)
	{
		goto errorOnParam;
	}

	if (PVRSRV_CHECK_CPU_CACHE_CLEAN(uiFlags))
	{
		ui32CPUCacheFlags |= PVRSRV_MEMALLOCFLAG_CPU_CACHE_CLEAN;
	}

	_EncodeAllocationFlags(uiLog2AllocPageSize, uiFlags, &ui32AllocFlags);


#if defined(PVR_LINUX_PHYSMEM_ZERO_ALL_PAGES)
	/* Overwrite flags and always zero pages that could go back to UM */
	BIT_SET(ui32AllocFlags, FLAG_ZERO);
	BIT_UNSET(ui32AllocFlags, FLAG_POISON_ON_ALLOC);
#endif

	/* Physical allocation alignment is generally not supported except under
	   very restrictive conditions, also there is a maximum alignment value
	   which must not exceed the largest device page-size. If these are not
	   met then fail the aligned-requested allocation */
	if (BIT_ISSET(ui32AllocFlags, FLAG_IS_CMA))
	{
		IMG_UINT32 uiAlign = 1 << uiLog2AllocPageSize;
		if (uiAlign > uiSize || uiAlign > (1 << PVR_MAX_PHYSMEM_CONTIG_ALLOC_LOG2PGSZ))
		{
			PVR_DPF((PVR_DBG_ERROR,
					"%s: Invalid PA alignment: size 0x%llx, align 0x%x",
					__func__, uiSize, uiAlign));
			eError = PVRSRV_ERROR_INVALID_ALIGNMENT;
			goto errorOnParam;
		}
		PVR_ASSERT(uiLog2AllocPageSize > PVR_MIN_PHYSMEM_CONTIG_ALLOC_LOG2PGSZ);
	}

	/* Create Array structure that hold the physical pages */
	eError = _AllocOSPageArray(psDevNode,
							   uiSize,
							   ui32NumPhysChunks,
							   ui32NumVirtChunks,
							   uiLog2AllocPageSize,
							   ui32AllocFlags,
							   ui32CPUCacheFlags,
							   uiPid,
							   &psPrivData);
	if (eError != PVRSRV_OK)
	{
		goto errorOnAllocPageArray;
	}

	if (!BIT_ISSET(ui32AllocFlags, FLAG_ONDEMAND))
	{
		eError = DoPageAlloc(psPrivData, puiAllocIndices, ui32NumPhysChunks,
		                     ui32NumVirtChunks, uiLog2AllocPageSize);
		if (eError != PVRSRV_OK)
		{
			goto errorOnAllocPages;
		}
	}

	/*
	 * In this instance, we simply pass flags straight through.
	 *
	 * Generically, uiFlags can include things that control the PMR factory, but
	 * we don't need any such thing (at the time of writing!), and our caller
	 * specifies all PMR flags so we don't need to meddle with what was given to
	 * us.
	 */
	uiPMRFlags = (PMR_FLAGS_T)(uiFlags & PVRSRV_MEMALLOCFLAGS_PMRFLAGSMASK);

	/*
	 * Check no significant bits were lost in cast due to different bit widths
	 * for flags
	 */
	PVR_ASSERT(uiPMRFlags == (uiFlags & PVRSRV_MEMALLOCFLAGS_PMRFLAGSMASK));

	if (BIT_ISSET(ui32AllocFlags, FLAG_ONDEMAND))
	{
		PDUMPCOMMENT(PhysHeapDeviceNode(psPhysHeap), "Deferred Allocation PMR (UMA)");
	}

	eError = PMRCreatePMR(psPhysHeap,
						  uiSize,
						  ui32NumPhysChunks,
						  ui32NumVirtChunks,
						  puiAllocIndices,
						  uiLog2AllocPageSize,
						  uiPMRFlags,
						  pszAnnotation,
						  &_sPMROSPFuncTab,
						  psPrivData,
						  PMR_TYPE_OSMEM,
						  &psPMR,
						  ui32PDumpFlags);
	if (eError != PVRSRV_OK)
	{
		goto errorOnCreate;
	}

#if defined(PVRSRV_PHYSMEM_CPUMAP_HISTORY)
	psPrivData->hPMR = psPMR;
#endif

	*ppsPMRPtr = psPMR;

	return PVRSRV_OK;

errorOnCreate:
	if (!BIT_ISSET(ui32AllocFlags, FLAG_ONDEMAND))
	{
		eError2 = _FreeOSPages(psPrivData, NULL, 0);
		PVR_ASSERT(eError2 == PVRSRV_OK);
	}

errorOnAllocPages:
	_FreeOSPagesArray(psPrivData);

errorOnAllocPageArray:
errorOnParam:
	PVR_ASSERT(eError != PVRSRV_OK);
	return eError;
}