summaryrefslogtreecommitdiff
path: root/usr/src/uts/intel/io/agpgart/agpgart.c
blob: 7df05184e390b0931edc3abc1ae83788d18f1373 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
/*
 * Copyright (c) 2009, Intel Corporation.
 * All Rights Reserved.
 */

/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */
/*
 * Portions Philip Brown phil@bolthole.com Dec 2001
 */


/*
 * agpgart driver
 *
 * This driver is primary targeted at providing memory support for INTEL
 * AGP device, INTEL memory less video card, and AMD64 cpu GART devices.
 * So there are four main architectures, ARC_IGD810, ARC_IGD830, ARC_INTELAGP,
 * ARC_AMD64AGP to agpgart driver. However, the memory
 * interfaces are the same for these architectures. The difference is how to
 * manage the hardware GART table for them.
 *
 * For large memory allocation, this driver use direct mapping to userland
 * application interface to save kernel virtual memory .
 */

#include <sys/types.h>
#include <sys/pci.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/file.h>
#include <sys/kstat.h>
#include <sys/stat.h>
#include <sys/modctl.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>
#include <sys/sunldi.h>
#include <sys/policy.h>
#include <sys/ddidevmap.h>
#include <vm/seg_dev.h>
#include <sys/pmem.h>
#include <sys/agpgart.h>
#include <sys/agp/agpdefs.h>
#include <sys/agp/agpgart_impl.h>
#include <sys/agp/agpamd64gart_io.h>
#include <sys/agp/agpmaster_io.h>
#include <sys/agp/agptarget_io.h>

/* Dynamic debug support */
int agp_debug_var = 0;
#define	AGPDB_PRINT1(fmt)	if (agp_debug_var == 1) cmn_err fmt
#define	AGPDB_PRINT2(fmt)	if (agp_debug_var >= 1) cmn_err fmt

/* Driver global softstate handle */
static void *agpgart_glob_soft_handle;

#define	MAX_INSTNUM			16

#define	AGP_DEV2INST(devt)	(getminor((devt)) >> 4)
#define	AGP_INST2MINOR(instance)	((instance) << 4)
#define	IS_INTEL_830(type)	((type) == ARC_IGD830)
#define	IS_TRUE_AGP(type)	(((type) == ARC_INTELAGP) || \
	((type) == ARC_AMD64AGP))

#define	AGP_HASH_NODE	1024

static void
list_head_init(struct list_head  *head) {
	struct	list_head	*entry,	*tmp;
	/* HASH for accelerate */
	entry = kmem_zalloc(AGP_HASH_NODE *
		sizeof (struct list_head), KM_SLEEP);
	head->next = entry;
	for (int i = 0; i < AGP_HASH_NODE; i++) {
	tmp = &entry[i];
	tmp->next = tmp;
	tmp->prev = tmp;
	tmp->gttseg = NULL;
	}
}

static void
list_head_add_new(struct list_head	*head,
		igd_gtt_seg_t	*gttseg)
{
	struct list_head  *entry, *tmp;
	int key;
	entry = kmem_zalloc(sizeof (*entry), KM_SLEEP);
	key = gttseg->igs_pgstart % AGP_HASH_NODE;
	tmp = &head->next[key];
	tmp->next->prev = entry;
	entry->next = tmp->next;
	entry->prev = tmp;
	tmp->next = entry;
	entry->gttseg = gttseg;
}

static void
list_head_del(struct list_head	*entry) {
	(entry)->next->prev = (entry)->prev;      \
	(entry)->prev->next = (entry)->next;      \
	(entry)->gttseg = NULL; \
}

#define	list_head_for_each_safe(entry,	temp,	head)	\
	for (int key = 0; key < AGP_HASH_NODE; key++)	\
	for (entry = (&(head)->next[key])->next, temp = (entry)->next;	\
		entry != &(head)->next[key];	\
		entry = temp, temp = temp->next)


#define	agpinfo_default_to_32(v, v32)	\
	{	\
		(v32).agpi32_version = (v).agpi_version;	\
		(v32).agpi32_devid = (v).agpi_devid;	\
		(v32).agpi32_mode = (v).agpi_mode;	\
		(v32).agpi32_aperbase = (uint32_t)(v).agpi_aperbase;	\
		(v32).agpi32_apersize = (uint32_t)(v).agpi_apersize;	\
		(v32).agpi32_pgtotal = (v).agpi_pgtotal;	\
		(v32).agpi32_pgsystem = (v).agpi_pgsystem;	\
		(v32).agpi32_pgused = (v).agpi_pgused;	\
	}

static ddi_dma_attr_t agpgart_dma_attr = {
	DMA_ATTR_V0,
	0U,				/* dma_attr_addr_lo */
	0xffffffffU,			/* dma_attr_addr_hi */
	0xffffffffU,			/* dma_attr_count_max */
	(uint64_t)AGP_PAGE_SIZE,	/* dma_attr_align */
	1,				/* dma_attr_burstsizes */
	1,				/* dma_attr_minxfer */
	0xffffffffU,			/* dma_attr_maxxfer */
	0xffffffffU,			/* dma_attr_seg */
	1,				/* dma_attr_sgllen, variable */
	4,				/* dma_attr_granular */
	0				/* dma_attr_flags */
};

/*
 * AMD64 supports gart table above 4G. See alloc_gart_table.
 */
static ddi_dma_attr_t garttable_dma_attr = {
	DMA_ATTR_V0,
	0U,				/* dma_attr_addr_lo */
	0xffffffffU,			/* dma_attr_addr_hi */
	0xffffffffU,			/* dma_attr_count_max */
	(uint64_t)AGP_PAGE_SIZE,	/* dma_attr_align */
	1,				/* dma_attr_burstsizes */
	1,				/* dma_attr_minxfer */
	0xffffffffU,			/* dma_attr_maxxfer */
	0xffffffffU,			/* dma_attr_seg */
	1,				/* dma_attr_sgllen, variable */
	4,				/* dma_attr_granular */
	0				/* dma_attr_flags */
};

/*
 * AGPGART table need a physical contiguous memory. To assure that
 * each access to gart table is strongly ordered and uncachable,
 * we use DDI_STRICTORDER_ACC.
 */
static ddi_device_acc_attr_t gart_dev_acc_attr = {
	DDI_DEVICE_ATTR_V0,
	DDI_NEVERSWAP_ACC,
	DDI_STRICTORDER_ACC	/* must be DDI_STRICTORDER_ACC */
};

/*
 * AGP memory is usually used as texture memory or for a framebuffer, so we
 * can set the memory attribute to write combining. Video drivers will
 * determine the frame buffer attributes, for example the memory is write
 * combinging or non-cachable. However, the interface between Xorg and agpgart
 * driver to support attribute selcetion doesn't exist yet. So we set agp memory
 * to non-cachable by default now. This attribute might be overridden
 * by MTTR in X86.
 */
static ddi_device_acc_attr_t mem_dev_acc_attr = {
	DDI_DEVICE_ATTR_V0,
	DDI_NEVERSWAP_ACC,
	DDI_STRICTORDER_ACC	/* Can be DDI_MERGING_OK_ACC */
};

static keytable_ent_t *
agp_find_bound_keyent(agpgart_softstate_t *softstate, uint32_t pg_offset);
static void
amd64_gart_unregister(amd64_garts_dev_t *cpu_garts);


static void
agp_devmap_unmap(devmap_cookie_t handle, void *devprivate,
    offset_t off, size_t len, devmap_cookie_t new_handle1,
    void **new_devprivate1, devmap_cookie_t new_handle2,
    void **new_devprivate2)
{

	struct keytable_ent *mementry;
	agpgart_softstate_t *softstate;
	agpgart_ctx_t *ctxp, *newctxp1, *newctxp2;

	ASSERT(AGP_ALIGNED(len) && AGP_ALIGNED(off));
	ASSERT(devprivate);
	ASSERT(handle);

	ctxp = (agpgart_ctx_t *)devprivate;
	softstate = ctxp->actx_sc;
	ASSERT(softstate);

	if (new_handle1 != NULL) {
		newctxp1 = kmem_zalloc(sizeof (agpgart_ctx_t), KM_SLEEP);
		newctxp1->actx_sc = softstate;
		newctxp1->actx_off = ctxp->actx_off;
		*new_devprivate1 = newctxp1;
	}

	if (new_handle2 != NULL) {
		newctxp2 = kmem_zalloc(sizeof (agpgart_ctx_t), KM_SLEEP);
		newctxp2->actx_sc = softstate;
		newctxp2->actx_off = off + len;
		*new_devprivate2 = newctxp2;
	}

	mutex_enter(&softstate->asoft_instmutex);
	if ((new_handle1 == NULL) && (new_handle2 == NULL)) {
		mementry =
		    agp_find_bound_keyent(softstate, AGP_BYTES2PAGES(off));
		ASSERT(mementry);
		mementry->kte_refcnt--;
	} else if ((new_handle1 != NULL) && (new_handle2 != NULL)) {
		mementry =
		    agp_find_bound_keyent(softstate, AGP_BYTES2PAGES(off));
		ASSERT(mementry);
		mementry->kte_refcnt++;
	}
	ASSERT(mementry->kte_refcnt >= 0);
	mutex_exit(&softstate->asoft_instmutex);
	kmem_free(ctxp, sizeof (struct agpgart_ctx));
}

/*ARGSUSED*/
static int
agp_devmap_map(devmap_cookie_t handle, dev_t dev,
    uint_t flags, offset_t offset, size_t len, void **new_devprivate)
{
	agpgart_softstate_t *softstate;
	int instance;
	struct keytable_ent *mementry;
	agpgart_ctx_t *newctxp;

	ASSERT(handle);
	instance = AGP_DEV2INST(dev);
	softstate = ddi_get_soft_state(agpgart_glob_soft_handle, instance);
	if (softstate == NULL) {
		AGPDB_PRINT2((CE_WARN, "agp_devmap_map: get soft state err"));
		return (ENXIO);
	}

	ASSERT(softstate);
	ASSERT(mutex_owned(&softstate->asoft_instmutex));
	ASSERT(len);
	ASSERT(AGP_ALIGNED(offset) && AGP_ALIGNED(len));

	mementry =
	    agp_find_bound_keyent(softstate, AGP_BYTES2PAGES(offset));
	ASSERT(mementry);
	mementry->kte_refcnt++;
	ASSERT(mementry->kte_refcnt >= 0);
	newctxp = kmem_zalloc(sizeof (agpgart_ctx_t), KM_SLEEP);
	newctxp->actx_off = offset;
	newctxp->actx_sc = softstate;
	*new_devprivate = newctxp;

	return (0);
}

/*ARGSUSED*/
static int agp_devmap_dup(devmap_cookie_t handle, void *devprivate,
    devmap_cookie_t new_handle, void **new_devprivate)
{
	struct keytable_ent *mementry;
	agpgart_ctx_t *newctxp, *ctxp;
	agpgart_softstate_t *softstate;

	ASSERT(devprivate);
	ASSERT(handle && new_handle);

	ctxp = (agpgart_ctx_t *)devprivate;
	ASSERT(AGP_ALIGNED(ctxp->actx_off));

	newctxp = kmem_zalloc(sizeof (agpgart_ctx_t), KM_SLEEP);
	newctxp->actx_off = ctxp->actx_off;
	newctxp->actx_sc = ctxp->actx_sc;
	softstate = (agpgart_softstate_t *)newctxp->actx_sc;

	mutex_enter(&softstate->asoft_instmutex);
	mementry = agp_find_bound_keyent(softstate,
	    AGP_BYTES2PAGES(newctxp->actx_off));
	mementry->kte_refcnt++;
	ASSERT(mementry->kte_refcnt >= 0);
	mutex_exit(&softstate->asoft_instmutex);
	*new_devprivate = newctxp;

	return (0);
}

struct devmap_callback_ctl agp_devmap_cb = {
	DEVMAP_OPS_REV,		/* rev */
	agp_devmap_map,		/* map */
	NULL,			/* access */
	agp_devmap_dup,		/* dup */
	agp_devmap_unmap,	/* unmap */
};

/*
 * agp_master_regis_byname()
 *
 * Description:
 * 	Open the AGP master device node by device path name and
 * 	register the device handle for later operations.
 * 	We check all possible driver instance from 0
 * 	to MAX_INSTNUM because the master device could be
 * 	at any instance number. Only one AGP master is supported.
 *
 * Arguments:
 * 	master_hdlp		AGP master device LDI handle pointer
 *	agpgart_l		AGPGART driver LDI identifier
 *
 * Returns:
 * 	-1			failed
 * 	0			success
 */
static int
agp_master_regis_byname(ldi_handle_t *master_hdlp, ldi_ident_t agpgart_li)
{
	int	i;
	char	buf[MAXPATHLEN];

	ASSERT(master_hdlp);
	ASSERT(agpgart_li);

	/*
	 * Search all possible instance numbers for the agp master device.
	 * Only one master device is supported now, so the search ends
	 * when one master device is found.
	 */
	for (i = 0; i < MAX_INSTNUM; i++) {
		(void) snprintf(buf, MAXPATHLEN, "%s%d", AGPMASTER_DEVLINK, i);
		if ((ldi_open_by_name(buf, 0, kcred,
		    master_hdlp, agpgart_li)))
			continue;
		AGPDB_PRINT1((CE_NOTE,
		    "master device found: instance number=%d", i));
		break;

	}

	/* AGP master device not found */
	if (i == MAX_INSTNUM)
		return (-1);

	return (0);
}

/*
 * agp_target_regis_byname()
 *
 * Description:
 * 	This function opens agp bridge device node by
 * 	device path name and registers the device handle
 * 	for later operations.
 * 	We check driver instance from 0 to MAX_INSTNUM
 * 	because the master device could be at any instance
 * 	number. Only one agp target is supported.
 *
 *
 * Arguments:
 *	target_hdlp		AGP target device LDI handle pointer
 *	agpgart_l		AGPGART driver LDI identifier
 *
 * Returns:
 * 	-1			failed
 * 	0			success
 */
static int
agp_target_regis_byname(ldi_handle_t *target_hdlp, ldi_ident_t agpgart_li)
{
	int	i;
	char	buf[MAXPATHLEN];

	ASSERT(target_hdlp);
	ASSERT(agpgart_li);

	for (i = 0; i < MAX_INSTNUM; i++) {
		(void) snprintf(buf, MAXPATHLEN, "%s%d", AGPTARGET_DEVLINK, i);
		if ((ldi_open_by_name(buf, 0, kcred,
		    target_hdlp, agpgart_li)))
			continue;

		AGPDB_PRINT1((CE_NOTE,
		    "bridge device found: instance number=%d", i));
		break;

	}

	/* AGP bridge device not found */
	if (i == MAX_INSTNUM) {
		AGPDB_PRINT2((CE_WARN, "bridge device not found"));
		return (-1);
	}

	return (0);
}

/*
 * amd64_gart_regis_byname()
 *
 * Description:
 * 	Open all amd64 gart device nodes by deice path name and
 * 	register the device handles for later operations. Each cpu
 * 	has its own amd64 gart device.
 *
 * Arguments:
 * 	cpu_garts		cpu garts device list header
 *	agpgart_l		AGPGART driver LDI identifier
 *
 * Returns:
 * 	-1			failed
 * 	0			success
 */
static int
amd64_gart_regis_byname(amd64_garts_dev_t *cpu_garts, ldi_ident_t agpgart_li)
{
	amd64_gart_dev_list_t	*gart_list;
	int			i;
	char			buf[MAXPATHLEN];
	ldi_handle_t		gart_hdl;
	int			ret;

	ASSERT(cpu_garts);
	ASSERT(agpgart_li);

	/*
	 * Search all possible instance numbers for the gart devices.
	 * There can be multiple on-cpu gart devices for Opteron server.
	 */
	for (i = 0; i < MAX_INSTNUM; i++) {
		(void) snprintf(buf, MAXPATHLEN, "%s%d", CPUGART_DEVLINK, i);
		ret = ldi_open_by_name(buf, 0, kcred,
		    &gart_hdl, agpgart_li);

		if (ret == ENODEV)
			continue;
		else if (ret != 0) { /* There was an error opening the device */
			amd64_gart_unregister(cpu_garts);
			return (ret);
		}

		AGPDB_PRINT1((CE_NOTE,
		    "amd64 gart device found: instance number=%d", i));

		gart_list = (amd64_gart_dev_list_t *)
		    kmem_zalloc(sizeof (amd64_gart_dev_list_t), KM_SLEEP);

		/* Add new item to the head of the gart device list */
		gart_list->gart_devhdl = gart_hdl;
		gart_list->next = cpu_garts->gart_dev_list_head;
		cpu_garts->gart_dev_list_head = gart_list;
		cpu_garts->gart_device_num++;
	}

	if (cpu_garts->gart_device_num == 0)
		return (ENODEV);
	return (0);
}

/*
 * Unregister agp master device handle
 */
static void
agp_master_unregister(ldi_handle_t *master_hdlp)
{
	ASSERT(master_hdlp);

	if (master_hdlp) {
		(void) ldi_close(*master_hdlp, 0, kcred);
		*master_hdlp = NULL;
	}
}

/*
 * Unregister agp bridge device handle
 */
static void
agp_target_unregister(ldi_handle_t *target_hdlp)
{
	if (target_hdlp) {
		(void) ldi_close(*target_hdlp, 0, kcred);
		*target_hdlp = NULL;
	}
}

/*
 * Unregister all amd64 gart device handles
 */
static void
amd64_gart_unregister(amd64_garts_dev_t *cpu_garts)
{
	amd64_gart_dev_list_t	*gart_list;
	amd64_gart_dev_list_t	*next;

	ASSERT(cpu_garts);

	for (gart_list = cpu_garts->gart_dev_list_head;
	    gart_list; gart_list = next) {

		ASSERT(gart_list->gart_devhdl);
		(void) ldi_close(gart_list->gart_devhdl, 0, kcred);
		next = gart_list->next;
		/* Free allocated memory */
		kmem_free(gart_list, sizeof (amd64_gart_dev_list_t));
	}
	cpu_garts->gart_dev_list_head = NULL;
	cpu_garts->gart_device_num = 0;
}

/*
 * lyr_detect_master_type()
 *
 * Description:
 * 	This function gets agp master type by querying agp master device.
 *
 * Arguments:
 * 	master_hdlp		agp master device ldi handle pointer
 *
 * Returns:
 * 	-1			unsupported device
 * 	DEVICE_IS_I810		i810 series
 * 	DEVICE_IS_I810		i830 series
 * 	DEVICE_IS_AGP		true agp master
 */
static int
lyr_detect_master_type(ldi_handle_t *master_hdlp)
{
	int vtype;
	int err;

	ASSERT(master_hdlp);

	/* ldi_ioctl(agpmaster) */
	err = ldi_ioctl(*master_hdlp, DEVICE_DETECT,
	    (intptr_t)&vtype, FKIOCTL, kcred, 0);
	if (err) /* Unsupported graphics device */
		return (-1);
	return (vtype);
}

/*
 * devtect_target_type()
 *
 * Description:
 * 	This function gets the host bridge chipset type by querying the agp
 *	target device.
 *
 * Arguments:
 * 	target_hdlp		agp target device LDI handle pointer
 *
 * Returns:
 * 	CHIP_IS_INTEL		Intel agp chipsets
 * 	CHIP_IS_AMD		AMD agp chipset
 * 	-1			unsupported chipset
 */
static int
lyr_detect_target_type(ldi_handle_t *target_hdlp)
{
	int btype;
	int err;

	ASSERT(target_hdlp);

	err = ldi_ioctl(*target_hdlp, CHIP_DETECT, (intptr_t)&btype,
	    FKIOCTL, kcred, 0);
	if (err)	/* Unsupported bridge device */
		return (-1);
	return (btype);
}

/*
 * lyr_init()
 *
 * Description:
 * 	This function detects the  graphics system architecture and
 * 	registers all relative device handles in a global structure
 * 	"agp_regdev". Then it stores the system arc type in driver
 * 	soft state.
 *
 * Arguments:
 *	agp_regdev		AGP devices registration struct pointer
 *	agpgart_l		AGPGART driver LDI identifier
 *
 * Returns:
 * 	0	System arc supported and agp devices registration successed.
 * 	-1	System arc not supported or device registration failed.
 */
int
lyr_init(agp_registered_dev_t *agp_regdev, ldi_ident_t agpgart_li)
{
	ldi_handle_t *master_hdlp;
	ldi_handle_t *target_hdlp;
	amd64_garts_dev_t *garts_dev;
	int card_type, chip_type;
	int ret;

	ASSERT(agp_regdev);

	bzero(agp_regdev, sizeof (agp_registered_dev_t));
	agp_regdev->agprd_arctype = ARC_UNKNOWN;
	/*
	 * Register agp devices, assuming all instances attached, and
	 * detect which agp architucture this server belongs to. This
	 * must be done before the agpgart driver starts to use layered
	 * driver interfaces.
	 */
	master_hdlp = &agp_regdev->agprd_masterhdl;
	target_hdlp = &agp_regdev->agprd_targethdl;
	garts_dev = &agp_regdev->agprd_cpugarts;

	/* Check whether the system is amd64 arc */
	if ((ret = amd64_gart_regis_byname(garts_dev, agpgart_li)) == ENODEV) {
		/* No amd64 gart devices */
		AGPDB_PRINT1((CE_NOTE,
		    "lyr_init: this is not an amd64 system"));
		if (agp_master_regis_byname(master_hdlp, agpgart_li)) {
			AGPDB_PRINT2((CE_WARN,
			    "lyr_init: register master device unsuccessful"));
			goto err1;
		}
		if (agp_target_regis_byname(target_hdlp, agpgart_li)) {
			AGPDB_PRINT2((CE_WARN,
			    "lyr_init: register target device unsuccessful"));
			goto err2;
		}
		card_type = lyr_detect_master_type(master_hdlp);
		/*
		 * Detect system arc by master device. If it is a intel
		 * integrated device, finish the detection successfully.
		 */
		switch (card_type) {
		case DEVICE_IS_I810:	/* I810 likewise graphics */
			AGPDB_PRINT1((CE_NOTE,
			    "lyr_init: the system is Intel 810 arch"));
			agp_regdev->agprd_arctype = ARC_IGD810;
			return (0);
		case DEVICE_IS_I830:	/* I830 likewise graphics */
			AGPDB_PRINT1((CE_NOTE,
			    "lyr_init: the system is Intel 830 arch"));
			agp_regdev->agprd_arctype = ARC_IGD830;
			return (0);
		case DEVICE_IS_AGP:	/* AGP graphics */
			break;
		default:		/* Non IGD/AGP graphics */
			AGPDB_PRINT2((CE_WARN,
			    "lyr_init: non-supported master device"));
			goto err3;
		}

		chip_type = lyr_detect_target_type(target_hdlp);

		/* Continue to detect AGP arc by target device */
		switch (chip_type) {
		case CHIP_IS_INTEL:	/* Intel chipset */
			AGPDB_PRINT1((CE_NOTE,
			    "lyr_init: Intel AGP arch detected"));
			agp_regdev->agprd_arctype = ARC_INTELAGP;
			return (0);
		case CHIP_IS_AMD:	/* AMD chipset */
			AGPDB_PRINT2((CE_WARN,
			    "lyr_init: no cpu gart, but have AMD64 chipsets"));
			goto err3;
		default:		/* Non supported chipset */
			AGPDB_PRINT2((CE_WARN,
			    "lyr_init: detection can not continue"));
			goto err3;
		}

	}

	if (ret)
		return (-1); /* Errors in open amd64 cpu gart devices */

	/*
	 * AMD64 cpu gart device exsits, continue detection
	 */
	if (agp_master_regis_byname(master_hdlp, agpgart_li)) {
		AGPDB_PRINT1((CE_NOTE, "lyr_init: no AGP master in amd64"));
		goto err1;
	}

	if (agp_target_regis_byname(target_hdlp, agpgart_li)) {
		AGPDB_PRINT1((CE_NOTE,
		    "lyr_init: no AGP bridge"));
		goto err2;
	}

	AGPDB_PRINT1((CE_NOTE,
	    "lyr_init: the system is AMD64 AGP architecture"));

	agp_regdev->agprd_arctype = ARC_AMD64AGP;

	return (0); /* Finished successfully */

err3:
	agp_target_unregister(&agp_regdev->agprd_targethdl);
err2:
	agp_master_unregister(&agp_regdev->agprd_masterhdl);
err1:
	/* AMD64 CPU gart registered ? */
	if (ret == 0) {
		amd64_gart_unregister(garts_dev);
	}
	agp_regdev->agprd_arctype = ARC_UNKNOWN;
	return (-1);
}

void
lyr_end(agp_registered_dev_t *agp_regdev)
{
	ASSERT(agp_regdev);

	switch (agp_regdev->agprd_arctype) {
	case ARC_IGD810:
	case ARC_IGD830:
	case ARC_INTELAGP:
		agp_master_unregister(&agp_regdev->agprd_masterhdl);
		agp_target_unregister(&agp_regdev->agprd_targethdl);

		return;
	case ARC_AMD64AGP:
		agp_master_unregister(&agp_regdev->agprd_masterhdl);
		agp_target_unregister(&agp_regdev->agprd_targethdl);
		amd64_gart_unregister(&agp_regdev->agprd_cpugarts);

		return;
	default:
		ASSERT(0);
		return;
	}
}

int
lyr_get_info(agp_kern_info_t *info, agp_registered_dev_t *agp_regdev)
{
	ldi_handle_t hdl;
	igd_info_t value1;
	i_agp_info_t value2;
	size_t prealloc_size;
	int err;

	ASSERT(info);
	ASSERT(agp_regdev);

	switch (agp_regdev->agprd_arctype) {
	case ARC_IGD810:
		hdl = agp_regdev->agprd_masterhdl;
		err = ldi_ioctl(hdl, I8XX_GET_INFO, (intptr_t)&value1,
		    FKIOCTL, kcred, 0);
		if (err)
			return (-1);
		info->agpki_mdevid = value1.igd_devid;
		info->agpki_aperbase = value1.igd_aperbase;
		info->agpki_apersize = (uint32_t)value1.igd_apersize;

		hdl = agp_regdev->agprd_targethdl;
		err = ldi_ioctl(hdl, I8XX_GET_PREALLOC_SIZE,
		    (intptr_t)&prealloc_size, FKIOCTL, kcred, 0);
		if (err)
			return (-1);
		info->agpki_presize = prealloc_size;

		break;

	case ARC_IGD830:
		hdl = agp_regdev->agprd_masterhdl;
		err = ldi_ioctl(hdl, I8XX_GET_INFO, (intptr_t)&value1,
		    FKIOCTL, kcred, 0);
		if (err)
			return (-1);
		info->agpki_mdevid = value1.igd_devid;
		info->agpki_aperbase = value1.igd_aperbase;
		info->agpki_apersize = (uint32_t)value1.igd_apersize;

		hdl = agp_regdev->agprd_targethdl;
		err = ldi_ioctl(hdl, I8XX_GET_PREALLOC_SIZE,
		    (intptr_t)&prealloc_size, FKIOCTL, kcred, 0);
		if (err)
			return (-1);

		/*
		 * Assume all units are kilobytes unless explicitly
		 * stated below:
		 * preallocated GTT memory = preallocated memory - GTT size
		 * 	- scratch page size
		 *
		 * scratch page size = 4
		 * GTT size (KB) = aperture size (MB)
		 * this algorithm came from Xorg source code
		 */
		if (prealloc_size > (info->agpki_apersize + 4))
			prealloc_size =
			    prealloc_size - info->agpki_apersize - 4;
		else {
			AGPDB_PRINT2((CE_WARN, "lyr_get_info: "
			    "pre-allocated memory too small, setting to zero"));
			prealloc_size = 0;
		}
		info->agpki_presize = prealloc_size;
		AGPDB_PRINT2((CE_NOTE,
		    "lyr_get_info: prealloc_size = %ldKB, apersize = %dMB",
		    prealloc_size, info->agpki_apersize));
		break;
	case ARC_INTELAGP:
	case ARC_AMD64AGP:
		/* AGP devices */
		hdl = agp_regdev->agprd_masterhdl;
		err = ldi_ioctl(hdl, AGP_MASTER_GETINFO,
		    (intptr_t)&value2, FKIOCTL, kcred, 0);
		if (err)
			return (-1);
		info->agpki_mdevid = value2.iagp_devid;
		info->agpki_mver = value2.iagp_ver;
		info->agpki_mstatus = value2.iagp_mode;
		hdl = agp_regdev->agprd_targethdl;
		err = ldi_ioctl(hdl, AGP_TARGET_GETINFO,
		    (intptr_t)&value2, FKIOCTL, kcred, 0);
		if (err)
			return (-1);
		info->agpki_tdevid = value2.iagp_devid;
		info->agpki_tver = value2.iagp_ver;
		info->agpki_tstatus = value2.iagp_mode;
		info->agpki_aperbase = value2.iagp_aperbase;
		info->agpki_apersize = (uint32_t)value2.iagp_apersize;
		break;
	default:
		AGPDB_PRINT2((CE_WARN,
		    "lyr_get_info: function doesn't work for unknown arc"));
		return (-1);
	}
	if ((info->agpki_apersize >= MAXAPERMEGAS) ||
	    (info->agpki_apersize == 0) ||
	    (info->agpki_aperbase == 0)) {
		AGPDB_PRINT2((CE_WARN,
		    "lyr_get_info: aperture is not programmed correctly!"));
		return (-1);
	}

	return (0);
}

/*
 * lyr_i8xx_add_to_gtt()
 *
 * Description:
 * 	This function sets up the integrated video device gtt table
 * 	via an ioclt to the AGP master driver.
 *
 * Arguments:
 * 	pg_offset	The start entry to be setup
 * 	keyent		Keytable entity pointer
 *	agp_regdev	AGP devices registration struct pointer
 *
 * Returns:
 * 	0		success
 * 	-1		invalid operations
 */
int
lyr_i8xx_add_to_gtt(uint32_t pg_offset, keytable_ent_t *keyent,
    agp_registered_dev_t *agp_regdev)
{
	int err = 0;
	int rval;
	ldi_handle_t hdl;
	igd_gtt_seg_t gttseg;
	uint32_t *addrp, i;
	uint32_t npages;

	ASSERT(keyent);
	ASSERT(agp_regdev);
	gttseg.igs_pgstart =  pg_offset;
	npages = keyent->kte_pages;
	gttseg.igs_npage = npages;
	gttseg.igs_type = keyent->kte_type;
	gttseg.igs_phyaddr = (uint32_t *)kmem_zalloc
	    (sizeof (uint32_t) * gttseg.igs_npage, KM_SLEEP);

	addrp = gttseg.igs_phyaddr;
	for (i = 0; i < npages; i++, addrp++) {
		*addrp =
		    (uint32_t)((keyent->kte_pfnarray[i]) << GTT_PAGE_SHIFT);
	}

	hdl = agp_regdev->agprd_masterhdl;
	if (ldi_ioctl(hdl, I8XX_ADD2GTT, (intptr_t)&gttseg, FKIOCTL,
	    kcred, &rval)) {
		AGPDB_PRINT2((CE_WARN, "lyr_i8xx_add_to_gtt: ldi_ioctl error"));
		AGPDB_PRINT2((CE_WARN, "lyr_i8xx_add_to_gtt: pg_start=0x%x",
		    gttseg.igs_pgstart));
		AGPDB_PRINT2((CE_WARN, "lyr_i8xx_add_to_gtt: pages=0x%x",
		    gttseg.igs_npage));
		AGPDB_PRINT2((CE_WARN, "lyr_i8xx_add_to_gtt: type=0x%x",
		    gttseg.igs_type));
		err = -1;
	}
	kmem_free(gttseg.igs_phyaddr, sizeof (uint32_t) * gttseg.igs_npage);
	return (err);
}

/*
 * lyr_i8xx_remove_from_gtt()
 *
 * Description:
 * 	This function clears the integrated video device gtt table via
 * 	an ioctl to the agp master device.
 *
 * Arguments:
 * 	pg_offset	The starting entry to be cleared
 * 	npage		The number of entries to be cleared
 *	agp_regdev	AGP devices struct pointer
 *
 * Returns:
 * 	0		success
 * 	-1		invalid operations
 */
int
lyr_i8xx_remove_from_gtt(uint32_t pg_offset, uint32_t npage,
    agp_registered_dev_t *agp_regdev)
{
	int			rval;
	ldi_handle_t		hdl;
	igd_gtt_seg_t		gttseg;

	gttseg.igs_pgstart =  pg_offset;
	gttseg.igs_npage = npage;

	hdl = agp_regdev->agprd_masterhdl;
	if (ldi_ioctl(hdl, I8XX_REM_GTT, (intptr_t)&gttseg, FKIOCTL,
	    kcred, &rval))
		return (-1);

	return (0);
}

/*
 * lyr_set_gart_addr()
 *
 * Description:
 *	This function puts the gart table physical address in the
 * 	gart base register.
 *	Please refer to gart and gtt table base register format for
 *	gart base register format in agpdefs.h.
 *
 * Arguments:
 * 	phy_base	The base physical address of gart table
 *	agp_regdev	AGP devices registration struct pointer
 *
 * Returns:
 * 	0		success
 * 	-1		failed
 *
 */

int
lyr_set_gart_addr(uint64_t phy_base, agp_registered_dev_t *agp_regdev)
{
	amd64_gart_dev_list_t	*gart_list;
	ldi_handle_t		hdl;
	int			err = 0;

	ASSERT(agp_regdev);
	switch (agp_regdev->agprd_arctype) {
	case ARC_IGD810:
	{
		uint32_t base;

		ASSERT((phy_base & I810_POINTER_MASK) == 0);
		base = (uint32_t)phy_base;

		hdl = agp_regdev->agprd_masterhdl;
		err = ldi_ioctl(hdl, I810_SET_GTT_BASE,
		    (intptr_t)&base, FKIOCTL, kcred, 0);
		break;
	}
	case ARC_INTELAGP:
	{
		uint32_t addr;
		addr = (uint32_t)phy_base;

		ASSERT((phy_base & GTT_POINTER_MASK) == 0);
		hdl = agp_regdev->agprd_targethdl;
		err = ldi_ioctl(hdl, AGP_TARGET_SET_GATTADDR,
		    (intptr_t)&addr, FKIOCTL, kcred, 0);
		break;
	}
	case ARC_AMD64AGP:
	{
		uint32_t addr;

		ASSERT((phy_base & AMD64_POINTER_MASK) == 0);
		addr = (uint32_t)((phy_base >> AMD64_GARTBASE_SHIFT)
		    & AMD64_GARTBASE_MASK);

		for (gart_list = agp_regdev->agprd_cpugarts.gart_dev_list_head;
		    gart_list;
		    gart_list = gart_list->next) {
			hdl = gart_list->gart_devhdl;
			if (ldi_ioctl(hdl, AMD64_SET_GART_ADDR,
			    (intptr_t)&addr, FKIOCTL, kcred, 0)) {
				err = -1;
				break;
			}
		}
		break;
	}
	default:
		err = -1;
	}

	if (err)
		return (-1);

	return (0);
}

int
lyr_set_agp_cmd(uint32_t cmd, agp_registered_dev_t *agp_regdev)
{
	ldi_handle_t hdl;
	uint32_t command;

	ASSERT(agp_regdev);
	command = cmd;
	hdl = agp_regdev->agprd_targethdl;
	if (ldi_ioctl(hdl, AGP_TARGET_SETCMD,
	    (intptr_t)&command, FKIOCTL, kcred, 0))
		return (-1);
	hdl = agp_regdev->agprd_masterhdl;
	if (ldi_ioctl(hdl, AGP_MASTER_SETCMD,
	    (intptr_t)&command, FKIOCTL, kcred, 0))
		return (-1);

	return (0);
}

int
lyr_config_devices(agp_registered_dev_t *agp_regdev)
{
	amd64_gart_dev_list_t	*gart_list;
	ldi_handle_t		hdl;
	int			rc = 0;

	ASSERT(agp_regdev);
	switch (agp_regdev->agprd_arctype) {
	case ARC_IGD830:
	case ARC_IGD810:
		break;
	case ARC_INTELAGP:
	{
		hdl = agp_regdev->agprd_targethdl;
		rc = ldi_ioctl(hdl, AGP_TARGET_CONFIGURE,
		    0, FKIOCTL, kcred, 0);
		break;
	}
	case ARC_AMD64AGP:
	{
		/*
		 * BIOS always shadow registers such like Aperture Base
		 * register, Aperture Size Register from the AGP bridge
		 * to the AMD64 CPU host bridge. If future BIOSes are broken
		 * in this regard, we may need to shadow these registers
		 * in driver.
		 */

		for (gart_list = agp_regdev->agprd_cpugarts.gart_dev_list_head;
		    gart_list;
		    gart_list = gart_list->next) {
			hdl = gart_list->gart_devhdl;
			if (ldi_ioctl(hdl, AMD64_CONFIGURE,
			    0, FKIOCTL, kcred, 0)) {
				rc = -1;
				break;
			}
		}
		break;
	}
	default:
		rc = -1;
	}

	if (rc)
		return (-1);

	return (0);
}

int
lyr_unconfig_devices(agp_registered_dev_t *agp_regdev)
{
	amd64_gart_dev_list_t	*gart_list;
	ldi_handle_t		hdl;
	int			rc = 0;

	ASSERT(agp_regdev);
	switch (agp_regdev->agprd_arctype) {
	case ARC_IGD830:
	case ARC_IGD810:
	{
		hdl = agp_regdev->agprd_masterhdl;
		rc = ldi_ioctl(hdl, I8XX_UNCONFIG, 0, FKIOCTL, kcred, 0);
		break;
	}
	case ARC_INTELAGP:
	{
		hdl = agp_regdev->agprd_targethdl;
		rc = ldi_ioctl(hdl, AGP_TARGET_UNCONFIG,
		    0, FKIOCTL, kcred, 0);
		break;
	}
	case ARC_AMD64AGP:
	{
		for (gart_list = agp_regdev->agprd_cpugarts.gart_dev_list_head;
		    gart_list; gart_list = gart_list->next) {
			hdl = gart_list->gart_devhdl;
			if (ldi_ioctl(hdl, AMD64_UNCONFIG,
			    0, FKIOCTL, kcred, 0)) {
				rc = -1;
				break;
			}
		}
		break;
	}
	default:
		rc = -1;
	}

	if (rc)
		return (-1);

	return (0);
}

/*
 * lyr_flush_gart_cache()
 *
 * Description:
 * 	This function flushes the GART translation look-aside buffer. All
 * 	GART translation caches will be flushed after this operation.
 *
 * Arguments:
 *	agp_regdev	AGP devices struct pointer
 */
void
lyr_flush_gart_cache(agp_registered_dev_t *agp_regdev)
{
	amd64_gart_dev_list_t	*gart_list;
	ldi_handle_t		hdl;

	ASSERT(agp_regdev);
	if (agp_regdev->agprd_arctype == ARC_AMD64AGP) {
		for (gart_list = agp_regdev->agprd_cpugarts.gart_dev_list_head;
		    gart_list; gart_list = gart_list->next) {
			hdl = gart_list->gart_devhdl;
			(void) ldi_ioctl(hdl, AMD64_FLUSH_GTLB,
			    0, FKIOCTL, kcred, 0);
		}
	} else if (agp_regdev->agprd_arctype == ARC_INTELAGP) {
		hdl = agp_regdev->agprd_targethdl;
		(void) ldi_ioctl(hdl, AGP_TARGET_FLUSH_GTLB, 0,
		    FKIOCTL, kcred, 0);
	}
}

/*
 * get_max_pages()
 *
 * Description:
 * 	This function compute the total pages allowed for agp aperture
 *	based on the ammount of physical pages.
 * 	The algorithm is: compare the aperture size with 1/4 of total
 *	physical pages, and use the smaller one to for the max available
 * 	pages. But the minimum video memory should be 192M.
 *
 * Arguments:
 * 	aper_size	system agp aperture size (in MB)
 *
 * Returns:
 * 	The max possible number of agp memory pages available to users
 */
static uint32_t
get_max_pages(uint32_t aper_size)
{
	uint32_t i, j, size;

	ASSERT(aper_size <= MAXAPERMEGAS);

	i = AGP_MB2PAGES(aper_size);
	j = (physmem >> 2);

	size = ((i < j) ? i : j);

	if (size < AGP_MB2PAGES(MINAPERMEGAS))
		size = AGP_MB2PAGES(MINAPERMEGAS);
	return (size);
}

/*
 * agp_fill_empty_keyent()
 *
 * Description:
 * 	This function finds a empty key table slot and
 * 	fills it with a new entity.
 *
 * Arguments:
 * 	softsate	driver soft state pointer
 * 	entryp		new entity data pointer
 *
 * Returns:
 * 	NULL	no key table slot available
 * 	entryp	the new entity slot pointer
 */
static keytable_ent_t *
agp_fill_empty_keyent(agpgart_softstate_t *softstate, keytable_ent_t *entryp)
{
	int key;
	keytable_ent_t *newentryp;

	ASSERT(softstate);
	ASSERT(entryp);
	ASSERT(entryp->kte_memhdl);
	ASSERT(entryp->kte_pfnarray);
	ASSERT(mutex_owned(&softstate->asoft_instmutex));

	for (key = 0; key < AGP_MAXKEYS; key++) {
		newentryp = &softstate->asoft_table[key];
		if (newentryp->kte_memhdl == NULL) {
			break;
		}
	}

	if (key >= AGP_MAXKEYS) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_fill_empty_keyent: key table exhausted"));
		return (NULL);
	}

	ASSERT(newentryp->kte_pfnarray == NULL);
	bcopy(entryp, newentryp, sizeof (keytable_ent_t));
	newentryp->kte_key = key;

	return (newentryp);
}

/*
 * agp_find_bound_keyent()
 *
 * Description:
 * 	This function finds the key table entity by agp aperture page offset.
 * 	Every keytable entity will have an agp aperture range after the binding
 *	operation.
 *
 * Arguments:
 * 	softsate	driver soft state pointer
 * 	pg_offset	agp aperture page offset
 *
 * Returns:
 * 	NULL		no such keytable entity
 * 	pointer		key table entity pointer found
 */
static keytable_ent_t *
agp_find_bound_keyent(agpgart_softstate_t *softstate, uint32_t pg_offset)
{
	int keycount;
	keytable_ent_t *entryp;

	ASSERT(softstate);
	ASSERT(mutex_owned(&softstate->asoft_instmutex));

	for (keycount = 0; keycount < AGP_MAXKEYS; keycount++) {
		entryp = &softstate->asoft_table[keycount];
		if (entryp->kte_bound == 0) {
			continue;
		}

		if (pg_offset < entryp->kte_pgoff)
			continue;
		if (pg_offset >= (entryp->kte_pgoff + entryp->kte_pages))
			continue;

		ASSERT(entryp->kte_memhdl);
		ASSERT(entryp->kte_pfnarray);

		return (entryp);
	}

	return (NULL);
}

/*
 * agp_check_off()
 *
 * Description:
 * 	This function checks whether an AGP aperture range to be bound
 *	overlaps with AGP offset already bound.
 *
 * Arguments:
 *	entryp		key table start entry pointer
 * 	pg_start	AGP range start page offset
 *	pg_num		pages number to be bound
 *
 * Returns:
 *	0		Does not overlap
 *	-1		Overlaps
 */

static int
agp_check_off(keytable_ent_t *entryp, uint32_t pg_start, uint32_t pg_num)
{
	int key;
	uint64_t pg_end;
	uint64_t kpg_end;

	ASSERT(entryp);

	pg_end = pg_start + pg_num;
	for (key = 0; key < AGP_MAXKEYS; key++) {
		if (!entryp[key].kte_bound)
			continue;

		kpg_end = entryp[key].kte_pgoff + entryp[key].kte_pages;
		if (!((pg_end <= entryp[key].kte_pgoff) ||
		    (pg_start >= kpg_end)))
			break;
	}

	if (key == AGP_MAXKEYS)
		return (0);
	else
		return (-1);
}

static int
is_controlling_proc(agpgart_softstate_t *st)
{
	ASSERT(st);

	if (!st->asoft_acquired) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_setup: gart not acquired"));
		return (-1);
	}
	if (st->asoft_curpid != ddi_get_pid()) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_release: not  controlling process"));
		return (-1);
	}

	return (0);
}

static void release_control(agpgart_softstate_t *st)
{
	st->asoft_curpid = 0;
	st->asoft_acquired = 0;
}

static void acquire_control(agpgart_softstate_t *st)
{
	st->asoft_curpid = ddi_get_pid();
	st->asoft_acquired = 1;
}

/*
 * agp_remove_from_gart()
 *
 * Description:
 * 	This function fills the gart table entries by a given page
 * 	frame number array and setup the agp aperture page to physical
 * 	memory page translation.
 * Arguments:
 * 	pg_offset	Starting aperture page to be bound
 * 	entries		the number of pages to be bound
 * 	acc_hdl		GART table dma memory acc handle
 * 	tablep		GART table kernel virtual address
 */
static void
agp_remove_from_gart(
    uint32_t pg_offset,
    uint32_t entries,
    ddi_dma_handle_t dma_hdl,
    uint32_t *tablep)
{
	uint32_t items = 0;
	uint32_t *entryp;

	entryp = tablep + pg_offset;
	while (items < entries) {
		*(entryp + items) = 0;
		items++;
	}
	(void) ddi_dma_sync(dma_hdl, pg_offset * sizeof (uint32_t),
	    entries * sizeof (uint32_t), DDI_DMA_SYNC_FORDEV);
}

/*
 * agp_unbind_key()
 *
 * Description:
 * 	This function unbinds AGP memory from the gart table. It will clear
 * 	all the gart entries related to this agp memory.
 *
 * Arguments:
 * 	softstate		driver soft state pointer
 * 	entryp			key table entity pointer
 *
 * Returns:
 * 	EINVAL		invalid key table entity pointer
 * 	0		success
 *
 */
static int
agp_unbind_key(agpgart_softstate_t *softstate, keytable_ent_t *entryp)
{
	int retval = 0;

	ASSERT(entryp);
	ASSERT((entryp->kte_key >= 0) && (entryp->kte_key < AGP_MAXKEYS));

	if (!entryp->kte_bound) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_unbind_key: key = 0x%x, not bound",
		    entryp->kte_key));
		return (EINVAL);
	}
	if (entryp->kte_refcnt) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_unbind_key: memory is exported to users"));
		return (EINVAL);
	}

	ASSERT((entryp->kte_pgoff + entryp->kte_pages) <=
	    AGP_MB2PAGES(softstate->asoft_info.agpki_apersize));
	ASSERT((softstate->asoft_devreg.agprd_arctype != ARC_UNKNOWN));

	switch (softstate->asoft_devreg.agprd_arctype) {
	case ARC_IGD810:
	case ARC_IGD830:
		retval = lyr_i8xx_remove_from_gtt(
		    entryp->kte_pgoff, entryp->kte_pages,
		    &softstate->asoft_devreg);
		if (retval) {
			AGPDB_PRINT2((CE_WARN,
			    "agp_unbind_key: Key = 0x%x, clear table error",
			    entryp->kte_key));
			return (EIO);
		}
		break;
	case ARC_INTELAGP:
	case ARC_AMD64AGP:
		agp_remove_from_gart(entryp->kte_pgoff,
		    entryp->kte_pages,
		    softstate->gart_dma_handle,
		    (uint32_t *)softstate->gart_vbase);
		/* Flush GTLB table */
		lyr_flush_gart_cache(&softstate->asoft_devreg);

		break;
	}

	entryp->kte_bound = 0;

	return (0);
}

/*
 * agp_dealloc_kmem()
 *
 * Description:
 * 	This function deallocates dma memory resources for userland
 * 	applications.
 *
 * Arguments:
 * 	entryp		keytable entity pointer
 */
static void
agp_dealloc_kmem(keytable_ent_t *entryp)
{
	kmem_free(entryp->kte_pfnarray, sizeof (pfn_t) * entryp->kte_pages);
	entryp->kte_pfnarray = NULL;

	(void) ddi_dma_unbind_handle(KMEMP(entryp->kte_memhdl)->kmem_handle);
	KMEMP(entryp->kte_memhdl)->kmem_cookies_num = 0;
	ddi_dma_mem_free(&KMEMP(entryp->kte_memhdl)->kmem_acchdl);
	KMEMP(entryp->kte_memhdl)->kmem_acchdl = NULL;
	KMEMP(entryp->kte_memhdl)->kmem_reallen = 0;
	KMEMP(entryp->kte_memhdl)->kmem_kvaddr = NULL;

	ddi_dma_free_handle(&(KMEMP(entryp->kte_memhdl)->kmem_handle));
	KMEMP(entryp->kte_memhdl)->kmem_handle = NULL;

	kmem_free(entryp->kte_memhdl, sizeof (agp_kmem_handle_t));
	entryp->kte_memhdl = NULL;
}

/*
 * agp_dealloc_mem()
 *
 * Description:
 * 	This function deallocates physical memory resources allocated for
 *	userland applications.
 *
 * Arguments:
 * 	st		driver soft state pointer
 * 	entryp		key table entity pointer
 *
 * Returns:
 * 	-1		not a valid memory type or the memory is mapped by
 * 			user area applications
 * 	0		success
 */
static int
agp_dealloc_mem(agpgart_softstate_t *st, keytable_ent_t	*entryp)
{

	ASSERT(entryp);
	ASSERT(st);
	ASSERT(entryp->kte_memhdl);
	ASSERT(mutex_owned(&st->asoft_instmutex));

	/* auto unbind here */
	if (entryp->kte_bound && !entryp->kte_refcnt) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_dealloc_mem: key=0x%x, auto unbind",
		    entryp->kte_key));

		/*
		 * agp_dealloc_mem may be called indirectly by agp_detach.
		 * In the agp_detach function, agpgart_close is already
		 * called which will free the gart table. agp_unbind_key
		 * will panic if no valid gart table exists. So test if
		 * gart table exsits here.
		 */
		if (st->asoft_opened)
			(void) agp_unbind_key(st, entryp);
	}
	if (entryp->kte_refcnt) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_dealloc_mem: memory is exported to users"));
		return (-1);
	}

	switch (entryp->kte_type) {
	case AGP_NORMAL:
	case AGP_PHYSICAL:
		agp_dealloc_kmem(entryp);
		break;
	default:
		return (-1);
	}

	return (0);
}

/*
 * agp_del_allkeys()
 *
 * Description:
 * 	This function calls agp_dealloc_mem to release all the agp memory
 *	resource allocated.
 *
 * Arguments:
 * 	softsate	driver soft state pointer
 * Returns:
 * 	-1		can not free all agp memory
 * 	0		success
 *
 */
static int
agp_del_allkeys(agpgart_softstate_t *softstate)
{
	int key;
	int ret = 0;

	ASSERT(softstate);
	for (key = 0; key < AGP_MAXKEYS; key++) {
		if (softstate->asoft_table[key].kte_memhdl != NULL) {
			/*
			 * Check if we can free agp memory now.
			 * If agp memory is exported to user
			 * applications, agp_dealloc_mem will fail.
			 */
			if (agp_dealloc_mem(softstate,
			    &softstate->asoft_table[key]))
				ret = -1;
		}
	}

	return (ret);
}

/*
 * pfn2gartentry()
 *
 * Description:
 *	This function converts a physical address to GART entry.
 *	For AMD64, hardware only support addresses below 40bits,
 *	about 1024G physical address, so the largest pfn
 *	number is below 28 bits. Please refer to GART and GTT entry
 *	format table in agpdefs.h for entry format. Intel IGD only
 * 	only supports GTT entry below 1G. Intel AGP only supports
 * 	GART entry below 4G.
 *
 * Arguments:
 * 	arc_type		system agp arc type
 * 	pfn			page frame number
 * 	itemv			the entry item to be returned
 * Returns:
 * 	-1			not a invalid page frame
 * 	0			conversion success
 */
static int
pfn2gartentry(agp_arc_type_t arc_type, pfn_t pfn, uint32_t *itemv)
{
	uint64_t paddr;

	paddr = (uint64_t)pfn << AGP_PAGE_SHIFT;
	AGPDB_PRINT1((CE_NOTE, "checking pfn number %lu for type %d",
	    pfn, arc_type));

	switch (arc_type) {
	case ARC_INTELAGP:
	{
		/* Only support 32-bit hardware address */
		if ((paddr & AGP_INTEL_POINTER_MASK) != 0) {
			AGPDB_PRINT2((CE_WARN,
			    "INTEL AGP Hardware only support 32 bits"));
			return (-1);
		}
		*itemv =  (pfn << AGP_PAGE_SHIFT) | AGP_ENTRY_VALID;

		break;
	}
	case ARC_AMD64AGP:
	{
		uint32_t value1, value2;
		/* Physaddr should not exceed 40-bit */
		if ((paddr & AMD64_POINTER_MASK) != 0) {
			AGPDB_PRINT2((CE_WARN,
			    "AMD64 GART hardware only supoort 40 bits"));
			return (-1);
		}
		value1 = (uint32_t)pfn >> 20;
		value1 <<= 4;
		value2 = (uint32_t)pfn << 12;

		*itemv = value1 | value2 | AMD64_ENTRY_VALID;
		break;
	}
	case ARC_IGD810:
		if ((paddr & I810_POINTER_MASK) != 0) {
			AGPDB_PRINT2((CE_WARN,
			    "Intel i810 only support 30 bits"));
			return (-1);
		}
		break;

	case ARC_IGD830:
		if ((paddr & GTT_POINTER_MASK) != 0) {
			AGPDB_PRINT2((CE_WARN,
			    "Intel IGD only support 32 bits"));
			return (-1);
		}
		break;
	default:
		AGPDB_PRINT2((CE_WARN,
		    "pfn2gartentry: arc type = %d, not support", arc_type));
		return (-1);
	}
	return (0);
}

/*
 * Check allocated physical pages validity, only called in DEBUG
 * mode.
 */
static int
agp_check_pfns(agp_arc_type_t arc_type, pfn_t *pfnarray, int items)
{
	int count;
	uint32_t ret;

	for (count = 0; count < items; count++) {
		if (pfn2gartentry(arc_type, pfnarray[count], &ret))
			break;
	}
	if (count < items)
		return (-1);
	else
		return (0);
}

/*
 * kmem_getpfns()
 *
 * Description:
 * 	This function gets page frame numbers from dma handle.
 *
 * Arguments:
 * 	dma_handle		dma hanle allocated by ddi_dma_alloc_handle
 * 	dma_cookip		dma cookie pointer
 * 	cookies_num		cookies number
 * 	pfnarray		array to store page frames
 *
 * Returns:
 *	0		success
 */
static int
kmem_getpfns(
    ddi_dma_handle_t dma_handle,
    ddi_dma_cookie_t *dma_cookiep,
    int cookies_num,
    pfn_t *pfnarray)
{
	int	num_cookies;
	int	index = 0;

	num_cookies = cookies_num;

	while (num_cookies > 0) {
		uint64_t ck_startaddr, ck_length, ck_end;
		ck_startaddr = dma_cookiep->dmac_address;
		ck_length = dma_cookiep->dmac_size;

		ck_end = ck_startaddr + ck_length;
		while (ck_startaddr < ck_end) {
			pfnarray[index] = (pfn_t)ck_startaddr >> AGP_PAGE_SHIFT;
			ck_startaddr += AGP_PAGE_SIZE;
			index++;
		}

		num_cookies--;
		if (num_cookies > 0) {
			ddi_dma_nextcookie(dma_handle, dma_cookiep);
		}
	}

	return (0);
}

static int
copyinfo(agpgart_softstate_t *softstate, agp_info_t *info)
{
	switch (softstate->asoft_devreg.agprd_arctype) {
	case ARC_IGD810:
	case ARC_IGD830:
		info->agpi_version.agpv_major = 0;
		info->agpi_version.agpv_minor = 0;
		info->agpi_devid = softstate->asoft_info.agpki_mdevid;
		info->agpi_mode = 0;
		break;
	case ARC_INTELAGP:
	case ARC_AMD64AGP:
		info->agpi_version = softstate->asoft_info.agpki_tver;
		info->agpi_devid = softstate->asoft_info.agpki_tdevid;
		info->agpi_mode = softstate->asoft_info.agpki_tstatus;
		break;
	default:
		AGPDB_PRINT2((CE_WARN, "copyinfo: UNKNOW ARC"));
		return (-1);
	}
	/*
	 * 64bit->32bit conversion possible
	 */
	info->agpi_aperbase = softstate->asoft_info.agpki_aperbase;
	info->agpi_apersize = softstate->asoft_info.agpki_apersize;
	info->agpi_pgtotal = softstate->asoft_pgtotal;
	info->agpi_pgsystem = info->agpi_pgtotal;
	info->agpi_pgused = softstate->asoft_pgused;

	return (0);
}

static uint32_t
agp_v2_setup(uint32_t tstatus, uint32_t mstatus, uint32_t mode)
{
	uint32_t cmd;
	int rq, sba, over4g, fw, rate;

	/*
	 * tstatus: target device status
	 * mstatus: master device status
	 * mode: the agp mode to be sent
	 */

	/*
	 * RQ - Request Queue size
	 * set RQ to the min of mode and tstatus
	 * if mode set a RQ larger than hardware can support,
	 * use the max RQ which hardware can support.
	 * tstatus & AGPSTAT_RQ_MASK is the max RQ hardware can support
	 * Corelogic will enqueue agp transaction
	 */
	rq = mode & AGPSTAT_RQ_MASK;
	if ((tstatus & AGPSTAT_RQ_MASK) < rq)
		rq = tstatus & AGPSTAT_RQ_MASK;

	/*
	 * SBA - Sideband Addressing
	 *
	 * Sideband Addressing provides an additional bus to pass requests
	 * (address and command) to the target from the master.
	 *
	 * set SBA if all three support it
	 */
	sba = (tstatus & AGPSTAT_SBA) & (mstatus & AGPSTAT_SBA)
	    & (mode & AGPSTAT_SBA);

	/* set OVER4G  if all three support it */
	over4g = (tstatus & AGPSTAT_OVER4G) & (mstatus & AGPSTAT_OVER4G)
	    & (mode & AGPSTAT_OVER4G);

	/*
	 * FW - fast write
	 *
	 * acceleration of memory write transactions from the corelogic to the
	 * A.G.P. master device acting like a PCI target.
	 *
	 * set FW if all three support it
	 */
	fw = (tstatus & AGPSTAT_FW) & (mstatus & AGPSTAT_FW)
	    & (mode & AGPSTAT_FW);

	/*
	 * figure out the max rate
	 * AGP v2 support: 4X, 2X, 1X speed
	 * status bit		meaning
	 * ---------------------------------------------
	 * 7:3			others
	 * 3			0 stand for V2 support
	 * 0:2			001:1X, 010:2X, 100:4X
	 * ----------------------------------------------
	 */
	rate = (tstatus & AGPSTAT_RATE_MASK) & (mstatus & AGPSTAT_RATE_MASK)
	    & (mode & AGPSTAT_RATE_MASK);
	if (rate & AGP2_RATE_4X)
		rate = AGP2_RATE_4X;
	else if (rate & AGP2_RATE_2X)
		rate = AGP2_RATE_2X;
	else
		rate = AGP2_RATE_1X;

	cmd = rq | sba | over4g | fw | rate;
	/* enable agp mode */
	cmd |= AGPCMD_AGPEN;

	return (cmd);
}

static uint32_t
agp_v3_setup(uint32_t tstatus, uint32_t mstatus, uint32_t mode)
{
	uint32_t cmd = 0;
	uint32_t rq, arqsz, cal, sba, over4g, fw, rate;

	/*
	 * tstatus: target device status
	 * mstatus: master device status
	 * mode: the agp mode to be set
	 */

	/*
	 * RQ - Request Queue size
	 * Set RQ to the min of mode and tstatus
	 * If mode set a RQ larger than hardware can support,
	 * use the max RQ which hardware can support.
	 * tstatus & AGPSTAT_RQ_MASK is the max RQ hardware can support
	 * Corelogic will enqueue agp transaction;
	 */
	rq = mode & AGPSTAT_RQ_MASK;
	if ((tstatus & AGPSTAT_RQ_MASK) < rq)
		rq = tstatus & AGPSTAT_RQ_MASK;

	/*
	 * ARQSZ - Asynchronous Request Queue size
	 * Set the value equal to tstatus.
	 * Don't allow the mode register to override values
	 */
	arqsz = tstatus & AGPSTAT_ARQSZ_MASK;

	/*
	 * CAL - Calibration cycle
	 * Set to the min of tstatus and mstatus
	 * Don't allow override by mode register
	 */
	cal = tstatus & AGPSTAT_CAL_MASK;
	if ((mstatus & AGPSTAT_CAL_MASK) < cal)
		cal = mstatus & AGPSTAT_CAL_MASK;

	/*
	 * SBA - Sideband Addressing
	 *
	 * Sideband Addressing provides an additional bus to pass requests
	 * (address and command) to the target from the master.
	 *
	 * SBA in agp v3.0 must be set
	 */
	sba = AGPCMD_SBAEN;

	/* GART64B is not set since no hardware supports it now */

	/* Set OVER4G if all three support it */
	over4g = (tstatus & AGPSTAT_OVER4G) & (mstatus & AGPSTAT_OVER4G)
	    & (mode & AGPSTAT_OVER4G);

	/*
	 * FW - fast write
	 *
	 * Acceleration of memory write transactions from the corelogic to the
	 * A.G.P. master device acting like a PCI target.
	 *
	 * Always set FW in AGP 3.0
	 */
	fw = (tstatus & AGPSTAT_FW) & (mstatus & AGPSTAT_FW)
	    & (mode & AGPSTAT_FW);

	/*
	 * Figure out the max rate
	 *
	 * AGP v3 support: 8X, 4X speed
	 *
	 * status bit		meaning
	 * ---------------------------------------------
	 * 7:3			others
	 * 3			1 stand for V3 support
	 * 0:2			001:4X, 010:8X, 011:4X,8X
	 * ----------------------------------------------
	 */
	rate = (tstatus & AGPSTAT_RATE_MASK) & (mstatus & AGPSTAT_RATE_MASK)
	    & (mode & AGPSTAT_RATE_MASK);
	if (rate & AGP3_RATE_8X)
		rate = AGP3_RATE_8X;
	else
		rate = AGP3_RATE_4X;

	cmd = rq | arqsz | cal | sba | over4g | fw | rate;
	/* Enable AGP mode */
	cmd |= AGPCMD_AGPEN;

	return (cmd);
}

static int
agp_setup(agpgart_softstate_t *softstate, uint32_t mode)
{
	uint32_t tstatus, mstatus;
	uint32_t agp_mode;

	tstatus = softstate->asoft_info.agpki_tstatus;
	mstatus = softstate->asoft_info.agpki_mstatus;

	/*
	 * There are three kinds of AGP mode. AGP mode 1.0, 2.0, 3.0
	 * AGP mode 2.0 is fully compatible with AGP mode 1.0, so we
	 * only check 2.0 and 3.0 mode. AGP 3.0 device can work in
	 * two AGP 2.0 or AGP 3.0 mode. By checking AGP status register,
	 * we can get which mode it is working at. The working mode of
	 * AGP master and AGP target must be consistent. That is, both
	 * of them must work on AGP 3.0 mode or AGP 2.0 mode.
	 */
	if ((softstate->asoft_info.agpki_tver.agpv_major == 3) &&
	    (tstatus & AGPSTAT_MODE3)) {
		/* Master device should be 3.0 mode, too */
		if ((softstate->asoft_info.agpki_mver.agpv_major != 3) ||
		    ((mstatus & AGPSTAT_MODE3) == 0))
			return (EIO);

		agp_mode = agp_v3_setup(tstatus, mstatus, mode);
		/* Write to the AGPCMD register of target and master devices */
		if (lyr_set_agp_cmd(agp_mode,
		    &softstate->asoft_devreg))
			return (EIO);

		softstate->asoft_mode = agp_mode;

		return (0);
	}

	/*
	 * If agp taget device doesn't work in AGP 3.0 mode,
	 * it must work in AGP 2.0 mode. And make sure
	 * master device work in AGP 2.0 mode too
	 */
	if ((softstate->asoft_info.agpki_mver.agpv_major == 3) &&
	    (mstatus & AGPSTAT_MODE3))
		return (EIO);

	agp_mode = agp_v2_setup(tstatus, mstatus, mode);
	if (lyr_set_agp_cmd(agp_mode, &softstate->asoft_devreg))
		return (EIO);
	softstate->asoft_mode = agp_mode;

	return (0);
}

/*
 * agp_alloc_kmem()
 *
 * Description:
 * 	This function allocates physical memory for userland applications
 * 	by ddi interfaces. This function can also be called to allocate
 *	small phsyical contiguous pages, usually tens of kilobytes.
 *
 * Arguments:
 * 	softsate	driver soft state pointer
 * 	length		memory size
 *
 * Returns:
 * 	entryp		new keytable entity pointer
 * 	NULL		no keytable slot available or no physical
 *			memory available
 */
static keytable_ent_t *
agp_alloc_kmem(agpgart_softstate_t *softstate, size_t length, int type)
{
	keytable_ent_t	keyentry;
	keytable_ent_t	*entryp;
	int		ret;

	ASSERT(AGP_ALIGNED(length));

	bzero(&keyentry, sizeof (keytable_ent_t));

	keyentry.kte_pages = AGP_BYTES2PAGES(length);
	keyentry.kte_type = type;

	/*
	 * Set dma_attr_sgllen to assure contiguous physical pages
	 */
	if (type == AGP_PHYSICAL)
		agpgart_dma_attr.dma_attr_sgllen = 1;
	else
		agpgart_dma_attr.dma_attr_sgllen = (int)keyentry.kte_pages;

	/* 4k size pages */
	keyentry.kte_memhdl = kmem_zalloc(sizeof (agp_kmem_handle_t), KM_SLEEP);

	if (ddi_dma_alloc_handle(softstate->asoft_dip,
	    &agpgart_dma_attr,
	    DDI_DMA_SLEEP, NULL,
	    &(KMEMP(keyentry.kte_memhdl)->kmem_handle))) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_alloc_kmem: ddi_dma_allco_hanlde error"));
		goto err4;
	}

	if ((ret = ddi_dma_mem_alloc(
	    KMEMP(keyentry.kte_memhdl)->kmem_handle,
	    length,
	    &gart_dev_acc_attr,
	    DDI_DMA_CONSISTENT,
	    DDI_DMA_SLEEP, NULL,
	    &KMEMP(keyentry.kte_memhdl)->kmem_kvaddr,
	    &KMEMP(keyentry.kte_memhdl)->kmem_reallen,
	    &KMEMP(keyentry.kte_memhdl)->kmem_acchdl)) != 0) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_alloc_kmem: ddi_dma_mem_alloc error"));

		goto err3;
	}

	ret = ddi_dma_addr_bind_handle(
	    KMEMP(keyentry.kte_memhdl)->kmem_handle,
	    NULL,
	    KMEMP(keyentry.kte_memhdl)->kmem_kvaddr,
	    length,
	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
	    DDI_DMA_SLEEP,
	    NULL,
	    &KMEMP(keyentry.kte_memhdl)->kmem_dcookie,
	    &KMEMP(keyentry.kte_memhdl)->kmem_cookies_num);

	/*
	 * Even dma_attr_sgllen = 1, ddi_dma_addr_bind_handle may return more
	 * than one cookie, we check this in the if statement.
	 */

	if ((ret != DDI_DMA_MAPPED) ||
	    ((agpgart_dma_attr.dma_attr_sgllen == 1) &&
	    (KMEMP(keyentry.kte_memhdl)->kmem_cookies_num != 1))) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_alloc_kmem: can not alloc physical memory properly"));
		goto err2;
	}

	keyentry.kte_pfnarray = (pfn_t *)kmem_zalloc(sizeof (pfn_t) *
	    keyentry.kte_pages, KM_SLEEP);

	if (kmem_getpfns(
	    KMEMP(keyentry.kte_memhdl)->kmem_handle,
	    &KMEMP(keyentry.kte_memhdl)->kmem_dcookie,
	    KMEMP(keyentry.kte_memhdl)->kmem_cookies_num,
	    keyentry.kte_pfnarray)) {
		AGPDB_PRINT2((CE_WARN, "agp_alloc_kmem: get pfn array error"));
		goto err1;
	}

	ASSERT(!agp_check_pfns(softstate->asoft_devreg.agprd_arctype,
	    keyentry.kte_pfnarray, keyentry.kte_pages));
	if (agp_check_pfns(softstate->asoft_devreg.agprd_arctype,
	    keyentry.kte_pfnarray, keyentry.kte_pages))
		goto err1;
	entryp = agp_fill_empty_keyent(softstate, &keyentry);
	if (!entryp) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_alloc_kmem: agp_fill_empty_keyent error"));

		goto err1;
	}
	ASSERT((entryp->kte_key >= 0) && (entryp->kte_key < AGP_MAXKEYS));

	return (entryp);

err1:
	kmem_free(keyentry.kte_pfnarray, sizeof (pfn_t) * keyentry.kte_pages);
	keyentry.kte_pfnarray = NULL;
	(void) ddi_dma_unbind_handle(KMEMP(keyentry.kte_memhdl)->kmem_handle);
	KMEMP(keyentry.kte_memhdl)->kmem_cookies_num = 0;
err2:
	ddi_dma_mem_free(&KMEMP(keyentry.kte_memhdl)->kmem_acchdl);
	KMEMP(keyentry.kte_memhdl)->kmem_acchdl = NULL;
	KMEMP(keyentry.kte_memhdl)->kmem_reallen = 0;
	KMEMP(keyentry.kte_memhdl)->kmem_kvaddr = NULL;
err3:
	ddi_dma_free_handle(&(KMEMP(keyentry.kte_memhdl)->kmem_handle));
	KMEMP(keyentry.kte_memhdl)->kmem_handle = NULL;
err4:
	kmem_free(keyentry.kte_memhdl, sizeof (agp_kmem_handle_t));
	keyentry.kte_memhdl = NULL;
	return (NULL);

}

/*
 * agp_alloc_mem()
 *
 * Description:
 * 	This function allocate physical memory for userland applications,
 * 	in order to save kernel virtual space, we use the direct mapping
 * 	memory interface if it is available.
 *
 * Arguments:
 * 	st		driver soft state pointer
 * 	length		memory size
 * 	type		AGP_NORMAL: normal agp memory, AGP_PHISYCAL: specical
 *			memory type for intel i810 IGD
 *
 * Returns:
 * 	NULL 	Invalid memory type or can not allocate memory
 * 	Keytable entry pointer returned by agp_alloc_kmem
 */
static keytable_ent_t *
agp_alloc_mem(agpgart_softstate_t *st, size_t length, int type)
{

	/*
	 * AGP_PHYSICAL type require contiguous physical pages exported
	 * to X drivers, like i810 HW cursor, ARGB cursor. the number of
	 * pages needed is usuallysmall and contiguous, 4K, 16K. So we
	 * use DDI interface to allocated such memory. And X use xsvc
	 * drivers to map this memory into its own address space.
	 */
	ASSERT(st);

	switch (type) {
	case AGP_NORMAL:
	case AGP_PHYSICAL:
		return (agp_alloc_kmem(st, length, type));
	default:
		return (NULL);
	}
}

/*
 * free_gart_table()
 *
 * Description:
 * 	This function frees the gart table memory allocated by driver.
 * 	Must disable gart table before calling this function.
 *
 * Arguments:
 * 	softstate		driver soft state pointer
 *
 */
static void
free_gart_table(agpgart_softstate_t *st)
{

	if (st->gart_dma_handle == NULL)
		return;

	(void) ddi_dma_unbind_handle(st->gart_dma_handle);
	ddi_dma_mem_free(&st->gart_dma_acc_handle);
	st->gart_dma_acc_handle = NULL;
	ddi_dma_free_handle(&st->gart_dma_handle);
	st->gart_dma_handle = NULL;
	st->gart_vbase = 0;
	st->gart_size = 0;
}

/*
 * alloc_gart_table()
 *
 * Description:
 * 	This function allocates one physical continuous gart table.
 * 	INTEL integrated video device except i810 have their special
 * 	video bios; No need to allocate gart table for them.
 *
 * Arguments:
 * 	st		driver soft state pointer
 *
 * Returns:
 * 	0		success
 * 	-1		can not allocate gart tabl
 */
static int
alloc_gart_table(agpgart_softstate_t *st)
{
	int			num_pages;
	size_t			table_size;
	int			ret = DDI_SUCCESS;
	ddi_dma_cookie_t	cookie;
	uint32_t		num_cookies;

	num_pages = AGP_MB2PAGES(st->asoft_info.agpki_apersize);

	/*
	 * Only 40-bit maximum physical memory is supported by today's
	 * AGP hardware (32-bit gart tables can hold 40-bit memory addresses).
	 * No one supports 64-bit gart entries now, so the size of gart
	 * entries defaults to 32-bit though AGP3.0 specifies the possibility
	 * of 64-bit gart entries.
	 */

	table_size = num_pages * (sizeof (uint32_t));

	/*
	 * Only AMD64 can put gart table above 4G, 40 bits at maximum
	 */
	if (st->asoft_devreg.agprd_arctype == ARC_AMD64AGP)
		garttable_dma_attr.dma_attr_addr_hi = 0xffffffffffLL;
	else
		garttable_dma_attr.dma_attr_addr_hi = 0xffffffffU;
	/* Allocate physical continuous page frame for gart table */
	if (ret = ddi_dma_alloc_handle(st->asoft_dip,
	    &garttable_dma_attr,
	    DDI_DMA_SLEEP,
	    NULL, &st->gart_dma_handle)) {
		AGPDB_PRINT2((CE_WARN,
		    "alloc_gart_table: ddi_dma_alloc_handle failed"));
		goto err3;
	}

	if (ret = ddi_dma_mem_alloc(st->gart_dma_handle,
	    table_size,
	    &gart_dev_acc_attr,
	    DDI_DMA_CONSISTENT,
	    DDI_DMA_SLEEP, NULL,
	    &st->gart_vbase,
	    &st->gart_size,
	    &st->gart_dma_acc_handle)) {
		AGPDB_PRINT2((CE_WARN,
		    "alloc_gart_table: ddi_dma_mem_alloc failed"));
		goto err2;

	}

	ret = ddi_dma_addr_bind_handle(st->gart_dma_handle,
	    NULL, st->gart_vbase,
	    table_size,
	    DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
	    DDI_DMA_SLEEP, NULL,
	    &cookie,  &num_cookies);

	st->gart_pbase = cookie.dmac_address;

	if ((ret != DDI_DMA_MAPPED) || (num_cookies != 1)) {
		if (num_cookies > 1)
			(void) ddi_dma_unbind_handle(st->gart_dma_handle);
		AGPDB_PRINT2((CE_WARN,
		    "alloc_gart_table: alloc contiguous phys memory failed"));
		goto err1;
	}

	return (0);
err1:
	ddi_dma_mem_free(&st->gart_dma_acc_handle);
	st->gart_dma_acc_handle = NULL;
err2:
	ddi_dma_free_handle(&st->gart_dma_handle);
	st->gart_dma_handle = NULL;
err3:
	st->gart_pbase = 0;
	st->gart_size = 0;
	st->gart_vbase = 0;

	return (-1);
}

/*
 * agp_add_to_gart()
 *
 * Description:
 * 	This function fills the gart table entries by a given page frame number
 * 	array and set up the agp aperture page to physical memory page
 * 	translation.
 * Arguments:
 * 	type		valid sytem arc types ARC_AMD64AGP, ARC_INTELAGP,
 * 			ARC_AMD64AGP
 * 	pfnarray	allocated physical page frame number array
 * 	pg_offset	agp aperture start page to be bound
 * 	entries		the number of pages to be bound
 * 	dma_hdl		gart table dma memory handle
 * 	tablep		gart table kernel virtual address
 * Returns:
 * 	-1		failed
 * 	0		success
 */
static int
agp_add_to_gart(
    agp_arc_type_t type,
    pfn_t *pfnarray,
    uint32_t pg_offset,
    uint32_t entries,
    ddi_dma_handle_t dma_hdl,
    uint32_t *tablep)
{
	int items = 0;
	uint32_t *entryp;
	uint32_t itemv;

	entryp = tablep + pg_offset;
	while (items < entries) {
		if (pfn2gartentry(type, pfnarray[items], &itemv))
			break;
		*(entryp + items) = itemv;
		items++;
	}
	if (items < entries)
		return (-1);

	(void) ddi_dma_sync(dma_hdl, pg_offset * sizeof (uint32_t),
	    entries * sizeof (uint32_t), DDI_DMA_SYNC_FORDEV);

	return (0);
}

/*
 * agp_bind_key()
 *
 * Description:
 * 	This function will call low level gart table access functions to
 * 	set up gart table translation. Also it will do some sanity
 * 	checking on key table entry.
 *
 * Arguments:
 * 	softstate		driver soft state pointer
 * 	keyent			key table entity pointer to be bound
 * 	pg_offset		aperture start page to be bound
 * Returns:
 * 	EINVAL			not a valid operation
 */
static int
agp_bind_key(agpgart_softstate_t *softstate,
    keytable_ent_t  *keyent, uint32_t  pg_offset)
{
	uint64_t pg_end;
	int ret = 0;

	ASSERT(keyent);
	ASSERT((keyent->kte_key >= 0) && (keyent->kte_key < AGP_MAXKEYS));
	ASSERT(mutex_owned(&softstate->asoft_instmutex));

	pg_end = pg_offset + keyent->kte_pages;

	if (pg_end > AGP_MB2PAGES(softstate->asoft_info.agpki_apersize)) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_bind_key: key=0x%x,exceed aper range",
		    keyent->kte_key));

		return (EINVAL);
	}

	if (agp_check_off(softstate->asoft_table,
	    pg_offset, keyent->kte_pages)) {
		AGPDB_PRINT2((CE_WARN,
		    "agp_bind_key: pg_offset=0x%x, pages=0x%lx overlaped",
		    pg_offset, keyent->kte_pages));
		return (EINVAL);
	}

	ASSERT(keyent->kte_pfnarray != NULL);

	switch (softstate->asoft_devreg.agprd_arctype) {
	case ARC_IGD810:
	case ARC_IGD830:
		ret = lyr_i8xx_add_to_gtt(pg_offset, keyent,
		    &softstate->asoft_devreg);
		if (ret)
			return (EIO);
		break;
	case ARC_INTELAGP:
	case ARC_AMD64AGP:
		ret =  agp_add_to_gart(
		    softstate->asoft_devreg.agprd_arctype,
		    keyent->kte_pfnarray,
		    pg_offset,
		    keyent->kte_pages,
		    softstate->gart_dma_handle,
		    (uint32_t *)softstate->gart_vbase);
		if (ret)
			return (EINVAL);
		/* Flush GTLB table */
		lyr_flush_gart_cache(&softstate->asoft_devreg);
		break;
	default:
		AGPDB_PRINT2((CE_WARN,
		    "agp_bind_key: arc type = 0x%x unsupported",
		    softstate->asoft_devreg.agprd_arctype));
		return (EINVAL);
	}
	return (0);
}

static int
agpgart_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
{
	int instance;
	agpgart_softstate_t *softstate;

	if (cmd != DDI_ATTACH) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_attach: only attach op supported"));
		return (DDI_FAILURE);
	}
	instance = ddi_get_instance(dip);

	if (ddi_soft_state_zalloc(agpgart_glob_soft_handle, instance)
	    != DDI_SUCCESS) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_attach: soft state zalloc failed"));
		goto err1;

	}
	softstate = ddi_get_soft_state(agpgart_glob_soft_handle, instance);
	mutex_init(&softstate->asoft_instmutex, NULL, MUTEX_DRIVER, NULL);
	softstate->asoft_dip = dip;
	/*
	 * Allocate LDI identifier for agpgart driver
	 * Agpgart driver is the kernel consumer
	 */
	if (ldi_ident_from_dip(dip, &softstate->asoft_li)) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_attach: LDI indentifier allcation failed"));
		goto err2;
	}

	softstate->asoft_devreg.agprd_arctype = ARC_UNKNOWN;
	/* Install agp kstat */
	if (agp_init_kstats(softstate)) {
		AGPDB_PRINT2((CE_WARN, "agpgart_attach: init kstats error"));
		goto err3;
	}
	/*
	 * devfs will create /dev/agpgart
	 * and  /devices/agpgart:agpgart
	 */

	if (ddi_create_minor_node(dip, AGPGART_DEVNODE, S_IFCHR,
	    AGP_INST2MINOR(instance),
	    DDI_NT_AGP_PSEUDO, 0)) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_attach: Can not create minor node"));
		goto err4;
	}

	softstate->asoft_table = kmem_zalloc(
	    AGP_MAXKEYS * (sizeof (keytable_ent_t)),
	    KM_SLEEP);

	list_head_init(&softstate->mapped_list);

	return (DDI_SUCCESS);
err4:
	agp_fini_kstats(softstate);
err3:
	ldi_ident_release(softstate->asoft_li);
err2:
	ddi_soft_state_free(agpgart_glob_soft_handle, instance);
err1:
	return (DDI_FAILURE);
}

static int
agpgart_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
{
	int instance;
	agpgart_softstate_t *st;

	instance = ddi_get_instance(dip);

	st = ddi_get_soft_state(agpgart_glob_soft_handle, instance);

	if (cmd != DDI_DETACH)
		return (DDI_FAILURE);

	/*
	 * Caller should free all the memory allocated explicitly.
	 * We release the memory allocated by caller which is not
	 * properly freed. mutex_enter here make sure assertion on
	 * softstate mutex success in agp_dealloc_mem.
	 */
	mutex_enter(&st->asoft_instmutex);
	if (agp_del_allkeys(st)) {
		AGPDB_PRINT2((CE_WARN, "agpgart_detach: agp_del_allkeys err"));
		AGPDB_PRINT2((CE_WARN,
		    "you might free agp memory exported to your applications"));

		mutex_exit(&st->asoft_instmutex);
		return (DDI_FAILURE);
	}
	mutex_exit(&st->asoft_instmutex);
	if (st->asoft_table) {
		kmem_free(st->asoft_table,
		    AGP_MAXKEYS * (sizeof (keytable_ent_t)));
		st->asoft_table = 0;
	}

	struct list_head	*entry,	*temp,	*head;
	igd_gtt_seg_t	*gttseg;
	list_head_for_each_safe(entry, temp, &st->mapped_list) {
		gttseg = entry->gttseg;
		list_head_del(entry);
		kmem_free(entry, sizeof (*entry));
		kmem_free(gttseg->igs_phyaddr,
		    sizeof (uint32_t) * gttseg->igs_npage);
		kmem_free(gttseg, sizeof (igd_gtt_seg_t));
	}
	head = &st->mapped_list;
	kmem_free(head->next,
	    AGP_HASH_NODE * sizeof (struct list_head));
	head->next = NULL;

	ddi_remove_minor_node(dip, AGPGART_DEVNODE);
	agp_fini_kstats(st);
	ldi_ident_release(st->asoft_li);
	mutex_destroy(&st->asoft_instmutex);
	ddi_soft_state_free(agpgart_glob_soft_handle, instance);

	return (DDI_SUCCESS);
}

/*ARGSUSED*/
static int
agpgart_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg,
    void **resultp)
{
	agpgart_softstate_t *st;
	int instance, rval = DDI_FAILURE;
	dev_t dev;

	switch (cmd) {
	case DDI_INFO_DEVT2DEVINFO:
		dev = (dev_t)arg;
		instance = AGP_DEV2INST(dev);
		st = ddi_get_soft_state(agpgart_glob_soft_handle, instance);
		if (st != NULL) {
			mutex_enter(&st->asoft_instmutex);
			*resultp = st->asoft_dip;
			mutex_exit(&st->asoft_instmutex);
			rval = DDI_SUCCESS;
		} else
			*resultp = NULL;

		break;
	case DDI_INFO_DEVT2INSTANCE:
		dev = (dev_t)arg;
		instance = AGP_DEV2INST(dev);
		*resultp = (void *)(uintptr_t)instance;
		rval = DDI_SUCCESS;

		break;
	default:
		break;
	}

	return (rval);
}

/*
 * agpgart_open()
 *
 * Description:
 * 	This function is the driver open entry point. If it is the
 * 	first time the agpgart driver is opened, the driver will
 * 	open other agp related layered drivers and set up the agpgart
 * 	table properly.
 *
 * Arguments:
 * 	dev			device number pointer
 * 	openflags		open flags
 *	otyp			OTYP_BLK, OTYP_CHR
 * 	credp			user's credential's struct pointer
 *
 * Returns:
 * 	ENXIO			operation error
 * 	EAGAIN			resoure temporarily unvailable
 * 	0			success
 */
/*ARGSUSED*/
static int
agpgart_open(dev_t *dev, int openflags, int otyp, cred_t *credp)
{
	int instance = AGP_DEV2INST(*dev);
	agpgart_softstate_t *softstate;
	int rc = 0;
	uint32_t devid;

	if (secpolicy_gart_access(credp)) {
		AGPDB_PRINT2((CE_WARN, "agpgart_open: permission denied"));
		return (EPERM);
	}
	softstate = ddi_get_soft_state(agpgart_glob_soft_handle, instance);
	if (softstate == NULL) {
		AGPDB_PRINT2((CE_WARN, "agpgart_open: get soft state err"));
		return (ENXIO);
	}

	mutex_enter(&softstate->asoft_instmutex);

	if (softstate->asoft_opened) {
		softstate->asoft_opened++;
		mutex_exit(&softstate->asoft_instmutex);
		return (0);
	}

	/*
	 * The driver is opened first time, so we initialize layered
	 * driver interface and softstate member here.
	 */
	softstate->asoft_pgused = 0;
	if (lyr_init(&softstate->asoft_devreg, softstate->asoft_li)) {
		AGPDB_PRINT2((CE_WARN, "agpgart_open: lyr_init failed"));
		mutex_exit(&softstate->asoft_instmutex);
		return (EAGAIN);
	}

	/* Call into layered driver */
	if (lyr_get_info(&softstate->asoft_info, &softstate->asoft_devreg)) {
		AGPDB_PRINT2((CE_WARN, "agpgart_open: lyr_get_info error"));
		lyr_end(&softstate->asoft_devreg);
		mutex_exit(&softstate->asoft_instmutex);
		return (EIO);
	}

	/*
	 * BIOS already set up gtt table for ARC_IGD830
	 */
	if (IS_INTEL_830(softstate->asoft_devreg.agprd_arctype)) {
		softstate->asoft_opened++;

		softstate->asoft_pgtotal =
		    get_max_pages(softstate->asoft_info.agpki_apersize);

		if (lyr_config_devices(&softstate->asoft_devreg)) {
			AGPDB_PRINT2((CE_WARN,
			    "agpgart_open: lyr_config_devices error"));
			lyr_end(&softstate->asoft_devreg);
			mutex_exit(&softstate->asoft_instmutex);

			return (EIO);
		}
		devid = softstate->asoft_info.agpki_mdevid;
		if (IS_INTEL_915(devid) ||
		    IS_INTEL_965(devid) ||
		    IS_INTEL_X33(devid) ||
		    IS_INTEL_G4X(devid)) {
			rc = ldi_ioctl(softstate->asoft_devreg.agprd_targethdl,
			    INTEL_CHIPSET_FLUSH_SETUP, 0, FKIOCTL, kcred, 0);
		}
		if (rc) {
			AGPDB_PRINT2((CE_WARN,
			    "agpgart_open: Intel chipset flush setup error"));
			lyr_end(&softstate->asoft_devreg);
			mutex_exit(&softstate->asoft_instmutex);
			return (EIO);
		}
		mutex_exit(&softstate->asoft_instmutex);
		return (0);
	}

	rc = alloc_gart_table(softstate);

	/*
	 * Allocate physically contiguous pages for AGP arc or
	 * i810 arc. If failed, divide aper_size by 2 to
	 * reduce gart table size until 4 megabytes. This
	 * is just a workaround for systems with very few
	 * physically contiguous memory.
	 */
	if (rc) {
		while ((softstate->asoft_info.agpki_apersize >= 4) &&
		    (alloc_gart_table(softstate))) {
			softstate->asoft_info.agpki_apersize >>= 1;
		}
		if (softstate->asoft_info.agpki_apersize >= 4)
			rc = 0;
	}

	if (rc != 0) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_open: alloc gart table failed"));
		lyr_end(&softstate->asoft_devreg);
		mutex_exit(&softstate->asoft_instmutex);
		return (EAGAIN);
	}

	softstate->asoft_pgtotal =
	    get_max_pages(softstate->asoft_info.agpki_apersize);
	/*
	 * BIOS doesn't initialize GTT for i810,
	 * So i810 GTT must be created by driver.
	 *
	 * Set up gart table and enable it.
	 */
	if (lyr_set_gart_addr(softstate->gart_pbase,
	    &softstate->asoft_devreg)) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_open: set gart table addr failed"));
		free_gart_table(softstate);
		lyr_end(&softstate->asoft_devreg);
		mutex_exit(&softstate->asoft_instmutex);
		return (EIO);
	}
	if (lyr_config_devices(&softstate->asoft_devreg)) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_open: lyr_config_devices failed"));
		free_gart_table(softstate);
		lyr_end(&softstate->asoft_devreg);
		mutex_exit(&softstate->asoft_instmutex);
		return (EIO);
	}

	softstate->asoft_opened++;
	mutex_exit(&softstate->asoft_instmutex);

	return (0);
}

/*
 * agpgart_close()
 *
 * Description:
 * 	agpgart_close will release resources allocated in the first open
 * 	and close other open layered drivers. Also it frees the memory
 *	allocated by ioctls.
 *
 * Arguments:
 * 	dev			device number
 * 	flag			file status flag
 *	otyp			OTYP_BLK, OTYP_CHR
 * 	credp			user's credential's struct pointer
 *
 * Returns:
 * 	ENXIO			not an error, to support "deferred attach"
 * 	0			success
 */
/*ARGSUSED*/
static int
agpgart_close(dev_t dev, int flag, int otyp, cred_t *credp)
{
	int instance = AGP_DEV2INST(dev);
	agpgart_softstate_t *softstate;
	int rc = 0;
	uint32_t devid;

	softstate = ddi_get_soft_state(agpgart_glob_soft_handle, instance);
	if (softstate == NULL) {
		AGPDB_PRINT2((CE_WARN, "agpgart_close: get soft state err"));
		return (ENXIO);
	}

	mutex_enter(&softstate->asoft_instmutex);
	ASSERT(softstate->asoft_opened);


	/*
	 * If the last process close this device is not the controlling
	 * process, also release the control over agpgart driver here if the
	 * the controlling process fails to release the control before it
	 * close the driver.
	 */
	if (softstate->asoft_acquired == 1) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_close: auto release control over driver"));
		release_control(softstate);
	}

	devid = softstate->asoft_info.agpki_mdevid;
	if (IS_INTEL_915(devid) ||
	    IS_INTEL_965(devid) ||
	    IS_INTEL_X33(devid) ||
	    IS_INTEL_G4X(devid)) {
		rc = ldi_ioctl(softstate->asoft_devreg.agprd_targethdl,
		    INTEL_CHIPSET_FLUSH_FREE, 0, FKIOCTL, kcred, 0);
	}
	if (rc) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_open: Intel chipset flush free error"));
	}

	if (lyr_unconfig_devices(&softstate->asoft_devreg)) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_close: lyr_unconfig_device error"));
		mutex_exit(&softstate->asoft_instmutex);
		return (EIO);
	}
	softstate->asoft_agpen = 0;

	if (!IS_INTEL_830(softstate->asoft_devreg.agprd_arctype)) {
		free_gart_table(softstate);
	}

	lyr_end(&softstate->asoft_devreg);

	/*
	 * This statement must be positioned before agp_del_allkeys
	 * agp_dealloc_mem indirectly called by agp_del_allkeys
	 * will test this variable.
	 */
	softstate->asoft_opened = 0;

	/*
	 * Free the memory allocated by user applications which
	 * was never deallocated.
	 */
	(void) agp_del_allkeys(softstate);

	mutex_exit(&softstate->asoft_instmutex);

	return (0);
}

static int
ioctl_agpgart_info(agpgart_softstate_t  *softstate, void  *arg, int flags)
{
	agp_info_t infostruct;
#ifdef _MULTI_DATAMODEL
	agp_info32_t infostruct32;
#endif

	bzero(&infostruct, sizeof (agp_info_t));

#ifdef _MULTI_DATAMODEL
	bzero(&infostruct32, sizeof (agp_info32_t));
	if (ddi_model_convert_from(flags & FMODELS) == DDI_MODEL_ILP32) {
		if (copyinfo(softstate, &infostruct))
			return (EINVAL);

		agpinfo_default_to_32(infostruct, infostruct32);
		if (ddi_copyout(&infostruct32, arg,
		    sizeof (agp_info32_t), flags) != 0)
			return (EFAULT);

		return (0);
	}
#endif /* _MULTI_DATAMODEL */
	if (copyinfo(softstate, &infostruct))
		return (EINVAL);

	if (ddi_copyout(&infostruct, arg, sizeof (agp_info_t), flags) != 0) {
		return (EFAULT);
	}

	return (0);
}

static int
ioctl_agpgart_acquire(agpgart_softstate_t  *st)
{
	if (st->asoft_acquired) {
		AGPDB_PRINT2((CE_WARN, "ioctl_acquire: already acquired"));
		return (EBUSY);
	}
	acquire_control(st);
	return (0);
}

static int
ioctl_agpgart_release(agpgart_softstate_t  *st)
{
	if (is_controlling_proc(st) < 0) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_release: not a controlling process"));
		return (EPERM);
	}
	release_control(st);
	return (0);
}

static int
ioctl_agpgart_setup(agpgart_softstate_t  *st, void  *arg, int flags)
{
	agp_setup_t data;
	int rc = 0;

	if (is_controlling_proc(st) < 0) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_setup: not a controlling process"));
		return (EPERM);
	}

	if (!IS_TRUE_AGP(st->asoft_devreg.agprd_arctype)) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_setup: no true agp bridge"));
		return (EINVAL);
	}

	if (ddi_copyin(arg, &data, sizeof (agp_setup_t), flags) != 0)
		return (EFAULT);

	if (rc = agp_setup(st, data.agps_mode))
		return (rc);
	/* Store agp mode status for kstat */
	st->asoft_agpen = 1;
	return (0);
}

static int
ioctl_agpgart_alloc(agpgart_softstate_t  *st, void  *arg, int flags)
{
	agp_allocate_t	alloc_info;
	keytable_ent_t	*entryp;
	size_t		length;
	uint64_t	pg_num;

	if (is_controlling_proc(st) < 0) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_alloc: not a controlling process"));
		return (EPERM);
	}

	if (ddi_copyin(arg, &alloc_info,
	    sizeof (agp_allocate_t), flags) != 0) {
		return (EFAULT);
	}
	pg_num = st->asoft_pgused + alloc_info.agpa_pgcount;
	if (pg_num > st->asoft_pgtotal) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_alloc: exceeding the memory pages limit"));
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_alloc: request %x pages failed",
		    alloc_info.agpa_pgcount));
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_alloc: pages used %x total is %x",
		    st->asoft_pgused, st->asoft_pgtotal));

		return (EINVAL);
	}

	length = AGP_PAGES2BYTES(alloc_info.agpa_pgcount);
	entryp = agp_alloc_mem(st, length, alloc_info.agpa_type);
	if (!entryp) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_alloc: allocate 0x%lx bytes failed",
		    length));
		return (ENOMEM);
	}
	ASSERT((entryp->kte_key >= 0) && (entryp->kte_key < AGP_MAXKEYS));
	alloc_info.agpa_key = entryp->kte_key;
	if (alloc_info.agpa_type == AGP_PHYSICAL) {
		alloc_info.agpa_physical =
		    (uint32_t)(entryp->kte_pfnarray[0] << AGP_PAGE_SHIFT);
	}
	/* Update the memory pagse used */
	st->asoft_pgused += alloc_info.agpa_pgcount;

	if (ddi_copyout(&alloc_info, arg,
	    sizeof (agp_allocate_t), flags) != 0) {

		return (EFAULT);
	}

	return (0);
}

static int
ioctl_agpgart_dealloc(agpgart_softstate_t  *st, intptr_t arg)
{
	int key;
	keytable_ent_t  *keyent;

	if (is_controlling_proc(st) < 0) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_dealloc: not a controlling process"));
		return (EPERM);
	}
	key = (int)arg;
	if ((key >= AGP_MAXKEYS) || key < 0) {
		return (EINVAL);
	}
	keyent = &st->asoft_table[key];
	if (!keyent->kte_memhdl) {
		return (EINVAL);
	}

	if (agp_dealloc_mem(st, keyent))
		return (EINVAL);

	/* Update the memory pages used */
	st->asoft_pgused -= keyent->kte_pages;
	bzero(keyent, sizeof (keytable_ent_t));

	return (0);
}

static int
ioctl_agpgart_bind(agpgart_softstate_t  *st, void  *arg, int flags)
{
	agp_bind_t 	bind_info;
	keytable_ent_t	*keyent;
	int		key;
	uint32_t	pg_offset;
	int		retval = 0;

	if (is_controlling_proc(st) < 0) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_bind: not a controlling process"));
		return (EPERM);
	}

	if (ddi_copyin(arg, &bind_info, sizeof (agp_bind_t), flags) != 0) {
		return (EFAULT);
	}

	key = bind_info.agpb_key;
	if ((key >= AGP_MAXKEYS) || key < 0) {
		AGPDB_PRINT2((CE_WARN, "ioctl_agpgart_bind: invalid key"));
		return (EINVAL);
	}

	if (IS_INTEL_830(st->asoft_devreg.agprd_arctype)) {
		if (AGP_PAGES2KB(bind_info.agpb_pgstart) <
		    st->asoft_info.agpki_presize) {
			AGPDB_PRINT2((CE_WARN,
			    "ioctl_agpgart_bind: bind to prealloc area "
			    "pgstart = %dKB < presize = %ldKB",
			    AGP_PAGES2KB(bind_info.agpb_pgstart),
			    st->asoft_info.agpki_presize));
			return (EINVAL);
		}
	}

	pg_offset = bind_info.agpb_pgstart;
	keyent = &st->asoft_table[key];
	if (!keyent->kte_memhdl) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_bind: Key = 0x%x can't get keyenty",
		    key));
		return (EINVAL);
	}

	if (keyent->kte_bound != 0) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_bind: Key = 0x%x already bound",
		    key));
		return (EINVAL);
	}
	retval = agp_bind_key(st, keyent, pg_offset);

	if (retval == 0) {
		keyent->kte_pgoff = pg_offset;
		keyent->kte_bound = 1;
	}

	return (retval);
}

static int
ioctl_agpgart_unbind(agpgart_softstate_t  *st, void  *arg, int flags)
{
	int key, retval = 0;
	agp_unbind_t unbindinfo;
	keytable_ent_t *keyent;

	if (is_controlling_proc(st) < 0) {
		AGPDB_PRINT2((CE_WARN,
		    "ioctl_agpgart_bind: not a controlling process"));
		return (EPERM);
	}

	if (ddi_copyin(arg, &unbindinfo, sizeof (unbindinfo), flags) != 0) {
		return (EFAULT);
	}
	key = unbindinfo.agpu_key;
	if ((key >= AGP_MAXKEYS) || key < 0) {
		AGPDB_PRINT2((CE_WARN, "ioctl_agpgart_unbind: invalid key"));
		return (EINVAL);
	}
	keyent = &st->asoft_table[key];
	if (!keyent->kte_bound) {
		return (EINVAL);
	}

	if ((retval = agp_unbind_key(st, keyent)) != 0)
		return (retval);

	return (0);
}

static int
ioctl_agpgart_flush_chipset(agpgart_softstate_t *st)
{
	ldi_handle_t	hdl;
	uint32_t devid;
	int rc = 0;
	devid = st->asoft_info.agpki_mdevid;
	hdl = st->asoft_devreg.agprd_targethdl;
	if (IS_INTEL_915(devid) ||
	    IS_INTEL_965(devid) ||
	    IS_INTEL_X33(devid) ||
	    IS_INTEL_G4X(devid)) {
		rc = ldi_ioctl(hdl, INTEL_CHIPSET_FLUSH, 0, FKIOCTL, kcred, 0);
	}
	return	(rc);
}

static int
ioctl_agpgart_pages_bind(agpgart_softstate_t  *st, void  *arg, int flags)
{
	agp_bind_pages_t 	bind_info;
	uint32_t	pg_offset;
	int err = 0;
	ldi_handle_t hdl;
	uint32_t npages;
	igd_gtt_seg_t *gttseg;
	uint32_t i;
	int rval;
	if (ddi_copyin(arg, &bind_info,
	    sizeof (agp_bind_pages_t), flags) != 0) {
		return (EFAULT);
	}

	gttseg = (igd_gtt_seg_t *)kmem_zalloc(sizeof (igd_gtt_seg_t),
	    KM_SLEEP);

	pg_offset = bind_info.agpb_pgstart;

	gttseg->igs_pgstart =  pg_offset;
	npages = (uint32_t)bind_info.agpb_pgcount;
	gttseg->igs_npage = npages;

	gttseg->igs_type = AGP_NORMAL;
	gttseg->igs_phyaddr = (uint32_t *)kmem_zalloc
	    (sizeof (uint32_t) * gttseg->igs_npage, KM_SLEEP);

	for (i = 0; i < npages; i++) {
		gttseg->igs_phyaddr[i] = bind_info.agpb_pages[i] <<
		    GTT_PAGE_SHIFT;
	}

	hdl = st->asoft_devreg.agprd_masterhdl;
	if (ldi_ioctl(hdl, I8XX_ADD2GTT, (intptr_t)gttseg, FKIOCTL,
	    kcred, &rval)) {
		AGPDB_PRINT2((CE_WARN, "ioctl_agpgart_pages_bind: start0x%x",
		    gttseg->igs_pgstart));
		AGPDB_PRINT2((CE_WARN, "ioctl_agpgart_pages_bind: pages=0x%x",
		    gttseg->igs_npage));
		AGPDB_PRINT2((CE_WARN, "ioctl_agpgart_pages_bind: type=0x%x",
		    gttseg->igs_type));
		err = -1;
	}

	list_head_add_new(&st->mapped_list, gttseg);
	return (err);
}

static int
ioctl_agpgart_pages_unbind(agpgart_softstate_t  *st, void  *arg, int flags)
{
	agp_unbind_pages_t unbind_info;
	int	rval;
	ldi_handle_t	hdl;
	igd_gtt_seg_t	*gttseg;

	if (ddi_copyin(arg, &unbind_info, sizeof (unbind_info), flags) != 0) {
		return (EFAULT);
	}

	struct list_head  *entry, *temp;
	list_head_for_each_safe(entry, temp, &st->mapped_list) {
		if (entry->gttseg->igs_pgstart == unbind_info.agpb_pgstart) {
			gttseg = entry->gttseg;
			/* not unbind if VT switch */
			if (unbind_info.agpb_type) {
				list_head_del(entry);
				kmem_free(entry, sizeof (*entry));
			}
			break;
		}
	}
	ASSERT(gttseg != NULL);
	gttseg->igs_pgstart =  unbind_info.agpb_pgstart;
	ASSERT(gttseg->igs_npage == unbind_info.agpb_pgcount);

	hdl = st->asoft_devreg.agprd_masterhdl;
	if (ldi_ioctl(hdl, I8XX_REM_GTT, (intptr_t)gttseg, FKIOCTL,
	    kcred, &rval))
		return (-1);

	if (unbind_info.agpb_type) {
		kmem_free(gttseg->igs_phyaddr, sizeof (uint32_t) *
		    gttseg->igs_npage);
		kmem_free(gttseg, sizeof (igd_gtt_seg_t));
	}

	return (0);
}

static int
ioctl_agpgart_pages_rebind(agpgart_softstate_t  *st)
{
	int	rval;
	ldi_handle_t	hdl;
	igd_gtt_seg_t	*gttseg;
	int err = 0;

	hdl = st->asoft_devreg.agprd_masterhdl;
	struct list_head  *entry, *temp;
	list_head_for_each_safe(entry, temp, &st->mapped_list) {
		gttseg = entry->gttseg;
		list_head_del(entry);
		kmem_free(entry, sizeof (*entry));
		if (ldi_ioctl(hdl, I8XX_ADD2GTT, (intptr_t)gttseg, FKIOCTL,
		    kcred, &rval)) {
			AGPDB_PRINT2((CE_WARN, "agpgart_pages_rebind errori"));
			err = -1;
			break;
		}
		kmem_free(gttseg->igs_phyaddr, sizeof (uint32_t) *
		    gttseg->igs_npage);
		kmem_free(gttseg, sizeof (igd_gtt_seg_t));

	}
	return (err);

}

/*ARGSUSED*/
static int
agpgart_ioctl(dev_t dev, int cmd, intptr_t intarg, int flags,
    cred_t *credp, int *rvalp)
{
	int instance;
	int retval = 0;
	void *arg = (void*)intarg;

	agpgart_softstate_t *softstate;

	instance = AGP_DEV2INST(dev);
	softstate = ddi_get_soft_state(agpgart_glob_soft_handle, instance);
	if (softstate == NULL) {
		AGPDB_PRINT2((CE_WARN, "agpgart_ioctl: get soft state err"));
		return (ENXIO);
	}

	mutex_enter(&softstate->asoft_instmutex);

	switch (cmd) {
	case AGPIOC_INFO:
		retval = ioctl_agpgart_info(softstate, arg, flags);
		break;
	case AGPIOC_ACQUIRE:
		retval = ioctl_agpgart_acquire(softstate);
		break;
	case AGPIOC_RELEASE:
		retval = ioctl_agpgart_release(softstate);
		break;
	case AGPIOC_SETUP:
		retval = ioctl_agpgart_setup(softstate, arg, flags);
		break;
	case AGPIOC_ALLOCATE:
		retval = ioctl_agpgart_alloc(softstate, arg, flags);
		break;
	case AGPIOC_DEALLOCATE:
		retval = ioctl_agpgart_dealloc(softstate, intarg);
		break;
	case AGPIOC_BIND:
		retval = ioctl_agpgart_bind(softstate, arg, flags);
		break;
	case AGPIOC_UNBIND:
		retval = ioctl_agpgart_unbind(softstate, arg, flags);
		break;
	case AGPIOC_FLUSHCHIPSET:
		retval = ioctl_agpgart_flush_chipset(softstate);
		break;
	case AGPIOC_PAGES_BIND:
		retval = ioctl_agpgart_pages_bind(softstate, arg, flags);
		break;
	case AGPIOC_PAGES_UNBIND:
		retval = ioctl_agpgart_pages_unbind(softstate, arg, flags);
		break;
	case AGPIOC_PAGES_REBIND:
		retval = ioctl_agpgart_pages_rebind(softstate);
		break;
	default:
		AGPDB_PRINT2((CE_WARN, "agpgart_ioctl: wrong argument"));
		retval = ENXIO;
		break;
	}

	mutex_exit(&softstate->asoft_instmutex);
	return (retval);
}

static int
agpgart_segmap(dev_t dev, off_t off, struct as *asp,
    caddr_t *addrp, off_t len, unsigned int prot,
    unsigned int maxprot, unsigned int flags, cred_t *credp)
{

	struct agpgart_softstate *softstate;
	int instance;
	int rc = 0;

	instance = AGP_DEV2INST(dev);
	softstate = ddi_get_soft_state(agpgart_glob_soft_handle, instance);
	if (softstate == NULL) {
		AGPDB_PRINT2((CE_WARN, "agpgart_segmap: get soft state err"));
		return (ENXIO);
	}
	if (!AGP_ALIGNED(len))
		return (EINVAL);

	mutex_enter(&softstate->asoft_instmutex);

	rc = devmap_setup(dev, (offset_t)off, asp, addrp,
	    (size_t)len, prot, maxprot, flags, credp);

	mutex_exit(&softstate->asoft_instmutex);
	return (rc);
}

/*ARGSUSED*/
static int
agpgart_devmap(dev_t dev, devmap_cookie_t cookie, offset_t offset, size_t len,
    size_t *mappedlen, uint_t model)
{
	struct agpgart_softstate *softstate;
	int instance, status;
	struct keytable_ent *mementry;
	offset_t local_offset;

	instance = AGP_DEV2INST(dev);
	softstate = ddi_get_soft_state(agpgart_glob_soft_handle, instance);
	if (softstate == NULL) {
		AGPDB_PRINT2((CE_WARN, "agpgart_devmap: get soft state err"));
		return (ENXIO);
	}


	if (offset > MB2BYTES(softstate->asoft_info.agpki_apersize)) {
		AGPDB_PRINT2((CE_WARN, "agpgart_devmap: offset is too large"));
		return (EINVAL);
	}

	/*
	 * Can not find any memory now, so fail.
	 */

	mementry = agp_find_bound_keyent(softstate, AGP_BYTES2PAGES(offset));

	if (mementry == NULL) {
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_devmap: can not find the proper keyent"));
		return (EINVAL);
	}

	local_offset = offset - AGP_PAGES2BYTES(mementry->kte_pgoff);

	if (len > (AGP_PAGES2BYTES(mementry->kte_pages) - local_offset)) {
		len = AGP_PAGES2BYTES(mementry->kte_pages) - local_offset;
	}

	switch (mementry->kte_type) {
	case AGP_NORMAL:
		if (PMEMP(mementry->kte_memhdl)->pmem_cookie) {
			status = devmap_pmem_setup(cookie,
			    softstate->asoft_dip,
			    &agp_devmap_cb,
			    PMEMP(mementry->kte_memhdl)->pmem_cookie,
			    local_offset,
			    len, PROT_ALL,
			    (DEVMAP_DEFAULTS|IOMEM_DATA_UC_WR_COMBINE),
			    &mem_dev_acc_attr);
		} else {
			AGPDB_PRINT2((CE_WARN,
			    "agpgart_devmap: not a valid memory type"));
			return (EINVAL);

		}

		break;
	default:
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_devmap: not a valid memory type"));
		return (EINVAL);
	}


	if (status == 0) {
		*mappedlen = len;
	} else {
		*mappedlen = 0;
		AGPDB_PRINT2((CE_WARN,
		    "agpgart_devmap: devmap interface failed"));
		return (EINVAL);
	}

	return (0);
}

static struct cb_ops	agpgart_cb_ops = {
	agpgart_open,		/* open() */
	agpgart_close,		/* close() */
	nodev,			/* strategy() */
	nodev,			/* print routine */
	nodev,			/* no dump routine */
	nodev,			/* read() */
	nodev,			/* write() */
	agpgart_ioctl,		/* agpgart_ioctl */
	agpgart_devmap,		/* devmap routine */
	nodev,			/* no longer use mmap routine */
	agpgart_segmap,		/* system segmap routine */
	nochpoll,		/* no chpoll routine */
	ddi_prop_op,		/* system prop operations */
	0,			/* not a STREAMS driver */
	D_DEVMAP | D_MP,	/* safe for multi-thread/multi-processor */
	CB_REV,			/* cb_ops version? */
	nodev,			/* cb_aread() */
	nodev,			/* cb_awrite() */
};

static struct dev_ops agpgart_ops = {
	DEVO_REV,		/* devo_rev */
	0,			/* devo_refcnt */
	agpgart_getinfo,	/* devo_getinfo */
	nulldev,		/* devo_identify */
	nulldev,		/* devo_probe */
	agpgart_attach,		/* devo_attach */
	agpgart_detach,		/* devo_detach */
	nodev,			/* devo_reset */
	&agpgart_cb_ops,	/* devo_cb_ops */
	(struct bus_ops *)0,	/* devo_bus_ops */
	NULL,			/* devo_power */
	ddi_quiesce_not_needed,	/* devo_quiesce */
};

static	struct modldrv modldrv = {
	&mod_driverops,
	"AGP driver",
	&agpgart_ops,
};

static struct modlinkage modlinkage = {
	MODREV_1,		/* MODREV_1 is indicated by manual */
	{&modldrv, NULL, NULL, NULL}
};

static void *agpgart_glob_soft_handle;

int
_init(void)
{
	int ret = DDI_SUCCESS;

	ret = ddi_soft_state_init(&agpgart_glob_soft_handle,
	    sizeof (agpgart_softstate_t),
	    AGPGART_MAX_INSTANCES);

	if (ret != 0) {
		AGPDB_PRINT2((CE_WARN,
		    "_init: soft state init error code=0x%x", ret));
		return (ret);
	}

	if ((ret = mod_install(&modlinkage)) != 0) {
		AGPDB_PRINT2((CE_WARN,
		    "_init: mod install error code=0x%x", ret));
		ddi_soft_state_fini(&agpgart_glob_soft_handle);
		return (ret);
	}

	return (DDI_SUCCESS);
}

int
_info(struct modinfo *modinfop)
{
	return (mod_info(&modlinkage, modinfop));
}

int
_fini(void)
{
	int ret;

	if ((ret = mod_remove(&modlinkage)) == 0) {
		ddi_soft_state_fini(&agpgart_glob_soft_handle);
	}

	return (ret);
}