summaryrefslogtreecommitdiff
path: root/sys/arch/arm/arm/pmap7.c
blob: 64a9ddbb00299e0ae3412680da7a81706ac15a6b (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
/*	$OpenBSD: pmap7.c,v 1.26 2016/07/18 13:38:11 tom Exp $	*/
/*	$NetBSD: pmap.c,v 1.147 2004/01/18 13:03:50 scw Exp $	*/

/*
 * Copyright 2003 Wasabi Systems, Inc.
 * All rights reserved.
 *
 * Written by Steve C. Woodford for Wasabi Systems, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed for the NetBSD Project by
 *      Wasabi Systems, Inc.
 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Copyright (c) 2002-2003 Wasabi Systems, Inc.
 * Copyright (c) 2001 Richard Earnshaw
 * Copyright (c) 2001-2002 Christopher Gilbert
 * All rights reserved.
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the company nor the name of the author may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*-
 * Copyright (c) 1999 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Copyright (c) 1994-1998 Mark Brinicombe.
 * Copyright (c) 1994 Brini.
 * All rights reserved.
 *
 * This code is derived from software written for Brini by Mark Brinicombe
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Mark Brinicombe.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 *
 * RiscBSD kernel project
 *
 * pmap.c
 *
 * Machine dependant vm stuff
 *
 * Created      : 20/09/94
 */

/*
 * Performance improvements, UVM changes, overhauls and part-rewrites
 * were contributed by Neil A. Carson <neil@causality.com>.
 */

/*
 * Overhauled again to speedup the pmap, use MMU Domains so that L1 tables
 * can be shared, and re-work the KVM layout, by Steve Woodford of Wasabi
 * Systems, Inc.
 *
 * There are still a few things outstanding at this time:
 *
 *   - There are some unresolved issues for MP systems:
 *
 *     o The L1 metadata needs a lock, or more specifically, some places
 *       need to acquire an exclusive lock when modifying L1 translation
 *       table entries.
 *
 *     o When one cpu modifies an L1 entry, and that L1 table is also
 *       being used by another cpu, then the latter will need to be told
 *       that a tlb invalidation may be necessary. (But only if the old
 *       domain number in the L1 entry being over-written is currently
 *       the active domain on that cpu). I guess there are lots more tlb
 *       shootdown issues too...
 *
 *     o If the vector_page is at 0x00000000 instead of 0xffff0000, then
 *       MP systems will lose big-time because of the MMU domain hack.
 *       The only way this can be solved (apart from moving the vector
 *       page to 0xffff0000) is to reserve the first 1MB of user address
 *       space for kernel use only. This would require re-linking all
 *       applications so that the text section starts above this 1MB
 *       boundary.
 *
 *     o Tracking which VM space is resident in the cache/tlb has not yet
 *       been implemented for MP systems.
 *
 *     o Finally, there is a pathological condition where two cpus running
 *       two separate processes (not procs) which happen to share an L1
 *       can get into a fight over one or more L1 entries. This will result
 *       in a significant slow-down if both processes are in tight loops.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/malloc.h>
#include <sys/user.h>
#include <sys/pool.h>
#include <sys/cdefs.h>
#include <sys/sched.h>
 
#include <uvm/uvm.h>

#include <machine/bus.h>
#include <machine/pmap.h>
#include <machine/pcb.h>
#include <machine/param.h>
#include <arm/cpufunc.h>

//#define PMAP_DEBUG
#ifdef PMAP_DEBUG

/*
 * for switching to potentially finer grained debugging
 */
#define	PDB_FOLLOW	0x0001
#define	PDB_INIT	0x0002
#define	PDB_ENTER	0x0004
#define	PDB_REMOVE	0x0008
#define	PDB_CREATE	0x0010
#define	PDB_PTPAGE	0x0020
#define	PDB_GROWKERN	0x0040
#define	PDB_BITS	0x0080
#define	PDB_COLLECT	0x0100
#define	PDB_PROTECT	0x0200
#define	PDB_MAP_L1	0x0400
#define	PDB_BOOTSTRAP	0x1000
#define	PDB_PARANOIA	0x2000
#define	PDB_WIRING	0x4000
#define	PDB_PVDUMP	0x8000
#define	PDB_KENTER	0x20000
#define	PDB_KREMOVE	0x40000

#define pmapdebug (cold ? 0 : 0xffffffff)
#define	NPDEBUG(_lev_,_stat_) \
	if (pmapdebug & (_lev_)) \
        	((_stat_))
    
#else	/* PMAP_DEBUG */
#define NPDEBUG(_lev_,_stat_) /* Nothing */
#endif	/* PMAP_DEBUG */

/*
 * pmap_kernel() points here
 */
struct pmap     kernel_pmap_store;

/*
 * Pool and cache that pmap structures are allocated from.
 * We use a cache to avoid clearing the pm_l2[] array (1KB)
 * in pmap_create().
 */
struct pool pmap_pmap_pool;

/*
 * Pool of PV structures
 */
struct pool pmap_pv_pool;
void *pmap_bootstrap_pv_page_alloc(struct pool *, int, int *);
void pmap_bootstrap_pv_page_free(struct pool *, void *);
struct pool_allocator pmap_bootstrap_pv_allocator = {
	pmap_bootstrap_pv_page_alloc, pmap_bootstrap_pv_page_free
};

/*
 * Pool and cache of l2_dtable structures.
 * We use a cache to avoid clearing the structures when they're
 * allocated. (196 bytes)
 */
struct pool pmap_l2dtable_pool;
vaddr_t pmap_kernel_l2dtable_kva;

/*
 * Pool and cache of L2 page descriptors.
 * We use a cache to avoid clearing the descriptor table
 * when they're allocated. (1KB)
 */
struct pool pmap_l2ptp_pool;
vaddr_t pmap_kernel_l2ptp_kva;
paddr_t pmap_kernel_l2ptp_phys;

/*
 * pmap copy/zero page, wb page, and mem(5) hook point
 */
pt_entry_t *csrc_pte, *cdst_pte, *cwb_pte;
vaddr_t csrcp, cdstp, cwbp;
char *memhook;
extern caddr_t msgbufaddr;

/*
 * Flag to indicate if pmap_init() has done its thing
 */
boolean_t pmap_initialized;

/*
 * Metadata for L1 translation tables.
 */
struct l1_ttable {
	/* Entry on the L1 Table list */
	TAILQ_ENTRY(l1_ttable) l1_link;

	/* Physical address of this L1 page table */
	paddr_t l1_physaddr;

	/* KVA of this L1 page table */
	pd_entry_t *l1_kva;
};

/*
 * Convert a virtual address into its L1 table index. That is, the
 * index used to locate the L2 descriptor table pointer in an L1 table.
 * This is basically used to index l1->l1_kva[].
 *
 * Each L2 descriptor table represents 1MB of VA space.
 */
#define	L1_IDX(va)		(((vaddr_t)(va)) >> L1_S_SHIFT)

/*
 * A list of all L1 tables
 */
TAILQ_HEAD(, l1_ttable) l1_list;

/*
 * The l2_dtable tracks L2_BUCKET_SIZE worth of L1 slots.
 *
 * This is normally 16MB worth L2 page descriptors for any given pmap.
 * Reference counts are maintained for L2 descriptors so they can be
 * freed when empty.
 */
struct l2_dtable {
	/* The number of L2 page descriptors allocated to this l2_dtable */
	u_int l2_occupancy;

	/* List of L2 page descriptors */
	struct l2_bucket {
		pt_entry_t *l2b_kva;	/* KVA of L2 Descriptor Table */
		paddr_t l2b_phys;	/* Physical address of same */
		u_short l2b_l1idx;	/* This L2 table's L1 index */
		u_short l2b_occupancy;	/* How many active descriptors */
	} l2_bucket[L2_BUCKET_SIZE];
};

/*
 * Given an L1 table index, calculate the corresponding l2_dtable index
 * and bucket index within the l2_dtable.
 */
#define	L2_IDX(l1idx)		(((l1idx) >> L2_BUCKET_LOG2) & \
				 (L2_SIZE - 1))
#define	L2_BUCKET(l1idx)	((l1idx) & (L2_BUCKET_SIZE - 1))

/*
 * Given a virtual address, this macro returns the
 * virtual address required to drop into the next L2 bucket.
 */
#define	L2_NEXT_BUCKET(va)	(((va) & L1_S_FRAME) + L1_S_SIZE)

/*
 * L2 allocation.
 */
#define	pmap_alloc_l2_dtable()		\
	    pool_get(&pmap_l2dtable_pool, PR_NOWAIT|PR_ZERO)
#define	pmap_free_l2_dtable(l2)		\
	    pool_put(&pmap_l2dtable_pool, (l2))

/*
 * We try to map the page tables write-through, if possible.  However, not
 * all CPUs have a write-through cache mode, so on those we have to sync
 * the cache when we frob page tables.
 *
 * We try to evaluate this at compile time, if possible.  However, it's
 * not always possible to do that, hence this run-time var.
 */
int	pmap_needs_pte_sync;

/*
 * Real definition of pv_entry.
 */
struct pv_entry {
	struct pv_entry *pv_next;       /* next pv_entry */
	pmap_t		pv_pmap;        /* pmap where mapping lies */
	vaddr_t		pv_va;          /* virtual address for mapping */
	u_int		pv_flags;       /* flags */
};

/*
 * Macro to determine if a mapping might be resident in the
 * instruction cache and/or TLB
 */
#define	PV_BEEN_EXECD(f)  (((f) & (PVF_REF | PVF_EXEC)) == (PVF_REF | PVF_EXEC))

/*
 * Macro to determine if a mapping might be resident in the
 * data cache and/or TLB
 */
#define	PV_BEEN_REFD(f)   (((f) & PVF_REF) != 0)

/*
 * Local prototypes
 */
int		pmap_set_pt_cache_mode(pd_entry_t *, vaddr_t);
void		pmap_alloc_specials(vaddr_t *, int, vaddr_t *,
		    pt_entry_t **);
static boolean_t	pmap_is_current(pmap_t);
void		pmap_enter_pv(struct vm_page *, struct pv_entry *,
		    pmap_t, vaddr_t, u_int);
static struct pv_entry *pmap_find_pv(struct vm_page *, pmap_t, vaddr_t);
struct pv_entry *pmap_remove_pv(struct vm_page *, pmap_t, vaddr_t);
u_int		pmap_modify_pv(struct vm_page *, pmap_t, vaddr_t,
		    u_int, u_int);

void		pmap_alloc_l1(pmap_t, int);
void		pmap_free_l1(pmap_t);

struct l2_bucket *pmap_get_l2_bucket(pmap_t, vaddr_t);
struct l2_bucket *pmap_alloc_l2_bucket(pmap_t, vaddr_t);
void		pmap_free_l2_bucket(pmap_t, struct l2_bucket *, u_int);
void		pmap_l2ptp_ctor(void *);

void		pmap_clearbit(struct vm_page *, u_int);
void		pmap_clean_page(struct vm_page *, int);
void		pmap_page_remove(struct vm_page *);

void		pmap_init_l1(struct l1_ttable *, pd_entry_t *);
vaddr_t		kernel_pt_lookup(paddr_t);


/*
 * External function prototypes
 */
extern void bzero_page(vaddr_t);
extern void bcopy_page(vaddr_t, vaddr_t);

/*
 * Misc variables
 */
vaddr_t virtual_avail;
vaddr_t virtual_end;
vaddr_t pmap_curmaxkvaddr;

extern pv_addr_t systempage;

static __inline boolean_t
pmap_is_current(pmap_t pm)
{
	if (pm == pmap_kernel() ||
	    (curproc && curproc->p_vmspace->vm_map.pmap == pm))
		return (TRUE);

	return (FALSE);
}

/*
 * A bunch of routines to conditionally flush the caches/TLB depending
 * on whether the specified pmap actually needs to be flushed at any
 * given time.
 */
static __inline void
pmap_tlb_flushID_SE(pmap_t pm, vaddr_t va)
{
	if (pmap_is_current(pm))
		cpu_tlb_flushID_SE(va);
}

static __inline void
pmap_tlb_flushD_SE(pmap_t pm, vaddr_t va)
{
	if (pmap_is_current(pm))
		cpu_tlb_flushD_SE(va);
}

static __inline void
pmap_tlb_flushID(pmap_t pm)
{
	if (pmap_is_current(pm))
		cpu_tlb_flushID();
}

static __inline void
pmap_tlb_flushD(pmap_t pm)
{
	if (pmap_is_current(pm))
		cpu_tlb_flushD();
}

/*
 * Returns a pointer to the L2 bucket associated with the specified pmap
 * and VA, or NULL if no L2 bucket exists for the address.
 */
struct l2_bucket *
pmap_get_l2_bucket(pmap_t pm, vaddr_t va)
{
	struct l2_dtable *l2;
	struct l2_bucket *l2b;
	u_short l1idx;

	l1idx = L1_IDX(va);

	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL ||
	    (l2b = &l2->l2_bucket[L2_BUCKET(l1idx)])->l2b_kva == NULL)
		return (NULL);

	return (l2b);
}

/*
 * main pv_entry manipulation functions:
 *   pmap_enter_pv: enter a mapping onto a vm_page list
 *   pmap_remove_pv: remove a mapping from a vm_page list
 *
 * NOTE: pmap_enter_pv expects to lock the pvh itself
 *       pmap_remove_pv expects te caller to lock the pvh before calling
 */

/*
 * pmap_enter_pv: enter a mapping onto a vm_page lst
 *
 * => caller should have pmap locked
 * => we will gain the lock on the vm_page and allocate the new pv_entry
 * => caller should adjust ptp's wire_count before calling
 * => caller should not adjust pmap's wire_count
 */
void
pmap_enter_pv(struct vm_page *pg, struct pv_entry *pve, pmap_t pm,
    vaddr_t va, u_int flags)
{

	NPDEBUG(PDB_PVDUMP,
	    printf("pmap_enter_pv: pm %p, pg %p, flags 0x%x\n", pm, pg, flags));

	pve->pv_pmap = pm;
	pve->pv_va = va;
	pve->pv_flags = flags;

	pve->pv_next = pg->mdpage.pvh_list;	/* add to ... */
	pg->mdpage.pvh_list = pve;		/* ... locked list */
	pg->mdpage.pvh_attrs |= flags & (PVF_REF | PVF_MOD);

	if (pve->pv_flags & PVF_WIRED)
		++pm->pm_stats.wired_count;
}

/*
 *
 * pmap_find_pv: Find a pv entry
 *
 * => caller should hold lock on vm_page
 */
static __inline struct pv_entry *
pmap_find_pv(struct vm_page *pg, pmap_t pm, vaddr_t va)
{
	struct pv_entry *pv;

	for (pv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
		if (pm == pv->pv_pmap && va == pv->pv_va)
			break;
	}

	return (pv);
}

/*
 * pmap_remove_pv: try to remove a mapping from a pv_list
 *
 * => pmap should be locked
 * => caller should hold lock on vm_page [so that attrs can be adjusted]
 * => caller should adjust ptp's wire_count and free PTP if needed
 * => caller should NOT adjust pmap's wire_count
 * => we return the removed pve
 */
struct pv_entry *
pmap_remove_pv(struct vm_page *pg, pmap_t pm, vaddr_t va)
{
	struct pv_entry *pve, **prevptr;

	NPDEBUG(PDB_PVDUMP,
	    printf("pmap_remove_pv: pm %p, pg %p, va 0x%08lx\n", pm, pg, va));

	prevptr = &pg->mdpage.pvh_list;		/* previous pv_entry pointer */
	pve = *prevptr;

	while (pve) {
		if (pve->pv_pmap == pm && pve->pv_va == va) {	/* match? */
			NPDEBUG(PDB_PVDUMP,
			    printf("pmap_remove_pv: pm %p, pg %p, flags 0x%x\n", pm, pg, pve->pv_flags));
			*prevptr = pve->pv_next;		/* remove it! */
			if (pve->pv_flags & PVF_WIRED)
			    --pm->pm_stats.wired_count;
			break;
		}
		prevptr = &pve->pv_next;		/* previous pointer */
		pve = pve->pv_next;			/* advance */
	}

	return(pve);				/* return removed pve */
}

/*
 *
 * pmap_modify_pv: Update pv flags
 *
 * => caller should hold lock on vm_page [so that attrs can be adjusted]
 * => caller should NOT adjust pmap's wire_count
 * => we return the old flags
 * 
 * Modify a physical-virtual mapping in the pv table
 */
u_int
pmap_modify_pv(struct vm_page *pg, pmap_t pm, vaddr_t va,
    u_int clr_mask, u_int set_mask)
{
	struct pv_entry *npv;
	u_int flags, oflags;

	if ((npv = pmap_find_pv(pg, pm, va)) == NULL)
		return (0);

	NPDEBUG(PDB_PVDUMP,
	    printf("pmap_modify_pv: pm %p, pg %p, clr 0x%x, set 0x%x, flags 0x%x\n", pm, pg, clr_mask, set_mask, npv->pv_flags));

	/*
	 * There is at least one VA mapping this page.
	 */

	if (clr_mask & (PVF_REF | PVF_MOD))
		pg->mdpage.pvh_attrs |= set_mask & (PVF_REF | PVF_MOD);

	oflags = npv->pv_flags;
	npv->pv_flags = flags = (oflags & ~clr_mask) | set_mask;

	if ((flags ^ oflags) & PVF_WIRED) {
		if (flags & PVF_WIRED)
			++pm->pm_stats.wired_count;
		else
			--pm->pm_stats.wired_count;
	}

	return (oflags);
}

uint nl1;
/*
 * Allocate an L1 translation table for the specified pmap.
 * This is called at pmap creation time.
 */
void
pmap_alloc_l1(pmap_t pm, int domain)
{
	struct l2_bucket *l2b;
	struct l1_ttable *l1;
	struct pglist plist;
	struct vm_page *m;
	pd_entry_t *pl1pt;
	pt_entry_t *ptep, pte;
	vaddr_t va, eva;
	int error;

#ifdef PMAP_DEBUG
printf("%s: %d %d\n", __func__, domain, ++nl1);
#endif
	/* XXX use a pool? or move to inside struct pmap? */
	l1 = malloc(sizeof(*l1), M_VMPMAP, M_WAITOK);

	/* Allocate a L1 page table */
	for (;;) {
		va = uvm_km_valloc(kernel_map, L1_TABLE_SIZE);
		if (va != 0)
			break;
		uvm_wait("alloc_l1_va");
	}

	for (;;) {
		TAILQ_INIT(&plist);
		error = uvm_pglistalloc(L1_TABLE_SIZE, 0, (paddr_t)-1,
		    L1_TABLE_SIZE, 0, &plist, 1, UVM_PLA_WAITOK);
		if (error == 0)
			break;
		uvm_wait("alloc_l1_pg");
	}

	pl1pt = (pd_entry_t *)va;
	m = TAILQ_FIRST(&plist);
	for (eva = va + L1_TABLE_SIZE; va < eva; va += PAGE_SIZE) {
		paddr_t pa = VM_PAGE_TO_PHYS(m);

		pmap_kenter_pa(va, pa, PROT_READ | PROT_WRITE);
		/*
		 * Make sure the L1 descriptor table is mapped
		 * with the cache-mode set to write-through, or
		 * correctly synced.
		 */
		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
		ptep = &l2b->l2b_kva[l2pte_index(va)];
		pte = *ptep;

		if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
			pte = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
			*ptep = pte;
			PTE_SYNC(ptep);
			cpu_tlb_flushD_SE(va);
		}

		m = TAILQ_NEXT(m, pageq);
	}

	pmap_init_l1(l1, pl1pt);

	pm->pm_l1 = l1;
	pm->pm_domain = domain;
}

/*
 * Free an L1 translation table.
 * This is called at pmap destruction time.
 */
void
pmap_free_l1(pmap_t pm)
{
	struct l1_ttable *l1 = pm->pm_l1;
	struct pglist mlist;
	struct vm_page *pg;
	struct l2_bucket *l2b;
	pt_entry_t *ptep;
	vaddr_t va;
	uint npg;

{
	u_int cur_ttb;

	__asm volatile("mrc p15, 0, %0, c2, c0, 0" : "=r"(cur_ttb));
	cur_ttb &= ~(L1_TABLE_SIZE - 1);

}
	pm->pm_l1 = NULL;
	TAILQ_REMOVE(&l1_list, l1, l1_link);

	/* free backing pages */
	TAILQ_INIT(&mlist);
	va = (vaddr_t)l1->l1_kva;
	for (npg = atop(L1_TABLE_SIZE); npg != 0; npg--) {
		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
		ptep = &l2b->l2b_kva[l2pte_index(va)];
		pg = PHYS_TO_VM_PAGE(l2pte_pa(*ptep));
		TAILQ_INSERT_TAIL(&mlist, pg, pageq);
		va += PAGE_SIZE;
	}
	pmap_kremove((vaddr_t)l1->l1_kva, L1_TABLE_SIZE);
	uvm_pglistfree(&mlist);

	/* free backing va */
	uvm_km_free(kernel_map, (vaddr_t)l1->l1_kva, L1_TABLE_SIZE);

	free(l1, M_VMPMAP, 0);
}

/*
 * void pmap_free_l2_ptp(pt_entry_t *)
 *
 * Free an L2 descriptor table.
 */
static __inline void
pmap_free_l2_ptp(pt_entry_t *l2)
{
	pool_put(&pmap_l2ptp_pool, (void *)l2);
}

/*
 * Returns a pointer to the L2 bucket associated with the specified pmap
 * and VA.
 *
 * If no L2 bucket exists, perform the necessary allocations to put an L2
 * bucket/page table in place.
 *
 * Note that if a new L2 bucket/page was allocated, the caller *must*
 * increment the bucket occupancy counter appropriately *before* 
 * releasing the pmap's lock to ensure no other thread or cpu deallocates
 * the bucket/page in the meantime.
 */
struct l2_bucket *
pmap_alloc_l2_bucket(pmap_t pm, vaddr_t va)
{
	struct l2_dtable *l2;
	struct l2_bucket *l2b;
	u_short l1idx;

	l1idx = L1_IDX(va);

	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
		/*
		 * No mapping at this address, as there is
		 * no entry in the L1 table.
		 * Need to allocate a new l2_dtable.
		 */
		if ((l2 = pmap_alloc_l2_dtable()) == NULL)
			return (NULL);

		/*
		 * Link it into the parent pmap
		 */
		pm->pm_l2[L2_IDX(l1idx)] = l2;
	}

	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];

	/*
	 * Fetch pointer to the L2 page table associated with the address.
	 */
	if (l2b->l2b_kva == NULL) {
		pt_entry_t *ptep;

		/*
		 * No L2 page table has been allocated. Chances are, this
		 * is because we just allocated the l2_dtable, above.
		 */
		ptep = pool_get(&pmap_l2ptp_pool, PR_NOWAIT|PR_ZERO);
		if (ptep == NULL) {
			/*
			 * Oops, no more L2 page tables available at this
			 * time. We may need to deallocate the l2_dtable
			 * if we allocated a new one above.
			 */
			if (l2->l2_occupancy == 0) {
				pm->pm_l2[L2_IDX(l1idx)] = NULL;
				pmap_free_l2_dtable(l2);
			}
			return (NULL);
		}
		pmap_l2ptp_ctor(ptep);
		pmap_extract(pmap_kernel(), (vaddr_t)ptep, &l2b->l2b_phys);

		l2->l2_occupancy++;
		l2b->l2b_kva = ptep;
		l2b->l2b_l1idx = l1idx;
	}

	return (l2b);
}

/*
 * One or more mappings in the specified L2 descriptor table have just been
 * invalidated.
 *
 * Garbage collect the metadata and descriptor table itself if necessary.
 *
 * The pmap lock must be acquired when this is called (not necessary
 * for the kernel pmap).
 */
void
pmap_free_l2_bucket(pmap_t pm, struct l2_bucket *l2b, u_int count)
{
	struct l2_dtable *l2;
	pd_entry_t *pl1pd, l1pd;
	pt_entry_t *ptep;
	u_short l1idx;

	KDASSERT(count <= l2b->l2b_occupancy);

	/*
	 * Update the bucket's reference count according to how many
	 * PTEs the caller has just invalidated.
	 */
	l2b->l2b_occupancy -= count;

	/*
	 * Note:
	 *
	 * Level 2 page tables allocated to the kernel pmap are never freed
	 * as that would require checking all Level 1 page tables and
	 * removing any references to the Level 2 page table. See also the
	 * comment elsewhere about never freeing bootstrap L2 descriptors.
	 *
	 * We make do with just invalidating the mapping in the L2 table.
	 *
	 * This isn't really a big deal in practice and, in fact, leads
	 * to a performance win over time as we don't need to continually
	 * alloc/free.
	 */
	if (l2b->l2b_occupancy > 0 || pm == pmap_kernel())
		return;

	/*
	 * There are no more valid mappings in this level 2 page table.
	 * Go ahead and NULL-out the pointer in the bucket, then
	 * free the page table.
	 */
	l1idx = l2b->l2b_l1idx;
	ptep = l2b->l2b_kva;
	l2b->l2b_kva = NULL;

	pl1pd = &pm->pm_l1->l1_kva[l1idx];

	/*
	 * If the L1 slot matches the pmap's domain
	 * number, then invalidate it.
	 */
	l1pd = *pl1pd & (L1_TYPE_MASK | L1_C_DOM_MASK);
	if (l1pd == (L1_C_DOM(pm->pm_domain) | L1_TYPE_C)) {
		*pl1pd = L1_TYPE_INV;
		PTE_SYNC(pl1pd);
	}

	/*
	 * Release the L2 descriptor table back to the pool cache.
	 */
	pmap_free_l2_ptp(ptep);

	/*
	 * Update the reference count in the associated l2_dtable
	 */
	l2 = pm->pm_l2[L2_IDX(l1idx)];
	if (--l2->l2_occupancy > 0)
		return;

	/*
	 * There are no more valid mappings in any of the Level 1
	 * slots managed by this l2_dtable. Go ahead and NULL-out
	 * the pointer in the parent pmap and free the l2_dtable.
	 */
	pm->pm_l2[L2_IDX(l1idx)] = NULL;
	pmap_free_l2_dtable(l2);
}

/*
 * Cache constructors for L2 descriptor tables, metadata and pmap
 * structures.
 */
void
pmap_l2ptp_ctor(void *v)
{
	struct l2_bucket *l2b;
	pt_entry_t *ptep, pte;
	vaddr_t va = (vaddr_t)v & ~PGOFSET;

	/*
	 * The mappings for these page tables were initially made using
	 * pmap_kenter_pa() by the pool subsystem. Therefore, the cache-
	 * mode will not be right for page table mappings. To avoid
	 * polluting the pmap_kenter_pa() code with a special case for
	 * page tables, we simply fix up the cache-mode here if it's not
	 * correct.
	 */
	l2b = pmap_get_l2_bucket(pmap_kernel(), va);
	KDASSERT(l2b != NULL);
	ptep = &l2b->l2b_kva[l2pte_index(va)];
	pte = *ptep;

	/* XXX redundant with PTE_SYNC_RANGE() ? */
	cpu_idcache_wbinv_range(va, PAGE_SIZE);
	cpu_sdcache_wbinv_range(va, pte & L2_S_FRAME, PAGE_SIZE);
	if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
		*ptep = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
		PTE_SYNC(ptep);
		cpu_tlb_flushD_SE(va);
		cpu_cpwait();
	}

	PTE_SYNC_RANGE(v, L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
}

/*
 * Make a pmap_kernel() mapping uncached. Used by bus_dma for coherent pages.
 */
void
pmap_uncache_page(paddr_t va, vaddr_t pa)
{
	struct vm_page *pg;
	struct pv_entry *pv;
	pt_entry_t *pte;

	if ((pg = PHYS_TO_VM_PAGE(pa)) != NULL) {
		pv = pmap_find_pv(pg, pmap_kernel(), va);
		if (pv != NULL)
			pv->pv_flags |= PVF_NC;	/* XXX ought to be pg attr */
	}

	pte = vtopte(va);
	*pte &= ~L2_S_CACHE_MASK;
	*pte |= L2_B; /* device memory */
	PTE_SYNC(pte);
	cpu_tlb_flushD_SE(va);
	cpu_cpwait();
}

/*
 * Modify pte bits for all ptes corresponding to the given physical address.
 * We use `maskbits' rather than `clearbits' because we're always passing
 * constants and the latter would require an extra inversion at run-time.
 */
void
pmap_clearbit(struct vm_page *pg, u_int maskbits)
{
	struct l2_bucket *l2b;
	struct pv_entry *pv;
	pt_entry_t *ptep, npte, opte;
	pmap_t pm;
	vaddr_t va;
	u_int oflags;

	NPDEBUG(PDB_BITS,
	    printf("pmap_clearbit: pg %p (0x%08lx) mask 0x%x\n",
	    pg, pg->phys_addr, maskbits));

	/*
	 * Clear saved attributes (modify, reference)
	 */
	pg->mdpage.pvh_attrs &= ~(maskbits & (PVF_MOD | PVF_REF));

	if (pg->mdpage.pvh_list == NULL)
		return;

	/*
	 * If we are changing a writable or modified page to
	 * read-only (or worse), be sure to flush it first.
	 */
	if (maskbits & (PVF_WRITE|PVF_MOD))
		pmap_clean_page(pg, FALSE);

	/*
	 * Loop over all current mappings setting/clearing as appropriate
	 */
	for (pv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
		va = pv->pv_va;
		pm = pv->pv_pmap;
		oflags = pv->pv_flags;
		pv->pv_flags &= ~maskbits;

		l2b = pmap_get_l2_bucket(pm, va);
		KDASSERT(l2b != NULL);

		ptep = &l2b->l2b_kva[l2pte_index(va)];
		npte = opte = *ptep;
		NPDEBUG(PDB_BITS,
		    printf(
		    "pmap_clearbit: pv %p, pm %p, va 0x%08lx, flag 0x%x\n",
		    pv, pv->pv_pmap, pv->pv_va, oflags));

		if (maskbits & (PVF_WRITE|PVF_MOD)) {
			/* make the pte read only */
			npte = (npte & ~L2_S_PROT_MASK) |
			    L2_S_PROT(pm == pmap_kernel() ? PTE_KERNEL : PTE_USER,
			      npte & L2_V7_S_XN ? PROT_READ : PROT_READ | PROT_EXEC);
		}

		if (maskbits & PVF_REF) {
			/*
			 * Make the PTE invalid so that we will take a
			 * page fault the next time the mapping is
			 * referenced.
			 */
			npte = (npte & ~L2_TYPE_MASK) | L2_TYPE_INV |
			    (npte & L2_V7_S_XN);
		}

		if (npte != opte) {
			*ptep = npte;
			PTE_SYNC(ptep);
			/* Flush the TLB entry if a current pmap. */
			if (PV_BEEN_EXECD(oflags))
				pmap_tlb_flushID_SE(pm, pv->pv_va);
			else
			if (PV_BEEN_REFD(oflags))
				pmap_tlb_flushD_SE(pm, pv->pv_va);
		}

		NPDEBUG(PDB_BITS,
		    printf("pmap_clearbit: pm %p va 0x%lx opte 0x%08x npte 0x%08x\n",
		    pm, va, opte, npte));
	}
}

/*
 * pmap_clean_page()
 *
 * This is a local function used to work out the best strategy to writeback
 * a single page.
 *
 * Its policy is effectively:
 *  o If there are no mappings, we don't bother doing anything with the cache.
 *  o If there is a valid mapping, we use it to clean that page.
 *  o If there is no valid mapping, we create a temporary one and wb through it.
 */
void
pmap_clean_page(struct vm_page *pg, int isync)
{
	pmap_t pm;
	struct pv_entry *pv;
	boolean_t wb = FALSE;

	/*
	 * To save time, we are only walking the pv list if an I$ invalidation
	 * is required.  Otherwise all we need is to map the page and writeback.
	 */
	if (isync) {
		if (curproc)
			pm = curproc->p_vmspace->vm_map.pmap;
		else
			pm = pmap_kernel();

		for (pv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
			/* inline !pmap_is_current(pv->pv_pmap) */
			if (pv->pv_pmap != pmap_kernel() && pv->pv_pmap != pm)
				continue;

			/*
			 * The page is mapped non-cacheable in 
			 * this map.  No need to flush the cache.
			 */
			if (pv->pv_flags & PVF_NC) /* XXX ought to be pg attr */
				break;

			if (PV_BEEN_EXECD(pv->pv_flags))
				cpu_icache_sync_range(pv->pv_va, PAGE_SIZE);

			/*
			 * If we have not written back that page yet, do this
			 * now while we still have a valid mapping for it.
			 */
			if (!wb) {
				cpu_dcache_wb_range(pv->pv_va, PAGE_SIZE);
				cpu_sdcache_wb_range(pv->pv_va,
				    VM_PAGE_TO_PHYS(pg), PAGE_SIZE);
				wb = TRUE;
			}
		}
	}

	/*
	 * If there is no active mapping left, or we did not bother checking
	 * for one, this does not mean the page doesn't have stale data. Map
	 * it in a working page and writeback.
	 */
	if (!wb) {
		*cwb_pte = L2_S_PROTO | VM_PAGE_TO_PHYS(pg) |
		    L2_S_PROT(PTE_KERNEL, PROT_WRITE) | pte_l2_s_cache_mode;
		PTE_SYNC(cwb_pte);
		cpu_tlb_flushD_SE(cwbp);
		cpu_cpwait();
		cpu_dcache_wb_range(cwbp, PAGE_SIZE);
		cpu_sdcache_wb_range(cwbp, VM_PAGE_TO_PHYS(pg), PAGE_SIZE);
	}
}

/*
 * Routine:	pmap_page_remove
 * Function:
 *		Removes this physical page from
 *		all physical maps in which it resides.
 *		Reflects back modify bits to the pager.
 */
void
pmap_page_remove(struct vm_page *pg)
{
	struct l2_bucket *l2b;
	struct pv_entry *pv, *npv;
	pmap_t pm, curpm;
	pt_entry_t *ptep, pte;
	boolean_t flush;

	NPDEBUG(PDB_FOLLOW,
	    printf("pmap_page_remove: pg %p (0x%08lx)\n", pg, pg->phys_addr));

	pv = pg->mdpage.pvh_list;
	if (pv == NULL)
		return;

	flush = FALSE;
	if (curproc)
		curpm = curproc->p_vmspace->vm_map.pmap;
	else
		curpm = pmap_kernel();

	while (pv) {
		pm = pv->pv_pmap;

		l2b = pmap_get_l2_bucket(pm, pv->pv_va);
		KDASSERT(l2b != NULL);

		ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
		if (l2pte_valid(*ptep)) {
			pte = *ptep;

			/* inline pmap_is_current(pm) */
			if (pm == curpm || pm == pmap_kernel()) {
				if (PV_BEEN_EXECD(pv->pv_flags))
					cpu_icache_sync_range(pv->pv_va, PAGE_SIZE);
				if (flush == FALSE) {
					paddr_t pa;
					cpu_dcache_wb_range(pv->pv_va,
					    PAGE_SIZE);
					if (pmap_extract(pm, (vaddr_t)pv->pv_va,
					    &pa))
						cpu_sdcache_wb_range(pv->pv_va,
						    pa, PAGE_SIZE);
				}
				flush = TRUE;
			}

			/*
			 * Update statistics
			 */
			--pm->pm_stats.resident_count;

			/* Wired bit */
			if (pv->pv_flags & PVF_WIRED)
				--pm->pm_stats.wired_count;

			/*
			 * Invalidate the PTEs.
			 */
			*ptep = L2_TYPE_INV;
			PTE_SYNC(ptep);
			if (flush)
				cpu_tlb_flushID_SE(pv->pv_va);

			pmap_free_l2_bucket(pm, l2b, 1);
		}

		npv = pv->pv_next;
		pool_put(&pmap_pv_pool, pv);
		pv = npv;
	}
	pg->mdpage.pvh_list = NULL;

	if (flush)
		cpu_cpwait();
}

/*
 * pmap_t pmap_create(void)
 *  
 *      Create a new pmap structure from scratch.
 */
pmap_t
pmap_create(void)
{
	pmap_t pm;

	pm = pool_get(&pmap_pmap_pool, PR_WAITOK|PR_ZERO);

	pm->pm_refs = 1;
	pm->pm_stats.wired_count = 0;
	pmap_alloc_l1(pm, PMAP_DOMAIN_USER_V7);

	/*
	 * Note: The pool ctor ensures that the pm_l2[] array is already
	 * initialised to zero.
	 */

	return (pm);
}

/*
 * void pmap_enter(pmap_t pm, vaddr_t va, paddr_t pa, vm_prot_t prot,
 *     int flags)
 *  
 *      Insert the given physical page (p) at
 *      the specified virtual address (v) in the
 *      target physical map with the protection requested.
 *
 *      NB:  This is the only routine which MAY NOT lazy-evaluate
 *      or lose information.  That is, this routine must actually
 *      insert this page into the given map NOW.
 */
int
pmap_enter(pmap_t pm, vaddr_t va, paddr_t pa, vm_prot_t prot, int flags)
{
	struct l2_bucket *l2b;
	struct vm_page *pg, *opg;
	struct pv_entry *pve;
	pt_entry_t *ptep, npte, opte;
	u_int nflags;
	u_int oflags;
	int mapped = 1;

	NPDEBUG(PDB_ENTER, printf("pmap_enter: pm %p va 0x%lx pa 0x%lx prot %x flag %x\n", pm, va, pa, prot, flags));

	KDASSERT((flags & PMAP_WIRED) == 0 || (flags & PROT_MASK) != 0);
	KDASSERT(((va | pa) & PGOFSET) == 0);

	/*
	 * Get a pointer to the page.  Later on in this function, we
	 * test for a managed page by checking pg != NULL.
	 */
	pg = pmap_initialized ? PHYS_TO_VM_PAGE(pa) : NULL;

	nflags = 0;
	if (prot & PROT_WRITE)
		nflags |= PVF_WRITE;
	if (prot & PROT_EXEC)
		nflags |= PVF_EXEC;
	if (flags & PMAP_WIRED)
		nflags |= PVF_WIRED;

	/*
	 * Fetch the L2 bucket which maps this page, allocating one if
	 * necessary for user pmaps.
	 */
	if (pm == pmap_kernel())
		l2b = pmap_get_l2_bucket(pm, va);
	else
		l2b = pmap_alloc_l2_bucket(pm, va);
	if (l2b == NULL) {
		if (flags & PMAP_CANFAIL)
			return (ENOMEM);

		panic("pmap_enter: failed to allocate L2 bucket");
	}
	ptep = &l2b->l2b_kva[l2pte_index(va)];
	opte = *ptep;
	npte = pa;
	oflags = 0;

	if (opte != 0) {	/* not l2pte_valid!!! MIOD */
		/*
		 * There is already a mapping at this address.
		 * If the physical address is different, lookup the
		 * vm_page.
		 */
		if (l2pte_pa(opte) != pa)
			opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
		else
			opg = pg;
	} else
		opg = NULL;

	if (pg) {
		/*
		 * This has to be a managed mapping.
		 */
		if ((flags & PROT_MASK) ||
		    (pg->mdpage.pvh_attrs & PVF_REF)) {
			/*
			 * - The access type indicates that we don't need
			 *   to do referenced emulation.
			 * OR
			 * - The physical page has already been referenced
			 *   so no need to re-do referenced emulation here.
			 */
			npte |= L2_S_PROTO;

			nflags |= PVF_REF;

			if ((prot & PROT_WRITE) != 0 &&
			    ((flags & PROT_WRITE) != 0 ||
			     (pg->mdpage.pvh_attrs & PVF_MOD) != 0)) {
				/*
				 * This is a writable mapping, and the
				 * page's mod state indicates it has
				 * already been modified. Make it
				 * writable from the outset.
				 */
				nflags |= PVF_MOD;
			}
		} else {
			/*
			 * Need to do page referenced emulation.
			 */
			npte &= ~L2_TYPE_MASK;
			npte |= L2_TYPE_INV;
			prot &= ~PROT_WRITE;
			mapped = 0;
		}

		npte |= pte_l2_s_cache_mode;

		if (pg == opg) {
			/*
			 * We're changing the attrs of an existing mapping.
			 */
			oflags = pmap_modify_pv(pg, pm, va,
			    PVF_WRITE | PVF_EXEC | PVF_WIRED |
			    PVF_MOD | PVF_REF, nflags);

			/*
			 * We may need to flush the cache if we're
			 * doing rw-ro...
			 */
			if ((oflags & PVF_NC) == 0 &&
			    l2pte_is_writeable(opte, pm) &&
			    (prot & PROT_WRITE) == 0) {
				cpu_dcache_wb_range(va, PAGE_SIZE);
				cpu_sdcache_wb_range(va, opte & L2_S_FRAME,
				    PAGE_SIZE);
			}
		} else {
			/*
			 * New mapping, or changing the backing page
			 * of an existing mapping.
			 */
			if (opg) {
				/*
				 * Replacing an existing mapping with a new one.
				 * It is part of our managed memory so we
				 * must remove it from the PV list
				 */
				pve = pmap_remove_pv(opg, pm, va);
				oflags = pve->pv_flags;
			} else
			if ((pve = pool_get(&pmap_pv_pool, PR_NOWAIT)) == NULL){
				if ((flags & PMAP_CANFAIL) == 0)
					panic("pmap_enter: no pv entries");

				if (pm != pmap_kernel())
					pmap_free_l2_bucket(pm, l2b, 0);

				NPDEBUG(PDB_ENTER,
				    printf("pmap_enter: ENOMEM\n"));
				return (ENOMEM);
			}

			pmap_enter_pv(pg, pve, pm, va, nflags);
		}
	} else {
		/*
		 * We're mapping an unmanaged page.
		 * These are always readable, and possibly writable, from
		 * the get go as we don't need to track ref/mod status.
		 */
		npte |= L2_S_PROTO;

		if (opg) {
			/*
			 * Looks like there's an existing 'managed' mapping
			 * at this address.
			 */
			pve = pmap_remove_pv(opg, pm, va);
			oflags = pve->pv_flags;

			pool_put(&pmap_pv_pool, pve);
		}
	}

	/*
	 * Make sure userland mappings get the right permissions
	 */
	npte |= L2_S_PROT(pm == pmap_kernel() ?  PTE_KERNEL : PTE_USER,
	    prot & ~PROT_WRITE);

	/*
	 * Keep the stats up to date
	 */
	if (opte == 0) {	/* !! not l2pte_valid MIOD */
		l2b->l2b_occupancy++;
		pm->pm_stats.resident_count++;
	} 

	NPDEBUG(PDB_ENTER,
	    printf("pmap_enter: opte 0x%08x npte 0x%08x\n", opte, npte));

	/*
	 * If this is just a wiring change, the two PTEs will be
	 * identical, so there's no need to update the page table.
	 */
	if (npte != opte) {
		*ptep = npte;
		/*
		 * We only need to frob the cache/tlb if this pmap
		 * is current
		 */
		PTE_SYNC(ptep);
		if (/* va != vector_page && */ l2pte_valid(npte)) {
			/*
			 * This mapping is likely to be accessed as
			 * soon as we return to userland. Fix up the
			 * L1 entry to avoid taking another
			 * page/domain fault.
			 */
			pd_entry_t *pl1pd, l1pd;

			pl1pd = &pm->pm_l1->l1_kva[L1_IDX(va)];
			l1pd = l2b->l2b_phys | L1_C_DOM(pm->pm_domain) |
			    L1_C_PROTO;
			if (*pl1pd != l1pd) {
				*pl1pd = l1pd;
				PTE_SYNC(pl1pd);
			}
		}

		if (PV_BEEN_EXECD(oflags))
			pmap_tlb_flushID_SE(pm, va);
		else
		if (PV_BEEN_REFD(oflags))
			pmap_tlb_flushD_SE(pm, va);
	}

	/*
	 * Make sure executable pages do not have stale data in I$,
	 * which is VIPT.
	 */
	if (mapped && (prot & PROT_EXEC) != 0 && pmap_is_current(pm))
		cpu_icache_sync_range(va, PAGE_SIZE);

	return (0);
}

/*
 * pmap_remove()
 *
 * pmap_remove is responsible for nuking a number of mappings for a range
 * of virtual address space in the current pmap.
 */

void
pmap_remove(pmap_t pm, vaddr_t sva, vaddr_t eva)
{
	struct l2_bucket *l2b;
	vaddr_t next_bucket;
	pt_entry_t *ptep;
	u_int mappings, is_exec, is_refd;

	NPDEBUG(PDB_REMOVE, printf("pmap_remove: pmap=%p sva=%08lx eva=%08lx\n",
	    pm, sva, eva));

	while (sva < eva) {
		/*
		 * Do one L2 bucket's worth at a time.
		 */
		next_bucket = L2_NEXT_BUCKET(sva);
		if (next_bucket > eva)
			next_bucket = eva;

		l2b = pmap_get_l2_bucket(pm, sva);
		if (l2b == NULL) {
			sva = next_bucket;
			continue;
		}

		ptep = &l2b->l2b_kva[l2pte_index(sva)];
		mappings = 0;

		while (sva < next_bucket) {
			struct vm_page *pg;
			pt_entry_t pte;
			paddr_t pa;

			pte = *ptep;

			if (pte == 0) {	/* !!! not l2pte_valid */
				/*
				 * Nothing here, move along
				 */
				sva += PAGE_SIZE;
				ptep++;
				continue;
			}

			pm->pm_stats.resident_count--;
			pa = l2pte_pa(pte);
			is_exec = 0;
			is_refd = l2pte_valid(pte);

			/*
			 * Update flags. In a number of circumstances,
			 * we could cluster a lot of these and do a
			 * number of sequential pages in one go.
			 */
			pg = PHYS_TO_VM_PAGE(pa);
			if (pg != NULL) {
				struct pv_entry *pve;
				pve = pmap_remove_pv(pg, pm, sva);
				if (pve != NULL) {
					is_exec = PV_BEEN_EXECD(pve->pv_flags);
					is_refd = PV_BEEN_REFD(pve->pv_flags);
					pool_put(&pmap_pv_pool, pve);
				}
			}

			/*
			 * If the cache is physically indexed, we need
			 * to flush any changes to the page before it
			 * gets invalidated.	
			 */
			if (pg != NULL)
				pmap_clean_page(pg, TRUE);

			*ptep = L2_TYPE_INV;
			PTE_SYNC(ptep);
			if (is_exec)
				pmap_tlb_flushID_SE(pm, sva);
			else
			if (is_refd)
				pmap_tlb_flushD_SE(pm, sva);

			sva += PAGE_SIZE;
			ptep++;
			mappings++;
		}

		/*
		 * Deal with any left overs
		 */
		if (!pmap_is_current(pm))
			cpu_idcache_wbinv_all();

		pmap_free_l2_bucket(pm, l2b, mappings);
	}
}

/*
 * pmap_kenter_pa: enter an unmanaged, wired kernel mapping
 *
 * We assume there is already sufficient KVM space available
 * to do this, as we can't allocate L2 descriptor tables/metadata
 * from here.
 */
void
pmap_kenter_pa(vaddr_t va, paddr_t pa, vm_prot_t prot)
{
	struct l2_bucket *l2b;
	pt_entry_t *ptep, opte, npte;

	NPDEBUG(PDB_KENTER,
	    printf("pmap_kenter_pa: va 0x%08lx, pa 0x%08lx, prot 0x%x\n",
	    va, pa, prot));

	l2b = pmap_get_l2_bucket(pmap_kernel(), va);
	KDASSERT(l2b != NULL);

	ptep = &l2b->l2b_kva[l2pte_index(va)];
	opte = *ptep;

	if (l2pte_valid(opte)) {
		cpu_dcache_wb_range(va, PAGE_SIZE);
		cpu_sdcache_wb_range(va, opte & L2_S_FRAME, PAGE_SIZE);
	} else
	if (opte == 0)
		l2b->l2b_occupancy++;

	npte = L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) |
	    pte_l2_s_cache_mode;
	*ptep = npte;
	PTE_SYNC(ptep);
	if (l2pte_valid(opte)) {
		cpu_tlb_flushD_SE(va);
		cpu_cpwait();
	}
}

void
pmap_kenter_cache(vaddr_t va, paddr_t pa, vm_prot_t prot, int cacheable)
{
	pmap_kenter_pa(va, pa, prot);
	if (cacheable == 0)
		pmap_uncache_page(va, pa);
}

void
pmap_kremove(vaddr_t va, vsize_t len)
{
	struct l2_bucket *l2b;
	pt_entry_t *ptep, *sptep, opte;
	vaddr_t next_bucket, eva;
	u_int mappings;

	NPDEBUG(PDB_KREMOVE, printf("pmap_kremove: va 0x%08lx, len 0x%08lx\n",
	    va, len));

	eva = va + len;

	while (va < eva) {
		next_bucket = L2_NEXT_BUCKET(va);
		if (next_bucket > eva)
			next_bucket = eva;

		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
		KDASSERT(l2b != NULL);

		sptep = ptep = &l2b->l2b_kva[l2pte_index(va)];
		mappings = 0;

		while (va < next_bucket) {
			opte = *ptep;
			if (l2pte_valid(opte)) {
				cpu_dcache_wb_range(va, PAGE_SIZE);
				cpu_sdcache_wb_range(va, opte & L2_S_FRAME,
				    PAGE_SIZE);
			}
			if (opte != 0) {	/* !! not l2pte_valid */
				*ptep = L2_TYPE_INV;
				PTE_SYNC(ptep);
				mappings++;
			}
			if (l2pte_valid(opte))
				cpu_tlb_flushD_SE(va);
			va += PAGE_SIZE;
			ptep++;
		}
		KDASSERT(mappings <= l2b->l2b_occupancy);
		l2b->l2b_occupancy -= mappings;
	}
	cpu_cpwait();
}

boolean_t
pmap_extract(pmap_t pm, vaddr_t va, paddr_t *pap)
{
	struct l2_dtable *l2;
	pd_entry_t *pl1pd, l1pd;
	pt_entry_t *ptep, pte;
	paddr_t pa;
	u_int l1idx;


	l1idx = L1_IDX(va);
	pl1pd = &pm->pm_l1->l1_kva[l1idx];
	l1pd = *pl1pd;

	if (l1pte_section_p(l1pd)) {
		/*
		 * These should only happen for pmap_kernel()
		 */
		KDASSERT(pm == pmap_kernel());
		pa = (l1pd & L1_S_FRAME) | (va & L1_S_OFFSET);
	} else {
		/*
		 * Note that we can't rely on the validity of the L1
		 * descriptor as an indication that a mapping exists.
		 * We have to look it up in the L2 dtable.
		 */
		l2 = pm->pm_l2[L2_IDX(l1idx)];

		if (l2 == NULL ||
		    (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
			return (FALSE);
		}

		ptep = &ptep[l2pte_index(va)];
		pte = *ptep;

		if (pte == 0)	/* !!! not l2pte_valid */
			return (FALSE);

		switch (pte & L2_TYPE_MASK) {
		case L2_TYPE_L:
			pa = (pte & L2_L_FRAME) | (va & L2_L_OFFSET);
			break;
		/*
		 * Can't check for L2_TYPE_S on V7 because of the XN
		 * bit being part of L2_TYPE_MASK for S mappings.
		 */
		default:
			pa = (pte & L2_S_FRAME) | (va & L2_S_OFFSET);
			break;
		}
	}

	if (pap != NULL)
		*pap = pa;

	return (TRUE);
}

void
pmap_protect(pmap_t pm, vaddr_t sva, vaddr_t eva, vm_prot_t prot)
{
	struct l2_bucket *l2b;
	pt_entry_t *ptep, pte;
	vaddr_t next_bucket;
	u_int flags;
	int flush;

	NPDEBUG(PDB_PROTECT,
	    printf("pmap_protect: pm %p sva 0x%lx eva 0x%lx prot 0x%x",
	    pm, sva, eva, prot));

	if ((prot & PROT_READ) == 0) {
NPDEBUG(PDB_PROTECT, printf("\n"));
		pmap_remove(pm, sva, eva);
		return;
	}

	if (prot & PROT_WRITE) {
		/*
		 * If this is a read->write transition, just ignore it and let
		 * uvm_fault() take care of it later.
		 */
NPDEBUG(PDB_PROTECT, printf("\n"));
/* XXX WHAT IF RWX -> RW ??? */
		return;
	}

	/*
	 * OK, at this point, we know we're doing write-protect operation.
	 */

	/* XXX is that threshold of 4 the best choice for v7? */
	if (pmap_is_current(pm))
		flush = ((eva - sva) > (PAGE_SIZE * 4)) ? -1 : 0;
	else
		flush = -1;
	flags = 0;

	while (sva < eva) {
		next_bucket = L2_NEXT_BUCKET(sva);
		if (next_bucket > eva)
			next_bucket = eva;

		l2b = pmap_get_l2_bucket(pm, sva);
		if (l2b == NULL) {
			sva = next_bucket;
			continue;
		}

		ptep = &l2b->l2b_kva[l2pte_index(sva)];

		while (sva < next_bucket) {
			pte = *ptep;
			/* !!! not l2pte_valid */
/* XXX actually would only matter if really valid ??? */
			if (pte != 0 && l2pte_is_writeable(pte, pm)) {
				struct vm_page *pg;
				u_int f;

				pg = PHYS_TO_VM_PAGE(l2pte_pa(pte));
				if (pg != NULL)
					pmap_clean_page(pg, FALSE);
				pte = (pte & ~L2_S_PROT_MASK) |
				    L2_S_PROT(pm == pmap_kernel() ? PTE_KERNEL : PTE_USER,
				      pte & L2_V7_S_XN ? PROT_READ : PROT_READ | PROT_EXEC);
				*ptep = pte;
				PTE_SYNC(ptep);

				if (pg != NULL) {
					f = pmap_modify_pv(pg, pm, sva,
					    PVF_WRITE, 0);
				} else
					f = PVF_REF | PVF_EXEC;

				if (flush >= 0) {
					flush++;
					if (PV_BEEN_EXECD(f))
						cpu_tlb_flushID_SE(sva);
					else
					if (PV_BEEN_REFD(f))
						cpu_tlb_flushD_SE(sva);
				} else
					flags |= f;
			}

			sva += PAGE_SIZE;
			ptep++;
		}
	}

	if (flush < 0) {
		if (PV_BEEN_EXECD(flags))
			pmap_tlb_flushID(pm);
		else
		if (PV_BEEN_REFD(flags))
			pmap_tlb_flushD(pm);
	}
NPDEBUG(PDB_PROTECT, printf("\n"));
}

void
pmap_page_protect(struct vm_page *pg, vm_prot_t prot)
{

	NPDEBUG(PDB_PROTECT,
	    printf("pmap_page_protect: pg %p (0x%08lx), prot 0x%x\n",
	    pg, pg->phys_addr, prot));

	switch(prot) {
	case PROT_READ | PROT_WRITE | PROT_EXEC:
	case PROT_READ | PROT_WRITE:
		return;

	case PROT_READ:
	case PROT_READ | PROT_EXEC:
		pmap_clearbit(pg, PVF_WRITE);
		break;

	default:
		pmap_page_remove(pg);
		break;
	}
}

/*
 * pmap_clear_modify:
 *
 *	Clear the "modified" attribute for a page.
 */
boolean_t
pmap_clear_modify(struct vm_page *pg)
{
	boolean_t rv;

	if (pg->mdpage.pvh_attrs & PVF_MOD) {
		rv = TRUE;
		pmap_clearbit(pg, PVF_MOD);
	} else
		rv = FALSE;

	return (rv);
}

/*
 * pmap_clear_reference:
 *
 *	Clear the "referenced" attribute for a page.
 */
boolean_t
pmap_clear_reference(struct vm_page *pg)
{
	boolean_t rv;

	if (pg->mdpage.pvh_attrs & PVF_REF) {
		rv = TRUE;
		pmap_clearbit(pg, PVF_REF);
	} else
		rv = FALSE;

	return (rv);
}

/*
 * pmap_is_modified:
 *
 *	Test if a page has the "modified" attribute.
 */
/* See <arm/pmap.h> */

/*
 * pmap_is_referenced:
 *
 *	Test if a page has the "referenced" attribute.
 */
/* See <arm/pmap.h> */

int
pmap_fault_fixup(pmap_t pm, vaddr_t va, vm_prot_t ftype, int user)
{
	struct l2_dtable *l2;
	struct l2_bucket *l2b;
	pd_entry_t *pl1pd, l1pd;
	pt_entry_t *ptep, pte;
	paddr_t pa;
	u_int l1idx;
	int rv = 0;

	l1idx = L1_IDX(va);

	/*
	 * If there is no l2_dtable for this address, then the process
	 * has no business accessing it.
	 *
	 * Note: This will catch userland processes trying to access
	 * kernel addresses.
	 */
	l2 = pm->pm_l2[L2_IDX(l1idx)];
	if (l2 == NULL)
		goto out;

	/*
	 * Likewise if there is no L2 descriptor table
	 */
	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
	if (l2b->l2b_kva == NULL)
		goto out;

	/*
	 * Check the PTE itself.
	 */
	ptep = &l2b->l2b_kva[l2pte_index(va)];
	pte = *ptep;
	if (pte == 0)
		goto out;

	/* only if vectors are low ?? */
	/*
	 * Catch a userland access to the vector page mapped at 0x0
	 */
	if (user) {
		/* XXX use of L2_V7_S_XN */
		if ((pte & L2_S_PROT_MASK & ~L2_V7_S_XN) != L2_S_PROT(PTE_USER, PROT_READ) &&
		    (pte & L2_S_PROT_MASK & ~L2_V7_S_XN) != L2_S_PROT(PTE_USER, PROT_WRITE))
			goto out;
	}

	pa = l2pte_pa(pte);

	if ((ftype & PROT_EXEC) && (pte & L2_V7_S_XN)) {
printf("%s: va %08lx ftype %x %c pte %08x\n", __func__, va, ftype, user ? 'u' : 's', pte);
printf("fault on exec\n");
#ifdef DDB
Debugger();
#endif
		/* XXX FIX THIS */
		goto out;
	}
	if ((ftype & PROT_WRITE) && !l2pte_is_writeable(pte, pm)) {
		/*
		 * This looks like a good candidate for "page modified"
		 * emulation...
		 */
		struct pv_entry *pv;
		struct vm_page *pg;

		/* Extract the physical address of the page */
		if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL)
			goto out;

		/* Get the current flags for this page. */
		pv = pmap_find_pv(pg, pm, va);
		if (pv == NULL)
			goto out;

		/*
		 * Do the flags say this page is writable? If not then it
		 * is a genuine write fault. If yes then the write fault is
		 * our fault as we did not reflect the write access in the
		 * PTE. Now we know a write has occurred we can correct this
		 * and also set the modified bit
		 */
		if ((pv->pv_flags & PVF_WRITE) == 0)
			goto out;

		NPDEBUG(PDB_FOLLOW,
		    printf("pmap_fault_fixup: mod emul. pm %p, va 0x%08lx, pa 0x%08lx\n",
		    pm, va, pg->phys_addr));

		pg->mdpage.pvh_attrs |= PVF_REF | PVF_MOD;
		pv->pv_flags |= PVF_REF | PVF_MOD;

		/* 
		 * Re-enable write permissions for the page.
		 * We've already set the cacheable bits based on
		 * the assumption that we can write to this page.
		 */
		*ptep = (pte & ~(L2_TYPE_MASK|L2_S_PROT_MASK)) | L2_S_PROTO |
		    L2_S_PROT(pm == pmap_kernel() ? PTE_KERNEL : PTE_USER,
		      pte & L2_V7_S_XN ? PROT_WRITE : PROT_WRITE | PROT_EXEC);
		PTE_SYNC(ptep);
		rv = 1;
	} else
	/* XXX use of L2_V7_S_XN */
	if ((pte & L2_TYPE_MASK & ~L2_V7_S_XN) == L2_TYPE_INV) {
		/*
		 * This looks like a good candidate for "page referenced"
		 * emulation.
		 */
		struct pv_entry *pv;
		struct vm_page *pg;

		/* Extract the physical address of the page */
		if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL)
			goto out;

		/* Get the current flags for this page. */
		pv = pmap_find_pv(pg, pm, va);
		if (pv == NULL)
			goto out;

		pg->mdpage.pvh_attrs |= PVF_REF;
		pv->pv_flags |= PVF_REF;

		NPDEBUG(PDB_FOLLOW,
		    printf("pmap_fault_fixup: ref emul. pm %p, va 0x%08lx, pa 0x%08lx\n",
		    pm, va, pg->phys_addr));

		/* XXX use of L2_V7_S_XN */
		*ptep = (pte & ~(L2_TYPE_MASK & ~L2_V7_S_XN)) | L2_S_PROTO;
		PTE_SYNC(ptep);
		rv = 1;
	} else {
printf("%s: va %08lx ftype %x %c pte %08x\n", __func__, va, ftype, user ? 'u' : 's', pte);
		goto out;
	}

	/*
	 * We know there is a valid mapping here, so simply
	 * fix up the L1 if necessary.
	 */
	pl1pd = &pm->pm_l1->l1_kva[l1idx];
	l1pd = l2b->l2b_phys | L1_C_DOM(pm->pm_domain) | L1_C_PROTO;
	if (*pl1pd != l1pd) {
		*pl1pd = l1pd;
		PTE_SYNC(pl1pd);
		rv = 1;
	}

	if (rv) {
		cpu_tlb_flushID_SE(va);
		cpu_cpwait();
	}

out:
	return (rv);
}

/*
 * pmap_collect: free resources held by a pmap
 *
 * => optional function.
 * => called when a process is swapped out to free memory.
 */
void
pmap_collect(pmap_t pm)
{
	/*
	 * Nothing to do.
	 * We don't even need to free-up the process' L1.
	 */
}

/*
 * Routine:	pmap_proc_iflush
 *
 * Function:
 *	Synchronize caches corresponding to [addr, addr+len) in p.
 *
 */
void
pmap_proc_iflush(struct proc *p, vaddr_t va, vsize_t len)
{
	/* We only need to do anything if it is the current process. */
	if (p == curproc)
		cpu_icache_sync_range(va, len);
}

/*
 * Routine:	pmap_unwire
 * Function:	Clear the wired attribute for a map/virtual-address pair.
 *
 * In/out conditions:
 *		The mapping must already exist in the pmap.
 */
void
pmap_unwire(pmap_t pm, vaddr_t va)
{
	struct l2_bucket *l2b;
	pt_entry_t *ptep, pte;
	struct vm_page *pg;
	paddr_t pa;

	NPDEBUG(PDB_WIRING, printf("pmap_unwire: pm %p, va 0x%08lx\n", pm, va));

	l2b = pmap_get_l2_bucket(pm, va);
	KDASSERT(l2b != NULL);

	ptep = &l2b->l2b_kva[l2pte_index(va)];
	pte = *ptep;

	/* Extract the physical address of the page */
	pa = l2pte_pa(pte);

	if ((pg = PHYS_TO_VM_PAGE(pa)) != NULL) {
		/* Update the wired bit in the pv entry for this page. */
		(void) pmap_modify_pv(pg, pm, va, PVF_WIRED, 0);
	}
}

void
pmap_activate(struct proc *p)
{
	pmap_t pm;
	struct pcb *pcb;
	int s;

	pm = p->p_vmspace->vm_map.pmap;
	pcb = &p->p_addr->u_pcb;

	pmap_set_pcb_pagedir(pm, pcb);

	if (p == curproc) {
		u_int cur_dacr, cur_ttb;

		__asm volatile("mrc p15, 0, %0, c2, c0, 0" : "=r"(cur_ttb));
		__asm volatile("mrc p15, 0, %0, c3, c0, 0" : "=r"(cur_dacr));

		cur_ttb &= ~(L1_TABLE_SIZE - 1);

		if (cur_ttb == (u_int)pcb->pcb_pagedir &&
		    cur_dacr == pcb->pcb_dacr) {
			/*
			 * No need to switch address spaces.
			 */
			return;
		}

		s = splhigh();
		disable_interrupts(PSR_I | PSR_F);

		/*
		 * We MUST, I repeat, MUST fix up the L1 entry corresponding
		 * to 'vector_page' in the incoming L1 table before switching
		 * to it otherwise subsequent interrupts/exceptions (including
		 * domain faults!) will jump into hyperspace.
		 */
		if (pcb->pcb_pl1vec) {
			*pcb->pcb_pl1vec = pcb->pcb_l1vec;
			/*
			 * Don't need to PTE_SYNC() at this point since
			 * cpu_setttb() is about to flush both the cache
			 * and the TLB.
			 */
		}

		cpu_domains(pcb->pcb_dacr);
		cpu_setttb(pcb->pcb_pagedir);

		enable_interrupts(PSR_I | PSR_F);

		splx(s);
	}
}

void
pmap_update(pmap_t pm)
{
	/*
	 * make sure TLB/cache operations have completed.
	 */
	cpu_cpwait();
}

/*
 * Retire the given physical map from service.
 * Should only be called if the map contains no valid mappings.
 */
void
pmap_destroy(pmap_t pm)
{
	u_int count;

	/*
	 * Drop reference count
	 */
	count = --pm->pm_refs;
	if (count > 0)
		return;

	/*
	 * reference count is zero, free pmap resources and then free pmap.
	 */

	pmap_free_l1(pm);

	/* return the pmap to the pool */
	pool_put(&pmap_pmap_pool, pm);
}


/*
 * void pmap_reference(pmap_t pm)
 *
 * Add a reference to the specified pmap.
 */
void
pmap_reference(pmap_t pm)
{
	if (pm == NULL)
		return;

	pm->pm_refs++;
}

/*
 * pmap_zero_page()
 * 
 * Zero a given physical page by mapping it at a page hook point.
 * In doing the zero page op, the page we zero is mapped cachable, as with
 * StrongARM accesses to non-cached pages are non-burst making writing
 * _any_ bulk data very slow.
 */
void
pmap_zero_page_generic(struct vm_page *pg)
{
	paddr_t phys = VM_PAGE_TO_PHYS(pg);
#ifdef DEBUG
	if (pg->mdpage.pvh_list != NULL)
		panic("pmap_zero_page: page has mappings");
#endif

	/*
	 * Hook in the page, zero it, and purge the cache for that
	 * zeroed page. Invalidate the TLB as needed.
	 */
	*cdst_pte = L2_S_PROTO | phys |
	    L2_S_PROT(PTE_KERNEL, PROT_WRITE) | pte_l2_s_cache_mode;
	PTE_SYNC(cdst_pte);
	cpu_tlb_flushD_SE(cdstp);
	cpu_cpwait();
	bzero_page(cdstp);
}

/*
 * pmap_copy_page()
 *
 * Copy one physical page into another, by mapping the pages into
 * hook points. The same comment regarding cachability as in
 * pmap_zero_page also applies here.
 */
void
pmap_copy_page_generic(struct vm_page *src_pg, struct vm_page *dst_pg)
{
	paddr_t src = VM_PAGE_TO_PHYS(src_pg);
	paddr_t dst = VM_PAGE_TO_PHYS(dst_pg);
#ifdef DEBUG
	if (dst_pg->mdpage.pvh_list != NULL)
		panic("pmap_copy_page: dst page has mappings");
#endif

	/*
	 * Map the pages into the page hook points, copy them, and purge
	 * the cache for the appropriate page. Invalidate the TLB
	 * as required.
	 */
	*csrc_pte = L2_S_PROTO | src |
	    L2_S_PROT(PTE_KERNEL, PROT_READ) | pte_l2_s_cache_mode;
	PTE_SYNC(csrc_pte);
	*cdst_pte = L2_S_PROTO | dst |
	    L2_S_PROT(PTE_KERNEL, PROT_WRITE) | pte_l2_s_cache_mode;
	PTE_SYNC(cdst_pte);
	cpu_tlb_flushD_SE(csrcp);
	cpu_tlb_flushD_SE(cdstp);
	cpu_cpwait();
	bcopy_page(csrcp, cdstp);
}

/*
 * void pmap_virtual_space(vaddr_t *start, vaddr_t *end)
 *
 * Return the start and end addresses of the kernel's virtual space.
 * These values are setup in pmap_bootstrap and are updated as pages
 * are allocated.
 */
void
pmap_virtual_space(vaddr_t *start, vaddr_t *end)
{
	*start = virtual_avail;
	*end = virtual_end;
}

/*
 * Helper function for pmap_grow_l2_bucket()
 */
static __inline int
pmap_grow_map(vaddr_t va, pt_entry_t cache_mode, paddr_t *pap)
{
	struct l2_bucket *l2b;
	pt_entry_t *ptep;
	paddr_t pa;

	if (uvm.page_init_done == FALSE) {
		if (uvm_page_physget(&pa) == FALSE)
			return (1);
	} else {
		struct vm_page *pg;
		pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_USERESERVE);
		if (pg == NULL)
			return (1);
		pa = VM_PAGE_TO_PHYS(pg);
	}

	if (pap)
		*pap = pa;

	l2b = pmap_get_l2_bucket(pmap_kernel(), va);
	KDASSERT(l2b != NULL);

	ptep = &l2b->l2b_kva[l2pte_index(va)];
	*ptep = L2_S_PROTO | pa | cache_mode |
	    L2_S_PROT(PTE_KERNEL, PROT_READ | PROT_WRITE);
	PTE_SYNC(ptep);
	cpu_tlb_flushD_SE(va);

	memset((void *)va, 0, PAGE_SIZE);
	return (0);
}

/*
 * This is the same as pmap_alloc_l2_bucket(), except that it is only
 * used by pmap_growkernel().
 */
static __inline struct l2_bucket *
pmap_grow_l2_bucket(pmap_t pm, vaddr_t va)
{
	struct l2_dtable *l2;
	struct l2_bucket *l2b;
	u_short l1idx;
	vaddr_t nva;

	l1idx = L1_IDX(va);

	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
		/*
		 * No mapping at this address, as there is
		 * no entry in the L1 table.
		 * Need to allocate a new l2_dtable.
		 */
		nva = pmap_kernel_l2dtable_kva;
		if ((nva & PGOFSET) == 0) {
			/*
			 * Need to allocate a backing page
			 */
			if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
				return (NULL);
		}

		l2 = (struct l2_dtable *)nva;
		nva += sizeof(struct l2_dtable);

		if ((nva & PGOFSET) < (pmap_kernel_l2dtable_kva & PGOFSET)) {
			/*
			 * The new l2_dtable straddles a page boundary.
			 * Map in another page to cover it.
			 */
			if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
				return (NULL);
		}

		pmap_kernel_l2dtable_kva = nva;

		/*
		 * Link it into the parent pmap
		 */
		pm->pm_l2[L2_IDX(l1idx)] = l2;
	}

	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];

	/*
	 * Fetch pointer to the L2 page table associated with the address.
	 */
	if (l2b->l2b_kva == NULL) {
		pt_entry_t *ptep;

		/*
		 * No L2 page table has been allocated. Chances are, this
		 * is because we just allocated the l2_dtable, above.
		 */
		nva = pmap_kernel_l2ptp_kva;
		ptep = (pt_entry_t *)nva;
		if ((nva & PGOFSET) == 0) {
			/*
			 * Need to allocate a backing page
			 */
			if (pmap_grow_map(nva, pte_l2_s_cache_mode_pt,
			    &pmap_kernel_l2ptp_phys))
				return (NULL);
			PTE_SYNC_RANGE(ptep, PAGE_SIZE / sizeof(pt_entry_t));
		}

		l2->l2_occupancy++;
		l2b->l2b_kva = ptep;
		l2b->l2b_l1idx = l1idx;
		l2b->l2b_phys = pmap_kernel_l2ptp_phys;

		pmap_kernel_l2ptp_kva += L2_TABLE_SIZE_REAL;
		pmap_kernel_l2ptp_phys += L2_TABLE_SIZE_REAL;
	}

	return (l2b);
}

vaddr_t
pmap_growkernel(vaddr_t maxkvaddr)
{
	pmap_t kpm = pmap_kernel();
	struct l1_ttable *l1;
	struct l2_bucket *l2b;
	pd_entry_t *pl1pd;
	int s;

	if (maxkvaddr <= pmap_curmaxkvaddr)
		goto out;		/* we are OK */

	NPDEBUG(PDB_GROWKERN,
	    printf("pmap_growkernel: growing kernel from 0x%lx to 0x%lx\n",
	    pmap_curmaxkvaddr, maxkvaddr));

	KDASSERT(maxkvaddr <= virtual_end);

	/*
	 * whoops!   we need to add kernel PTPs
	 */

	s = splhigh();	/* to be safe */

	/* Map 1MB at a time */
	for (; pmap_curmaxkvaddr < maxkvaddr; pmap_curmaxkvaddr += L1_S_SIZE) {

		l2b = pmap_grow_l2_bucket(kpm, pmap_curmaxkvaddr);
		KDASSERT(l2b != NULL);

		/* Distribute new L1 entry to all other L1s */
		TAILQ_FOREACH(l1, &l1_list, l1_link) {
			pl1pd = &l1->l1_kva[L1_IDX(pmap_curmaxkvaddr)];
			*pl1pd = l2b->l2b_phys | L1_C_DOM(PMAP_DOMAIN_KERNEL) |
			    L1_C_PROTO;
			PTE_SYNC(pl1pd);
		}
	}

	/*
	 * flush out the cache, expensive but growkernel will happen so
	 * rarely
	 */
	cpu_dcache_wbinv_all();
	cpu_sdcache_wbinv_all();
	cpu_tlb_flushD();
	cpu_cpwait();

	splx(s);

out:
	return (pmap_curmaxkvaddr);
}

/************************ Utility routines ****************************/

/*
 * vector_page_setprot:
 *
 *	Manipulate the protection of the vector page.
 */
void
vector_page_setprot(int prot)
{
	struct l2_bucket *l2b;
	pt_entry_t *ptep;

	l2b = pmap_get_l2_bucket(pmap_kernel(), vector_page);
	KDASSERT(l2b != NULL);

	ptep = &l2b->l2b_kva[l2pte_index(vector_page)];

	*ptep = (*ptep & ~L2_S_PROT_MASK) | L2_S_PROT(PTE_KERNEL, prot);
	PTE_SYNC(ptep);
	cpu_tlb_flushD_SE(vector_page);
	cpu_cpwait();
}

/*
 * This is used to stuff certain critical values into the PCB where they
 * can be accessed quickly from cpu_switch() et al.
 */
void
pmap_set_pcb_pagedir(pmap_t pm, struct pcb *pcb)
{
	KDASSERT(pm->pm_l1);
	pcb->pcb_pagedir = pm->pm_l1->l1_physaddr;
	pcb->pcb_dacr = (DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) |
	    (DOMAIN_CLIENT << (pm->pm_domain * 2));

	pcb->pcb_pl1vec = NULL;
}

/*
 * Fetch pointers to the PDE/PTE for the given pmap/VA pair.
 * Returns TRUE if the mapping exists, else FALSE.
 *
 * NOTE: This function is only used by a couple of arm-specific modules.
 * It is not safe to take any pmap locks here, since we could be right
 * in the middle of debugging the pmap anyway...
 *
 * It is possible for this routine to return FALSE even though a valid
 * mapping does exist. This is because we don't lock, so the metadata
 * state may be inconsistent.
 *
 * NOTE: We can return a NULL *ptp in the case where the L1 pde is
 * a "section" mapping.
 */
boolean_t
pmap_get_pde_pte(pmap_t pm, vaddr_t va, pd_entry_t **pdp, pt_entry_t **ptp)
{
	struct l2_dtable *l2;
	pd_entry_t *pl1pd, l1pd;
	pt_entry_t *ptep;
	u_short l1idx;

	if (pm->pm_l1 == NULL)
		return (FALSE);

	l1idx = L1_IDX(va);
	*pdp = pl1pd = &pm->pm_l1->l1_kva[l1idx];
	l1pd = *pl1pd;

	if (l1pte_section_p(l1pd)) {
		*ptp = NULL;
		return (TRUE);
	}

	if (pm->pm_l2 == NULL)
		return (FALSE);

	l2 = pm->pm_l2[L2_IDX(l1idx)];

	if (l2 == NULL ||
	    (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
		return (FALSE);
	}

	*ptp = &ptep[l2pte_index(va)];
	return (TRUE);
}

/************************ Bootstrapping routines ****************************/

void
pmap_init_l1(struct l1_ttable *l1, pd_entry_t *l1pt)
{
	l1->l1_kva = l1pt;

	/*
	 * Copy the kernel's L1 entries to each new L1.
	 */
	if (pmap_initialized) {
		memcpy(l1pt, pmap_kernel()->pm_l1->l1_kva, L1_TABLE_SIZE);
/* XXX overkill? */
		cpu_dcache_wb_range((vaddr_t)l1pt, L1_TABLE_SIZE);
	}

	if (pmap_extract(pmap_kernel(), (vaddr_t)l1pt,
	    &l1->l1_physaddr) == FALSE)
		panic("pmap_init_l1: can't get PA of L1 at %p", l1pt);

	TAILQ_INSERT_TAIL(&l1_list, l1, l1_link);
}

/*
 * pmap_bootstrap() is called from the board-specific initarm() routine
 * once the kernel L1/L2 descriptors tables have been set up.
 *
 * This is a somewhat convoluted process since pmap bootstrap is, effectively,
 * spread over a number of disparate files/functions.
 *
 * We are passed the following parameters
 *  - kernel_l1pt
 *    This is a pointer to the base of the kernel's L1 translation table.
 *  - vstart
 *    1MB-aligned start of managed kernel virtual memory.
 *  - vend
 *    1MB-aligned end of managed kernel virtual memory.
 *
 * We use the first parameter to build the metadata (struct l1_ttable and
 * struct l2_dtable) necessary to track kernel mappings.
 */
#define	PMAP_STATIC_L2_SIZE 16
void
pmap_bootstrap(pd_entry_t *kernel_l1pt, vaddr_t vstart, vaddr_t vend)
{
	static struct l1_ttable static_l1;
	static struct l2_dtable static_l2[PMAP_STATIC_L2_SIZE];
	struct l1_ttable *l1 = &static_l1;
	struct l2_dtable *l2;
	struct l2_bucket *l2b;
	pmap_t pm = pmap_kernel();
	pd_entry_t pde;
	pt_entry_t *ptep;
	paddr_t pa;
	vaddr_t va;
	vsize_t size;
	int l1idx, l2idx, l2next = 0;

	/*
	 * Initialise the kernel pmap object
	 */
	pm->pm_l1 = l1;
	pm->pm_domain = PMAP_DOMAIN_KERNEL;
	pm->pm_refs = 1;

	/*
	 * Scan the L1 translation table created by initarm() and create
	 * the required metadata for all valid mappings found in it.
	 */
	for (l1idx = 0; l1idx < (L1_TABLE_SIZE / sizeof(pd_entry_t)); l1idx++) {
		pde = kernel_l1pt[l1idx];

		/*
		 * We're only interested in Coarse mappings.
		 * pmap_extract() can deal with section mappings without
		 * recourse to checking L2 metadata.
		 */
		if ((pde & L1_TYPE_MASK) != L1_TYPE_C)
			continue;

		/*
		 * Lookup the KVA of this L2 descriptor table
		 */
		pa = (paddr_t)(pde & L1_C_ADDR_MASK);
		ptep = (pt_entry_t *)kernel_pt_lookup(pa);
		if (ptep == NULL) {
			panic("pmap_bootstrap: No L2 for va 0x%x, pa 0x%lx",
			    (u_int)l1idx << L1_S_SHIFT, pa);
		}

		/*
		 * Fetch the associated L2 metadata structure.
		 * Allocate a new one if necessary.
		 */
		if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
			if (l2next == PMAP_STATIC_L2_SIZE)
				panic("pmap_bootstrap: out of static L2s");
			pm->pm_l2[L2_IDX(l1idx)] = l2 = &static_l2[l2next++];
		}

		/*
		 * One more L1 slot tracked...
		 */
		l2->l2_occupancy++;

		/*
		 * Fill in the details of the L2 descriptor in the
		 * appropriate bucket.
		 */
		l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
		l2b->l2b_kva = ptep;
		l2b->l2b_phys = pa;
		l2b->l2b_l1idx = l1idx;

		/*
		 * Establish an initial occupancy count for this descriptor
		 */
		for (l2idx = 0;
		    l2idx < (L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
		    l2idx++) {
			if ((ptep[l2idx] & L2_TYPE_MASK) != L2_TYPE_INV)
				l2b->l2b_occupancy++;
		}

		/*
		 * Make sure the descriptor itself has the correct cache mode.
		 * If not, fix it, but whine about the problem. Port-meisters
		 * should consider this a clue to fix up their initarm()
		 * function. :)
		 */
		if (pmap_set_pt_cache_mode(kernel_l1pt, (vaddr_t)ptep)) {
			printf("pmap_bootstrap: WARNING! wrong cache mode for "
			    "L2 pte @ %p\n", ptep);
		}
	}

	/*
	 * Ensure the primary (kernel) L1 has the correct cache mode for
	 * a page table. Bitch if it is not correctly set.
	 */
	for (va = (vaddr_t)kernel_l1pt;
	    va < ((vaddr_t)kernel_l1pt + L1_TABLE_SIZE); va += PAGE_SIZE) {
		if (pmap_set_pt_cache_mode(kernel_l1pt, va))
			printf("pmap_bootstrap: WARNING! wrong cache mode for "
			    "primary L1 @ 0x%lx\n", va);
	}

	cpu_idcache_wbinv_all();
	cpu_sdcache_wbinv_all();
	cpu_tlb_flushID();
	cpu_cpwait();

	/*
	 * now we allocate the "special" VAs which are used for tmp mappings
	 * by the pmap (and other modules).  we allocate the VAs by advancing
	 * virtual_avail (note that there are no pages mapped at these VAs).
	 *
	 * Managed KVM space start from wherever initarm() tells us.
	 */
	virtual_avail = vstart;
	virtual_end = vend;

	pmap_alloc_specials(&virtual_avail, 1, &csrcp, &csrc_pte);
	pmap_set_pt_cache_mode(kernel_l1pt, (vaddr_t)csrc_pte);
	pmap_alloc_specials(&virtual_avail, 1, &cdstp, &cdst_pte);
	pmap_set_pt_cache_mode(kernel_l1pt, (vaddr_t)cdst_pte);
	pmap_alloc_specials(&virtual_avail, 1, &cwbp, &cwb_pte);
	pmap_set_pt_cache_mode(kernel_l1pt, (vaddr_t)cwb_pte);
	pmap_alloc_specials(&virtual_avail, 1, (void *)&memhook, NULL);
	pmap_alloc_specials(&virtual_avail, round_page(MSGBUFSIZE) / PAGE_SIZE,
	    (void *)&msgbufaddr, NULL);

	/*
	 * Allocate a range of kernel virtual address space to be used
	 * for L2 descriptor tables and metadata allocation in
	 * pmap_growkernel().
	 */
	size = ((virtual_end - pmap_curmaxkvaddr) + L1_S_OFFSET) / L1_S_SIZE;
	pmap_alloc_specials(&virtual_avail,
	    round_page(size * L2_TABLE_SIZE_REAL) / PAGE_SIZE,
	    &pmap_kernel_l2ptp_kva, NULL);

	size = (size + (L2_BUCKET_SIZE - 1)) / L2_BUCKET_SIZE;
	pmap_alloc_specials(&virtual_avail,
	    round_page(size * sizeof(struct l2_dtable)) / PAGE_SIZE,
	    &pmap_kernel_l2dtable_kva, NULL);

	/*
	 * We can now initialise the first L1's metadata.
	 */
	TAILQ_INIT(&l1_list);
	pmap_init_l1(l1, kernel_l1pt);

	/*
	 * Initialize the pmap pool.
	 */
	pool_init(&pmap_pmap_pool, sizeof(struct pmap), 0, 0, 0,
	    "pmappl", &pool_allocator_single);
	pool_setipl(&pmap_pmap_pool, IPL_NONE);

	/*
	 * Initialize the pv pool.
	 */
	pool_init(&pmap_pv_pool, sizeof(struct pv_entry), 0, 0, 0, "pvepl",
	    &pmap_bootstrap_pv_allocator);
	pool_setipl(&pmap_pv_pool, IPL_VM);

	/*
	 * Initialize the L2 dtable pool.
	 */
	pool_init(&pmap_l2dtable_pool, sizeof(struct l2_dtable), 0, 0, 0,
	    "l2dtblpl", NULL);
	pool_setipl(&pmap_l2dtable_pool, IPL_VM);

	/*
	 * Initialise the L2 descriptor table pool.
	 */
	pool_init(&pmap_l2ptp_pool, L2_TABLE_SIZE_REAL, L2_TABLE_SIZE_REAL, 0,
	    0, "l2ptppl", &pool_allocator_single);
	pool_setipl(&pmap_l2ptp_pool, IPL_VM);

	cpu_dcache_wbinv_all();
	cpu_sdcache_wbinv_all();
}

int
pmap_set_pt_cache_mode(pd_entry_t *kl1, vaddr_t va)
{
	pd_entry_t *pdep, pde;
	pt_entry_t *ptep, pte;
	vaddr_t pa;
	int rv = 0;

	/*
	 * Make sure the descriptor itself has the correct cache mode
	 */
	pdep = &kl1[L1_IDX(va)];
	pde = *pdep;

	if (l1pte_section_p(pde)) {
		if ((pde & L1_S_CACHE_MASK) != pte_l1_s_cache_mode_pt) {
			*pdep = (pde & ~L1_S_CACHE_MASK) |
			    pte_l1_s_cache_mode_pt;
			PTE_SYNC(pdep);
			cpu_tlb_flushD_SE(va);
			rv = 1;
		}
	} else {
		pa = (paddr_t)(pde & L1_C_ADDR_MASK);
		ptep = (pt_entry_t *)kernel_pt_lookup(pa);
		if (ptep == NULL)
			panic("pmap_bootstrap: No L2 for L2 @ va %p", ptep);

		ptep = &ptep[l2pte_index(va)];
		pte = *ptep;
		if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
			*ptep = (pte & ~L2_S_CACHE_MASK) |
			    pte_l2_s_cache_mode_pt;
			PTE_SYNC(ptep);
			cpu_tlb_flushD_SE(va);
			rv = 1;
		}
	}

	return (rv);
}

void
pmap_alloc_specials(vaddr_t *availp, int pages, vaddr_t *vap, pt_entry_t **ptep)
{
	vaddr_t va = *availp;
	struct l2_bucket *l2b;

	if (ptep) {
		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
		if (l2b == NULL)
			panic("pmap_alloc_specials: no l2b for 0x%lx", va);

		if (ptep)
			*ptep = &l2b->l2b_kva[l2pte_index(va)];
	}

	*vap = va;
	*availp = va + (PAGE_SIZE * pages);
}

void
pmap_init(void)
{
	pool_setlowat(&pmap_pv_pool, (PAGE_SIZE / sizeof(struct pv_entry)) * 2);

	pmap_initialized = TRUE;
}

static vaddr_t last_bootstrap_page = 0;
static void *free_bootstrap_pages = NULL;

void *
pmap_bootstrap_pv_page_alloc(struct pool *pp, int flags, int *slowdown)
{
	extern void *pool_page_alloc(struct pool *, int, int *);
	vaddr_t new_page;
	void *rv;

	if (pmap_initialized)
		return (pool_page_alloc(pp, flags, slowdown));
	*slowdown = 0;

	if (free_bootstrap_pages) {
		rv = free_bootstrap_pages;
		free_bootstrap_pages = *((void **)rv);
		return (rv);
	}

	new_page = uvm_km_kmemalloc(kernel_map, NULL, PAGE_SIZE,
	    (flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT);

	last_bootstrap_page = new_page;
	return ((void *)new_page);
}

void
pmap_bootstrap_pv_page_free(struct pool *pp, void *v)
{
	extern void pool_page_free(struct pool *, void *);

	if (pmap_initialized) {
		pool_page_free(pp, v);
		return;
	}

	if ((vaddr_t)v < last_bootstrap_page) {
		*((void **)v) = free_bootstrap_pages;
		free_bootstrap_pages = v;
		return;
	}
}

/*
 * pmap_postinit()
 *
 * This routine is called after the vm and kmem subsystems have been
 * initialised. This allows the pmap code to perform any initialisation
 * that can only be done once the memory allocation is in place.
 */
void
pmap_postinit(void)
{
	pool_setlowat(&pmap_l2ptp_pool,
	    (PAGE_SIZE / L2_TABLE_SIZE_REAL) * 4);
	pool_setlowat(&pmap_l2dtable_pool,
	    (PAGE_SIZE / sizeof(struct l2_dtable)) * 2);
}

/*
 * Note that the following routines are used by board-specific initialisation
 * code to configure the initial kernel page tables.
 *
 * If ARM32_NEW_VM_LAYOUT is *not* defined, they operate on the assumption that
 * L2 page-table pages are 4KB in size and use 4 L1 slots. This mimics the
 * behaviour of the old pmap, and provides an easy migration path for
 * initial bring-up of the new pmap on existing ports. Fortunately,
 * pmap_bootstrap() compensates for this hackery. This is only a stop-gap and
 * will be deprecated.
 *
 * If ARM32_NEW_VM_LAYOUT *is* defined, these functions deal with 1KB L2 page
 * tables.
 */

/*
 * This list exists for the benefit of pmap_map_chunk().  It keeps track
 * of the kernel L2 tables during bootstrap, so that pmap_map_chunk() can
 * find them as necessary.
 *
 * Note that the data on this list MUST remain valid after initarm() returns,
 * as pmap_bootstrap() uses it to contruct L2 table metadata.
 */
SLIST_HEAD(, pv_addr) kernel_pt_list = SLIST_HEAD_INITIALIZER(kernel_pt_list);

vaddr_t
kernel_pt_lookup(paddr_t pa)
{
	pv_addr_t *pv;

	SLIST_FOREACH(pv, &kernel_pt_list, pv_list) {
#ifndef ARM32_NEW_VM_LAYOUT
		if (pv->pv_pa == (pa & ~PGOFSET))
			return (pv->pv_va | (pa & PGOFSET));
#else
		if (pv->pv_pa == pa)
			return (pv->pv_va);
#endif
	}
	return (0);
}

/*
 * pmap_map_section:
 *
 *	Create a single section mapping.
 */
void
pmap_map_section(vaddr_t l1pt, vaddr_t va, paddr_t pa, int prot, int cache)
{
	pd_entry_t *pde = (pd_entry_t *) l1pt;
	pd_entry_t fl;

	switch (cache) {
	case PTE_NOCACHE:
	default:
		fl = 0;
		break;

	case PTE_CACHE:
		fl = pte_l1_s_cache_mode;
		break;

	case PTE_PAGETABLE:
		fl = pte_l1_s_cache_mode_pt;
		break;
	}

	pde[va >> L1_S_SHIFT] = L1_S_PROTO | pa |
	    L1_S_PROT(PTE_KERNEL, prot) | fl | L1_S_DOM(PMAP_DOMAIN_KERNEL);
	PTE_SYNC(&pde[va >> L1_S_SHIFT]);
}

/*
 * pmap_map_entry:
 *
 *	Create a single page mapping.
 */
void
pmap_map_entry(vaddr_t l1pt, vaddr_t va, paddr_t pa, int prot, int cache)
{
	pd_entry_t *pde = (pd_entry_t *) l1pt;
	pt_entry_t fl;
	pt_entry_t *pte;

	switch (cache) {
	case PTE_NOCACHE:
	default:
		fl = 0;
		break;

	case PTE_CACHE:
		fl = pte_l2_s_cache_mode;
		break;

	case PTE_PAGETABLE:
		fl = pte_l2_s_cache_mode_pt;
		break;
	}

	if ((pde[va >> L1_S_SHIFT] & L1_TYPE_MASK) != L1_TYPE_C)
		panic("pmap_map_entry: no L2 table for VA 0x%08lx", va);

#ifndef ARM32_NEW_VM_LAYOUT
	pte = (pt_entry_t *)
	    kernel_pt_lookup(pde[va >> L1_S_SHIFT] & L2_S_FRAME);
#else
	pte = (pt_entry_t *) kernel_pt_lookup(pde[L1_IDX(va)] & L1_C_ADDR_MASK);
#endif
	if (pte == NULL)
		panic("pmap_map_entry: can't find L2 table for VA 0x%08lx", va);

#ifndef ARM32_NEW_VM_LAYOUT
	pte[(va >> PGSHIFT) & 0x3ff] =
	    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | fl;
	PTE_SYNC(&pte[(va >> PGSHIFT) & 0x3ff]);
#else
	pte[l2pte_index(va)] =
	    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | fl;
	PTE_SYNC(&pte[l2pte_index(va)]);
#endif
}

/*
 * pmap_link_l2pt:
 *
 *	Link the L2 page table specified by "l2pv" into the L1
 *	page table at the slot for "va".
 */
void
pmap_link_l2pt(vaddr_t l1pt, vaddr_t va, pv_addr_t *l2pv)
{
	pd_entry_t *pde = (pd_entry_t *) l1pt, proto;
	u_int slot = va >> L1_S_SHIFT;

	proto = L1_S_DOM(PMAP_DOMAIN_KERNEL) | L1_C_PROTO;

	pde[slot + 0] = proto | (l2pv->pv_pa + 0x000);
#ifdef ARM32_NEW_VM_LAYOUT
	PTE_SYNC(&pde[slot]);
#else
	pde[slot + 1] = proto | (l2pv->pv_pa + 0x400);
	pde[slot + 2] = proto | (l2pv->pv_pa + 0x800);
	pde[slot + 3] = proto | (l2pv->pv_pa + 0xc00);
	PTE_SYNC_RANGE(&pde[slot + 0], 4);
#endif

	SLIST_INSERT_HEAD(&kernel_pt_list, l2pv, pv_list);
}

/*
 * pmap_map_chunk:
 *
 *	Map a chunk of memory using the most efficient mappings
 *	possible (section, large page, small page) into the
 *	provided L1 and L2 tables at the specified virtual address.
 */
vsize_t
pmap_map_chunk(vaddr_t l1pt, vaddr_t va, paddr_t pa, vsize_t size,
    int prot, int cache)
{
	pd_entry_t *pde = (pd_entry_t *) l1pt;
	pt_entry_t *pte, f1, f2s, f2l;
	vsize_t resid;  
	int i;

	resid = (size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);

	if (l1pt == 0)
		panic("pmap_map_chunk: no L1 table provided");

#ifdef VERBOSE_INIT_ARM     
	printf("pmap_map_chunk: pa=0x%lx va=0x%lx size=0x%lx resid=0x%lx "
	    "prot=0x%x cache=%d\n", pa, va, size, resid, prot, cache);
#endif

	switch (cache) {
	case PTE_NOCACHE:
	default:
		f1 = 0;
		f2l = 0;
		f2s = 0;
		break;

	case PTE_CACHE:
		f1 = pte_l1_s_cache_mode;
		f2l = pte_l2_l_cache_mode;
		f2s = pte_l2_s_cache_mode;
		break;

	case PTE_PAGETABLE:
		f1 = pte_l1_s_cache_mode_pt;
		f2l = pte_l2_l_cache_mode_pt;
		f2s = pte_l2_s_cache_mode_pt;
		break;
	}

	size = resid;

	while (resid > 0) {
		/* See if we can use a section mapping. */
		if (L1_S_MAPPABLE_P(va, pa, resid)) {
#ifdef VERBOSE_INIT_ARM
			printf("S");
#endif
			pde[va >> L1_S_SHIFT] = L1_S_PROTO | pa |
			    L1_S_PROT(PTE_KERNEL, prot) | f1 |
			    L1_S_DOM(PMAP_DOMAIN_KERNEL);
			PTE_SYNC(&pde[va >> L1_S_SHIFT]);
			va += L1_S_SIZE;
			pa += L1_S_SIZE;
			resid -= L1_S_SIZE;
			continue;
		}

		/*
		 * Ok, we're going to use an L2 table.  Make sure
		 * one is actually in the corresponding L1 slot
		 * for the current VA.
		 */
		if ((pde[va >> L1_S_SHIFT] & L1_TYPE_MASK) != L1_TYPE_C)
			panic("pmap_map_chunk: no L2 table for VA 0x%08lx", va);

#ifndef ARM32_NEW_VM_LAYOUT
		pte = (pt_entry_t *)
		    kernel_pt_lookup(pde[va >> L1_S_SHIFT] & L2_S_FRAME);
#else
		pte = (pt_entry_t *) kernel_pt_lookup(
		    pde[L1_IDX(va)] & L1_C_ADDR_MASK);
#endif
		if (pte == NULL)
			panic("pmap_map_chunk: can't find L2 table for VA"
			    "0x%08lx", va);

		/* See if we can use a L2 large page mapping. */
		if (L2_L_MAPPABLE_P(va, pa, resid)) {
#ifdef VERBOSE_INIT_ARM
			printf("L");
#endif
			for (i = 0; i < 16; i++) {
#ifndef ARM32_NEW_VM_LAYOUT
				pte[((va >> PGSHIFT) & 0x3f0) + i] =
				    L2_L_PROTO | pa |
				    L2_L_PROT(PTE_KERNEL, prot) | f2l;
				PTE_SYNC(&pte[((va >> PGSHIFT) & 0x3f0) + i]);
#else
				pte[l2pte_index(va) + i] =
				    L2_L_PROTO | pa |
				    L2_L_PROT(PTE_KERNEL, prot) | f2l;
				PTE_SYNC(&pte[l2pte_index(va) + i]);
#endif
			}
			va += L2_L_SIZE;
			pa += L2_L_SIZE;
			resid -= L2_L_SIZE;
			continue;
		}

		/* Use a small page mapping. */
#ifdef VERBOSE_INIT_ARM
		printf("P");
#endif
#ifndef ARM32_NEW_VM_LAYOUT
		pte[(va >> PGSHIFT) & 0x3ff] =
		    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | f2s;
		PTE_SYNC(&pte[(va >> PGSHIFT) & 0x3ff]);
#else
		pte[l2pte_index(va)] =
		    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | f2s;
		PTE_SYNC(&pte[l2pte_index(va)]);
#endif
		va += PAGE_SIZE;
		pa += PAGE_SIZE;
		resid -= PAGE_SIZE;
	}
#ifdef VERBOSE_INIT_ARM
	printf("\n");
#endif
	return (size);
}

/********************** Static device map routines ***************************/

const struct pmap_devmap *pmap_devmap_table;

/*
 * Register the devmap table.  This is provided in case early console
 * initialization needs to register mappings created by bootstrap code
 * before pmap_devmap_bootstrap() is called.
 */
void
pmap_devmap_register(const struct pmap_devmap *table)
{

	pmap_devmap_table = table;
}

/*
 * Map all of the static regions in the devmap table, and remember
 * the devmap table so other parts of the kernel can look up entries
 * later.
 */
void
pmap_devmap_bootstrap(vaddr_t l1pt, const struct pmap_devmap *table)
{
	int i;

	pmap_devmap_table = table;

	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
#ifdef VERBOSE_INIT_ARM
		printf("devmap: %08lx -> %08lx @ %08lx\n",
		    pmap_devmap_table[i].pd_pa,
		    pmap_devmap_table[i].pd_pa +
			pmap_devmap_table[i].pd_size - 1,
		    pmap_devmap_table[i].pd_va);
#endif
		pmap_map_chunk(l1pt, pmap_devmap_table[i].pd_va,
		    pmap_devmap_table[i].pd_pa,
		    pmap_devmap_table[i].pd_size,
		    pmap_devmap_table[i].pd_prot,
		    pmap_devmap_table[i].pd_cache);
	}
}

const struct pmap_devmap *
pmap_devmap_find_pa(paddr_t pa, psize_t size)
{
	int i;

	if (pmap_devmap_table == NULL)
		return (NULL);

	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
		if (pa >= pmap_devmap_table[i].pd_pa &&
		    pa + size <= pmap_devmap_table[i].pd_pa +
				 pmap_devmap_table[i].pd_size)
			return (&pmap_devmap_table[i]);
	}

	return (NULL);
}

const struct pmap_devmap *
pmap_devmap_find_va(vaddr_t va, vsize_t size)
{
	int i;

	if (pmap_devmap_table == NULL)
		return (NULL);

	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
		if (va >= pmap_devmap_table[i].pd_va &&
		    va + size <= pmap_devmap_table[i].pd_va +
				 pmap_devmap_table[i].pd_size)
			return (&pmap_devmap_table[i]);
	}

	return (NULL);
}

/********************** PTE initialization routines **************************/

/*
 * These routines are called when the CPU type is identified to set up
 * the PTE prototypes, cache modes, etc.
 *
 * The variables are always here, just in case LKMs need to reference
 * them (though, they shouldn't).
 */

pt_entry_t	pte_l1_s_cache_mode;
pt_entry_t	pte_l1_s_cache_mode_pt;
pt_entry_t	pte_l1_s_cache_mask;

pt_entry_t	pte_l2_l_cache_mode;
pt_entry_t	pte_l2_l_cache_mode_pt;
pt_entry_t	pte_l2_l_cache_mask;

pt_entry_t	pte_l2_s_cache_mode;
pt_entry_t	pte_l2_s_cache_mode_pt;
pt_entry_t	pte_l2_s_cache_mask;

pt_entry_t	pte_l1_s_coherent;
pt_entry_t	pte_l2_l_coherent;
pt_entry_t	pte_l2_s_coherent;

pt_entry_t	pte_l1_s_prot_ur;
pt_entry_t	pte_l1_s_prot_uw;
pt_entry_t	pte_l1_s_prot_kr;
pt_entry_t	pte_l1_s_prot_kw;
pt_entry_t	pte_l1_s_prot_mask;

pt_entry_t	pte_l2_l_prot_ur;
pt_entry_t	pte_l2_l_prot_uw;
pt_entry_t	pte_l2_l_prot_kr;
pt_entry_t	pte_l2_l_prot_kw;
pt_entry_t	pte_l2_l_prot_mask;

pt_entry_t	pte_l2_s_prot_ur;
pt_entry_t	pte_l2_s_prot_uw;
pt_entry_t	pte_l2_s_prot_kr;
pt_entry_t	pte_l2_s_prot_kw;
pt_entry_t	pte_l2_s_prot_mask;

pt_entry_t	pte_l1_s_proto;
pt_entry_t	pte_l1_c_proto;
pt_entry_t	pte_l2_s_proto;

void		(*pmap_copy_page_func)(struct vm_page *, struct vm_page *);
void		(*pmap_zero_page_func)(struct vm_page *);

void
pmap_pte_init_generic(void)
{

	pte_l1_s_cache_mode = L1_S_B|L1_S_C;
	pte_l1_s_cache_mask = L1_S_CACHE_MASK_generic;

	pte_l2_l_cache_mode = L2_B|L2_C;
	pte_l2_l_cache_mask = L2_L_CACHE_MASK_generic;

	pte_l2_s_cache_mode = L2_B|L2_C;
	pte_l2_s_cache_mask = L2_S_CACHE_MASK_generic;

	/*
	 * If we have a write-through cache, set B and C.  If
	 * we have a write-back cache, then we assume setting
	 * only C will make those pages write-through.
	 */
	if (cpufuncs.cf_dcache_wb_range == (void *) cpufunc_nullop) {
		pte_l1_s_cache_mode_pt = L1_S_B|L1_S_C;
		pte_l2_l_cache_mode_pt = L2_B|L2_C;
		pte_l2_s_cache_mode_pt = L2_B|L2_C;
	} else {
		pte_l1_s_cache_mode_pt = L1_S_C;
		pte_l2_l_cache_mode_pt = L2_C;
		pte_l2_s_cache_mode_pt = L2_C;
	}

	pte_l1_s_coherent = L1_S_COHERENT_generic;
	pte_l2_l_coherent = L2_L_COHERENT_generic;
	pte_l2_s_coherent = L2_S_COHERENT_generic;

	pte_l1_s_prot_ur = L1_S_PROT_UR_generic;
	pte_l1_s_prot_uw = L1_S_PROT_UW_generic;
	pte_l1_s_prot_kr = L1_S_PROT_KR_generic;
	pte_l1_s_prot_kw = L1_S_PROT_KW_generic;
	pte_l1_s_prot_mask = L1_S_PROT_MASK_generic;

	pte_l2_l_prot_ur = L2_L_PROT_UR_generic;
	pte_l2_l_prot_uw = L2_L_PROT_UW_generic;
	pte_l2_l_prot_kr = L2_L_PROT_KR_generic;
	pte_l2_l_prot_kw = L2_L_PROT_KW_generic;
	pte_l2_l_prot_mask = L2_L_PROT_MASK_generic;

	pte_l2_s_prot_ur = L2_S_PROT_UR_generic;
	pte_l2_s_prot_uw = L2_S_PROT_UW_generic;
	pte_l2_s_prot_kr = L2_S_PROT_KR_generic;
	pte_l2_s_prot_kw = L2_S_PROT_KW_generic;
	pte_l2_s_prot_mask = L2_S_PROT_MASK_generic;

	pte_l1_s_proto = L1_S_PROTO_generic;
	pte_l1_c_proto = L1_C_PROTO_generic;
	pte_l2_s_proto = L2_S_PROTO_generic;

	pmap_copy_page_func = pmap_copy_page_generic;
	pmap_zero_page_func = pmap_zero_page_generic;
}

void
pmap_pte_init_armv7(void)
{
	uint32_t cachereg;

	/*
	 * XXX 
	 * ARMv7 is compatible with generic, but we want to use proper TEX
	 * settings eventually
	 */
	pmap_pte_init_generic();

	/* write-allocate should be tested */
	pte_l1_s_cache_mode = L1_S_C|L1_S_B;
	pte_l2_l_cache_mode = L2_C|L2_B;
	pte_l2_s_cache_mode = L2_C|L2_B;

	pte_l1_s_cache_mode_pt = L1_S_C;
	pte_l2_l_cache_mode_pt = L2_C;
	pte_l2_s_cache_mode_pt = L2_C;

	pte_l1_s_cache_mask = L1_S_CACHE_MASK_v7;
	pte_l2_l_cache_mask = L2_L_CACHE_MASK_v7;
	pte_l2_s_cache_mask = L2_S_CACHE_MASK_v7;

	pte_l1_s_coherent = L1_S_COHERENT_v7;
	pte_l2_l_coherent = L2_L_COHERENT_v7;
	pte_l2_s_coherent = L2_S_COHERENT_v7;

	pte_l1_s_prot_ur = L1_S_PROT_UR_v7;
	pte_l1_s_prot_uw = L1_S_PROT_UW_v7;
	pte_l1_s_prot_kr = L1_S_PROT_KR_v7;
	pte_l1_s_prot_kw = L1_S_PROT_KW_v7;
	pte_l1_s_prot_mask = L1_S_PROT_MASK_v7;

	pte_l2_l_prot_ur = L2_L_PROT_UR_v7;
	pte_l2_l_prot_uw = L2_L_PROT_UW_v7;
	pte_l2_l_prot_kr = L2_L_PROT_KR_v7;
	pte_l2_l_prot_kw = L2_L_PROT_KW_v7;
	pte_l2_l_prot_mask = L2_L_PROT_MASK_v7;

	pte_l2_s_prot_ur = L2_S_PROT_UR_v7;
	pte_l2_s_prot_uw = L2_S_PROT_UW_v7;
	pte_l2_s_prot_kr = L2_S_PROT_KR_v7;
	pte_l2_s_prot_kw = L2_S_PROT_KW_v7;
	pte_l2_s_prot_mask = L2_S_PROT_MASK_v7;

	pte_l1_s_proto = L1_S_PROTO_v7;
	pte_l1_c_proto = L1_C_PROTO_v7;
	pte_l2_s_proto = L2_S_PROTO_v7;

	/* probe L1 dcache */
	__asm volatile("mcr p15, 2, %0, c0, c0, 0" :: "r" (0) );
	__asm volatile("mrc p15, 1, %0, c0, c0, 0" : "=r" (cachereg) );
	if ((cachereg & 0x80000000) == 0) {
#if 0
		/*
		 * pmap_pte_init_generic() has defaulted to write-through
		 * settings for pte pages, but the cache does not support
		 * write-through.
		 */
		pmap_needs_pte_sync = 1;
		pte_l1_s_cache_mode_pt = L1_S_B|L1_S_C;
		pte_l2_l_cache_mode_pt = L2_B|L2_C;
		pte_l2_s_cache_mode_pt = L2_B|L2_C;
#endif
		/* XXX: Don't cache PTEs, until write-back is fixed. */
		pte_l1_s_cache_mode_pt = L1_S_V7_TEX(1);
		pte_l2_l_cache_mode_pt = L2_V7_L_TEX(1);
		pte_l2_s_cache_mode_pt = L2_V7_S_TEX(1);
	}
}

uint32_t pmap_alias_dist;
uint32_t pmap_alias_bits;

vaddr_t
pmap_prefer(vaddr_t foff, vaddr_t va)
{
	long d, m;

	m = pmap_alias_dist;
	if (m == 0)             /* m=0 => no cache aliasing */
		return va;

	d = foff - va;
	d &= (m - 1);
	return va + d;
}