aboutsummaryrefslogtreecommitdiff
path: root/drivers/mxc/gpu-viv/hal/kernel/gc_hal_kernel_command_vg.c
blob: 68b2d60298c1865099c1a3cc841760f705acaf9b (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
/****************************************************************************
*
*    Copyright (C) 2005 - 2011 by Vivante Corp.
*
*    This program is free software; you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation; either version 2 of the license, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program; if not write to the Free Software
*    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/




#include "gc_hal_kernel_precomp.h"

#if gcdENABLE_VG

#include "gc_hal_kernel_hardware_command_vg.h"

#define _GC_OBJ_ZONE            gcvZONE_COMMAND

/******************************************************************************\
*********************************** Debugging **********************************
\******************************************************************************/

#define gcvDISABLE_TIMEOUT      1
#define gcvDUMP_COMMAND_BUFFER  0
#define gcvDUMP_COMMAND_LINES   0


#if gcvDEBUG || defined(EMULATOR) || gcvDISABLE_TIMEOUT
#   define gcvQUEUE_TIMEOUT ~0
#else
#   define gcvQUEUE_TIMEOUT 10
#endif


/******************************************************************************\
********************************** Definitions *********************************
\******************************************************************************/

/* Minimum buffer size. */
#define gcvMINUMUM_BUFFER \
    gcmSIZEOF(gcsKERNEL_QUEUE_HEADER) + \
    gcmSIZEOF(gcsKERNEL_CMDQUEUE) * 2

#define gcmDECLARE_INTERRUPT_HANDLER(Block, Number) \
    static gceSTATUS \
    _EventHandler_##Block##_##Number( \
        IN gckVGKERNEL Kernel \
        )

#define gcmDEFINE_INTERRUPT_HANDLER(Block, Number) \
    gcmDECLARE_INTERRUPT_HANDLER(Block, Number) \
    { \
        return _EventHandler_Block( \
            Kernel, \
            &Kernel->command->taskTable[gcvBLOCK_##Block], \
            gcvFALSE \
            ); \
    }

#define gcmDEFINE_INTERRUPT_HANDLER_ENTRY(Block, Number) \
    { gcvBLOCK_##Block, _EventHandler_##Block##_##Number }

/* Block interrupt handling table entry. */
typedef struct _gcsBLOCK_INTERRUPT_HANDLER * gcsBLOCK_INTERRUPT_HANDLER_PTR;
typedef struct _gcsBLOCK_INTERRUPT_HANDLER
{
    gceBLOCK                block;
    gctINTERRUPT_HANDLER    handler;
}
gcsBLOCK_INTERRUPT_HANDLER;

/* Queue control functions. */
typedef struct _gcsQUEUE_UPDATE_CONTROL * gcsQUEUE_UPDATE_CONTROL_PTR;
typedef struct _gcsQUEUE_UPDATE_CONTROL
{
    gctOBJECT_HANDLER       execute;
    gctOBJECT_HANDLER       update;
    gctOBJECT_HANDLER       lastExecute;
    gctOBJECT_HANDLER       lastUpdate;
}
gcsQUEUE_UPDATE_CONTROL;


/******************************************************************************\
********************************* Support Code *********************************
\******************************************************************************/

static gceSTATUS
_WaitForIdle(
    IN gckVGCOMMAND Command,
    IN gcsKERNEL_QUEUE_HEADER_PTR Queue
    )
{
    gceSTATUS status = gcvSTATUS_OK;
    gctUINT32 idle;
    gctUINT timeout = 0;

    /* Loop while not idle. */
    while (Queue->pending)
    {
        /* Did we reach the timeout limit? */
        if (timeout == gcvQUEUE_TIMEOUT)
        {
            /* Hardware is probably dead... */
            return gcvSTATUS_TIMEOUT;
        }

        /* Sleep for 100ms. */
        gcmkERR_BREAK(gckOS_Delay(Command->os, 100));

        /* Not the first loop? */
        if (timeout > 0)
        {
            /* Read IDLE register. */
            gcmkVERIFY_OK(gckVGHARDWARE_GetIdle(Command->hardware, &idle));

            gcmkTRACE_ZONE(
                gcvLEVEL_ERROR, gcvZONE_COMMAND,
                "%s: timeout, IDLE=%08X\n",
                __FUNCTION__, idle
                );
        }

        /* Increment the timeout counter. */
        timeout += 1;
    }

    /* Return status. */
    return status;
}

static gctINT32
_GetNextInterrupt(
    IN gckVGCOMMAND Command,
    IN gceBLOCK Block
    )
{
    gctUINT index;
    gcsBLOCK_TASK_ENTRY_PTR entry;
    gctINT32 interrupt;

    /* Get the block entry. */
    entry = &Command->taskTable[Block];

    /* Make sure we have initialized interrupts. */
    gcmkASSERT(entry->interruptCount > 0);

    /* Decrement the interrupt usage semaphore. */
    gcmkVERIFY_OK(gckOS_DecrementSemaphore(
        Command->os, entry->interruptSemaphore
        ));

    /* Get the value index. */
    index = entry->interruptIndex;

    /* Get the interrupt value. */
    interrupt = entry->interruptArray[index];

    /* Must be a valid value. */
    gcmkASSERT((interrupt >= 0) && (interrupt <= 31));

    /* Advance the index to the next value. */
    index += 1;

    /* Set the new index. */
    entry->interruptIndex = (index == entry->interruptCount)
        ? 0
        : index;

    /* Return interrupt value. */
    return interrupt;
}


/******************************************************************************\
***************************** Task Storage Management **************************
\******************************************************************************/

/* Minimum task buffer size. */
#define gcvMIN_TASK_BUFFER \
( \
    gcmSIZEOF(gcsTASK_CONTAINER) + 128 \
)

/* Free list terminator. */
#define gcvFREE_TASK_TERMINATOR \
( \
    (gcsTASK_CONTAINER_PTR) gcmINT2PTR(~0) \
)


/*----------------------------------------------------------------------------*/
/*------------------- Allocated Task Buffer List Management ------------------*/

static void
_InsertTaskBuffer(
    IN gcsTASK_CONTAINER_PTR AddAfter,
    IN gcsTASK_CONTAINER_PTR Buffer
    )
{
    gcsTASK_CONTAINER_PTR addBefore;

    /* Cannot add before the first buffer. */
    gcmkASSERT(AddAfter != gcvNULL);

    /* Create a shortcut to the next buffer. */
    addBefore = AddAfter->allocNext;

    /* Initialize the links. */
    Buffer->allocPrev = AddAfter;
    Buffer->allocNext = addBefore;

    /* Link to the previous buffer. */
    AddAfter->allocNext = Buffer;

    /* Link to the next buffer. */
    if (addBefore != gcvNULL)
    {
        addBefore->allocPrev = Buffer;
    }
}

static void
_RemoveTaskBuffer(
    IN gcsTASK_CONTAINER_PTR Buffer
    )
{
    gcsTASK_CONTAINER_PTR prev;
    gcsTASK_CONTAINER_PTR next;

    /* Cannot remove the first buffer. */
    gcmkASSERT(Buffer->allocPrev != gcvNULL);

    /* Create shortcuts to the previous and next buffers. */
    prev = Buffer->allocPrev;
    next = Buffer->allocNext;

    /* Tail buffer? */
    if (next == gcvNULL)
    {
        /* Remove from the list. */
        prev->allocNext = gcvNULL;
    }

    /* Buffer from the middle. */
    else
    {
        prev->allocNext = next;
        next->allocPrev = prev;
    }
}


/*----------------------------------------------------------------------------*/
/*--------------------- Free Task Buffer List Management ---------------------*/

static void
_AppendToFreeList(
    IN gckVGCOMMAND Command,
    IN gcsTASK_CONTAINER_PTR Buffer
    )
{
    /* Cannot be a part of the free list already. */
    gcmkASSERT(Buffer->freePrev == gcvNULL);
    gcmkASSERT(Buffer->freeNext == gcvNULL);

    /* First buffer to add? */
    if (Command->taskFreeHead == gcvNULL)
    {
        /* Terminate the links. */
        Buffer->freePrev = gcvFREE_TASK_TERMINATOR;
        Buffer->freeNext = gcvFREE_TASK_TERMINATOR;

        /* Initialize the list pointer. */
        Command->taskFreeHead = Command->taskFreeTail = Buffer;
    }

    /* Not the first, add after the tail. */
    else
    {
        /* Initialize the new tail buffer. */
        Buffer->freePrev = Command->taskFreeTail;
        Buffer->freeNext = gcvFREE_TASK_TERMINATOR;

        /* Add after the tail. */
        Command->taskFreeTail->freeNext = Buffer;
        Command->taskFreeTail = Buffer;
    }
}

static void
_RemoveFromFreeList(
    IN gckVGCOMMAND Command,
    IN gcsTASK_CONTAINER_PTR Buffer
    )
{
    /* Has to be a part of the free list. */
    gcmkASSERT(Buffer->freePrev != gcvNULL);
    gcmkASSERT(Buffer->freeNext != gcvNULL);

    /* Head buffer? */
    if (Buffer->freePrev == gcvFREE_TASK_TERMINATOR)
    {
        /* Tail buffer as well? */
        if (Buffer->freeNext == gcvFREE_TASK_TERMINATOR)
        {
            /* Reset the list pointer. */
            Command->taskFreeHead = Command->taskFreeTail = gcvNULL;
        }

        /* No, just the head. */
        else
        {
            /* Update the head. */
            Command->taskFreeHead = Buffer->freeNext;

            /* Terminate the next buffer. */
            Command->taskFreeHead->freePrev = gcvFREE_TASK_TERMINATOR;
        }
    }

    /* Not the head. */
    else
    {
        /* Tail buffer? */
        if (Buffer->freeNext == gcvFREE_TASK_TERMINATOR)
        {
            /* Update the tail. */
            Command->taskFreeTail = Buffer->freePrev;

            /* Terminate the previous buffer. */
            Command->taskFreeTail->freeNext = gcvFREE_TASK_TERMINATOR;
        }

        /* A buffer in the middle. */
        else
        {
            /* Remove the buffer from the list. */
            Buffer->freePrev->freeNext = Buffer->freeNext;
            Buffer->freeNext->freePrev = Buffer->freePrev;
        }
    }

    /* Reset free list pointers. */
    Buffer->freePrev = gcvNULL;
    Buffer->freeNext = gcvNULL;
}


/*----------------------------------------------------------------------------*/
/*-------------------------- Task Buffer Allocation --------------------------*/

static void
_SplitTaskBuffer(
    IN gckVGCOMMAND Command,
    IN gcsTASK_CONTAINER_PTR Buffer,
    IN gctUINT Size
    )
{
    /* Determine the size of the new buffer. */
    gctINT splitBufferSize = Buffer->size - Size;
    gcmkASSERT(splitBufferSize >= 0);

    /* Is the split buffer big enough to become a separate buffer? */
    if (splitBufferSize >= gcvMIN_TASK_BUFFER)
    {
        /* Place the new path data. */
        gcsTASK_CONTAINER_PTR splitBuffer = (gcsTASK_CONTAINER_PTR)
        (
            (gctUINT8_PTR) Buffer + Size
        );

        /* Set the trimmed buffer size. */
        Buffer->size = Size;

        /* Initialize the split buffer. */
        splitBuffer->referenceCount = 0;
        splitBuffer->size           = splitBufferSize;
        splitBuffer->freePrev       = gcvNULL;
        splitBuffer->freeNext       = gcvNULL;

        /* Link in. */
        _InsertTaskBuffer(Buffer, splitBuffer);
        _AppendToFreeList(Command, splitBuffer);
    }
}

static gceSTATUS
_AllocateTaskContainer(
    IN gckVGCOMMAND Command,
    IN gctUINT Size,
    OUT gcsTASK_CONTAINER_PTR * Buffer
    )
{
    gceSTATUS status;

    gcmkHEADER_ARG("Command=0x%x Size=0x%x, Buffer ==0x%x", Command, Size, Buffer);

    /* Verify arguments. */
    gcmkVERIFY_ARGUMENT(Buffer != gcvNULL);

    do
    {
        gcsTASK_STORAGE_PTR storage;
        gcsTASK_CONTAINER_PTR buffer;

        /* Adjust the size. */
        Size += gcmSIZEOF(gcsTASK_CONTAINER);

        /* Adjust the allocation size if not big enough. */
        if (Size > Command->taskStorageUsable)
        {
            Command->taskStorageGranularity
                = gcmALIGN(Size + gcmSIZEOF(gcsTASK_STORAGE), 1024);

            Command->taskStorageUsable
                = Command->taskStorageGranularity - gcmSIZEOF(gcsTASK_STORAGE);
        }

        /* Is there a free buffer available? */
        else if (Command->taskFreeHead != gcvNULL)
        {
            /* Set the initial free buffer. */
            gcsTASK_CONTAINER_PTR buffer = Command->taskFreeHead;

            do
            {
                /* Is the buffer big enough? */
                if (buffer->size >= Size)
                {
                    /* Remove the buffer from the free list. */
                    _RemoveFromFreeList(Command, buffer);

                    /* Split the buffer. */
                    _SplitTaskBuffer(Command, buffer, Size);

                    /* Set the result. */
                    * Buffer = buffer;

                    /* Success. */
                    return gcvSTATUS_OK;
                }

                /* Get the next free buffer. */
                buffer = buffer->freeNext;
            }
            while (buffer != gcvFREE_TASK_TERMINATOR);
        }

        /* Allocate a container. */
        gcmkERR_BREAK(gckOS_Allocate(
            Command->os,
            Command->taskStorageGranularity,
            (gctPOINTER *) &storage
            ));

        /* Link in the storage buffer. */
        storage->next = Command->taskStorage;
        Command->taskStorage = storage;

        /* Place the task buffer. */
        buffer = (gcsTASK_CONTAINER_PTR) (storage + 1);

        /* Determine the size of the buffer. */
        buffer->size
            = Command->taskStorageGranularity
            - gcmSIZEOF(gcsTASK_STORAGE);

        /* Initialize the task buffer. */
        buffer->referenceCount = 0;
        buffer->allocPrev      = gcvNULL;
        buffer->allocNext      = gcvNULL;
        buffer->freePrev       = gcvNULL;
        buffer->freeNext       = gcvNULL;

        /* Split the buffer. */
        _SplitTaskBuffer(Command, buffer, Size);

        /* Set the result. */
        * Buffer = buffer;

        /* Success. */
        return gcvSTATUS_OK;
    }
    while (gcvFALSE);

    gcmkFOOTER();
    /* Return status. */
    return status;
}

static void
_FreeTaskContainer(
    IN gckVGCOMMAND Command,
    IN gcsTASK_CONTAINER_PTR Buffer
    )
{
    gcsTASK_CONTAINER_PTR prev;
    gcsTASK_CONTAINER_PTR next;
    gcsTASK_CONTAINER_PTR merged;

    gctSIZE_T mergedSize;

    /* Verify arguments. */
    gcmkASSERT(Buffer != gcvNULL);
    gcmkASSERT(Buffer->freePrev == gcvNULL);
    gcmkASSERT(Buffer->freeNext == gcvNULL);

    /* Get shortcuts to the previous and next path data buffers. */
    prev = Buffer->allocPrev;
    next = Buffer->allocNext;

    /* Is the previous path data buffer already free? */
    if (prev && prev->freeNext)
    {
        /* The previous path data buffer is the one that remains. */
        merged = prev;

        /* Is the next path data buffer already free? */
        if (next && next->freeNext)
        {
            /* Merge all three path data buffers into the previous. */
            mergedSize = prev->size + Buffer->size + next->size;

            /* Remove the next path data buffer. */
            _RemoveFromFreeList(Command, next);
            _RemoveTaskBuffer(next);
        }
        else
        {
            /* Merge the current path data buffer into the previous. */
            mergedSize = prev->size + Buffer->size;
        }

        /* Delete the current path data buffer. */
        _RemoveTaskBuffer(Buffer);

        /* Set new size. */
        merged->size = mergedSize;
    }
    else
    {
        /* The current path data buffer is the one that remains. */
        merged = Buffer;

        /* Is the next buffer already free? */
        if (next && next->freeNext)
        {
            /* Merge the next into the current. */
            mergedSize = Buffer->size + next->size;

            /* Remove the next buffer. */
            _RemoveFromFreeList(Command, next);
            _RemoveTaskBuffer(next);

            /* Set new size. */
            merged->size = mergedSize;
        }

        /* Add the current buffer into the free list. */
        _AppendToFreeList(Command, merged);
    }
}


/******************************************************************************\
********************************* Task Scheduling ******************************
\******************************************************************************/

static gceSTATUS
_ScheduleTasks(
    IN gckVGCOMMAND Command,
    IN gcsTASK_MASTER_TABLE_PTR TaskTable,
    IN gctUINT8_PTR PreviousEnd
    )
{
    gceSTATUS status;

    do
    {
        gctINT block;
        gcsTASK_CONTAINER_PTR container;
        gcsTASK_MASTER_ENTRY_PTR userTaskEntry;
        gcsBLOCK_TASK_ENTRY_PTR kernelTaskEntry;
        gcsTASK_PTR userTask;
        gctUINT8_PTR kernelTask;
        gctINT32 interrupt;
        gctUINT8_PTR eventCommand;

        /* Nothing to schedule? */
        if (TaskTable->size == 0)
        {
            status = gcvSTATUS_OK;
            break;
        }

        /* Acquire the mutex. */
        gcmkERR_BREAK(gckOS_AcquireMutex(
            Command->os,
            Command->taskMutex,
            gcvINFINITE
            ));

        gcmkTRACE_ZONE(
            gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
            "%s(%d)\n",
            __FUNCTION__, __LINE__
            );

        do
        {
            gcmkTRACE_ZONE(
                gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
                "  number of tasks scheduled   = %d\n"
                "  size of event data in bytes = %d\n",
                TaskTable->count,
                TaskTable->size
                );

            /* Allocate task buffer. */
            gcmkERR_BREAK(_AllocateTaskContainer(
                Command,
                TaskTable->size,
                &container
                ));

            /* Determine the task data pointer. */
            kernelTask = (gctUINT8_PTR) (container + 1);

            /* Initialize the reference count. */
            container->referenceCount = TaskTable->count;

            /* Process tasks. */
            for (block = gcvBLOCK_COUNT - 1; block >= 0; block -= 1)
            {
                /* Get the current user table entry. */
                userTaskEntry = &TaskTable->table[block];

                /* Are there tasks scheduled? */
                if (userTaskEntry->head == gcvNULL)
                {
                    /* No, skip to the next block. */
                    continue;
                }

                gcmkTRACE_ZONE(
                    gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
                    "  processing tasks for block %d\n",
                    block
                    );

                /* Get the current kernel table entry. */
                kernelTaskEntry = &Command->taskTable[block];

                /* Are there tasks for the current block scheduled? */
                if (kernelTaskEntry->container == gcvNULL)
                {
                    gcmkTRACE_ZONE(
                        gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
                        "  first task container for the block added\n",
                        block
                        );

                    /* Nothing yet, set the container buffer pointer. */
                    kernelTaskEntry->container = container;
                    kernelTaskEntry->task      = (gcsTASK_HEADER_PTR) kernelTask;
                }

                /* Yes, append to the end. */
                else
                {
                    kernelTaskEntry->link->cotainer = container;
                    kernelTaskEntry->link->task     = (gcsTASK_HEADER_PTR) kernelTask;
                }

                /* Set initial task. */
                userTask = userTaskEntry->head;

                gcmkTRACE_ZONE(
                    gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
                    "  copying user tasks over to the kernel\n"
                    );

                /* Copy tasks. */
                do
                {
                    gcmkTRACE_ZONE(
                        gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
                        "    task ID = %d, size = %d\n",
                        ((gcsTASK_HEADER_PTR) (userTask + 1))->id,
                        userTask->size
                        );

                    /* Copy the task data. */
                    gcmkVERIFY_OK(gckOS_MemCopy(
                        kernelTask, userTask + 1, userTask->size
                        ));

                    /* Advance to the next task. */
                    kernelTask += userTask->size;
                    userTask    = userTask->next;
                }
                while (userTask != gcvNULL);

                /* Update link pointer in the header. */
                kernelTaskEntry->link = (gcsTASK_LINK_PTR) kernelTask;

                /* Initialize link task. */
                kernelTaskEntry->link->id       = gcvTASK_LINK;
                kernelTaskEntry->link->cotainer = gcvNULL;
                kernelTaskEntry->link->task     = gcvNULL;

                /* Advance the task data pointer. */
                kernelTask += gcmSIZEOF(gcsTASK_LINK);
            }
        }
        while (gcvFALSE);

        /* Release the mutex. */
        gcmkERR_BREAK(gckOS_ReleaseMutex(
            Command->os,
            Command->taskMutex
            ));

        /* Assign interrupts to the blocks. */
        eventCommand = PreviousEnd;

        for (block = gcvBLOCK_COUNT - 1; block >= 0; block -= 1)
        {
            /* Get the current user table entry. */
            userTaskEntry = &TaskTable->table[block];

            /* Are there tasks scheduled? */
            if (userTaskEntry->head == gcvNULL)
            {
                /* No, skip to the next block. */
                continue;
            }

            /* Get the interrupt number. */
            interrupt = _GetNextInterrupt(Command, block);

            gcmkTRACE_ZONE(
                gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
                "%s(%d): block = %d interrupt = %d\n",
                __FUNCTION__, __LINE__,
                block, interrupt
                );

            /* Determine the command position. */
            eventCommand -= Command->info.eventCommandSize;

            /* Append an EVENT command. */
            gcmkERR_BREAK(gckVGCOMMAND_EventCommand(
                Command, eventCommand, block, interrupt, gcvNULL
                ));
        }
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}


/******************************************************************************\
******************************** Memory Management *****************************
\******************************************************************************/

static gceSTATUS
_HardwareToKernel(
    IN gckOS Os,
    IN gcuVIDMEM_NODE_PTR Node,
    IN gctUINT32 Address,
    OUT gctPOINTER * KernelPointer
    )
{
    gceSTATUS status;
    gckVIDMEM memory;
    gctUINT32 offset;

    /* Assume a non-virtual node and get the pool manager object. */
    memory = Node->VidMem.memory;

    /* Determine the header offset within the pool it is allocated in. */
    offset = Address - memory->baseAddress;

    /* Translate the offset into the kernel side pointer. */
    status = gckOS_GetKernelLogicalEx(
        Os,
        gcvCORE_VG,
        offset,
        KernelPointer
        );

    /* Return status. */
    return status;
}

static gceSTATUS
_ConvertUserCommandBufferPointer(
    IN gckVGCOMMAND Command,
    IN gcsCMDBUFFER_PTR UserCommandBuffer,
    OUT gcsCMDBUFFER_PTR * KernelCommandBuffer
    )
{
    gceSTATUS status, last;
    gcsCMDBUFFER_PTR mappedUserCommandBuffer = gcvNULL;

    do
    {
        gctUINT32 headerAddress;

        /* Map the command buffer structure into the kernel space. */
        gcmkERR_BREAK(gckOS_MapUserPointer(
            Command->os,
            UserCommandBuffer,
            gcmSIZEOF(gcsCMDBUFFER),
            (gctPOINTER *) &mappedUserCommandBuffer
            ));

        /* Determine the address of the header. */
        headerAddress
            = mappedUserCommandBuffer->address
            - mappedUserCommandBuffer->bufferOffset;

        /* Translate the logical address to the kernel space. */
        gcmkERR_BREAK(_HardwareToKernel(
            Command->os,
            mappedUserCommandBuffer->node,
            headerAddress,
            (gctPOINTER *) KernelCommandBuffer
            ));
    }
    while (gcvFALSE);

    /* Unmap the user command buffer. */
    if (mappedUserCommandBuffer != gcvNULL)
    {
        gcmkCHECK_STATUS(gckOS_UnmapUserPointer(
            Command->os,
            UserCommandBuffer,
            gcmSIZEOF(gcsCMDBUFFER),
            mappedUserCommandBuffer
            ));
    }

    /* Return status. */
    return status;
}

static gceSTATUS
_AllocateLinear(
    IN gckVGCOMMAND Command,
    IN gctUINT Size,
    IN gctUINT Alignment,
    OUT gcuVIDMEM_NODE_PTR * Node,
    OUT gctUINT32 * Address,
    OUT gctPOINTER * Logical
    )
{
    gceSTATUS status, last;
    gcuVIDMEM_NODE_PTR node = gcvNULL;
    gctUINT32 address = (gctUINT32)~0;

    do
    {
        gcePOOL pool;
        gctPOINTER logical;

        /* Allocate from the system pool. */
        pool = gcvPOOL_SYSTEM;

        /* Allocate memory. */
        gcmkERR_BREAK(gckKERNEL_AllocateLinearMemory(
            Command->kernel->kernel, &pool,
            Size, Alignment,
            gcvSURF_TYPE_UNKNOWN,
            &node
            ));

        /* Do not accept virtual pools for now because we don't handle the
           kernel pointer translation at the moment. */
        if (pool == gcvPOOL_VIRTUAL)
        {
            status = gcvSTATUS_OUT_OF_MEMORY;
            break;
        }

        /* Lock the command buffer. */
        gcmkERR_BREAK(gckVIDMEM_Lock(
            Command->kernel->kernel,
            node,
            gcvFALSE,
            &address
            ));

        /* Translate the logical address to the kernel space. */
        gcmkERR_BREAK(_HardwareToKernel(
            Command->os,
            node,
            address,
            &logical
            ));

        /* Set return values. */
        * Node    = node;
        * Address = address;
        * Logical = logical;

        /* Success. */
        return gcvSTATUS_OK;
    }
    while (gcvFALSE);

    /* Roll back. */
    if (node != gcvNULL)
    {
        /* Unlock the command buffer. */
        if (address != ~0)
        {
            gcmkCHECK_STATUS(gckVIDMEM_Unlock(
                Command->kernel->kernel, node, gcvSURF_TYPE_UNKNOWN, gcvNULL
                ));
        }

        /* Free the command buffer. */
        gcmkCHECK_STATUS(gckVIDMEM_Free(
            node
            ));
    }

    /* Return status. */
    return status;
}

static gceSTATUS
_FreeLinear(
    IN gckVGKERNEL Kernel,
    IN gcuVIDMEM_NODE_PTR Node
    )
{
    gceSTATUS status;

    do
    {
        /* Unlock the linear buffer. */
        gcmkERR_BREAK(gckVIDMEM_Unlock(Kernel->kernel, Node, gcvSURF_TYPE_UNKNOWN, gcvNULL));

        /* Free the linear buffer. */
        gcmkERR_BREAK(gckVIDMEM_Free(Node));
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

gceSTATUS
_AllocateCommandBuffer(
    IN gckVGCOMMAND Command,
    IN gctSIZE_T Size,
    OUT gcsCMDBUFFER_PTR * CommandBuffer
    )
{
    gceSTATUS status, last;
    gcuVIDMEM_NODE_PTR node = gcvNULL;

    do
    {
        gctUINT alignedHeaderSize;
        gctUINT requestedSize;
        gctUINT allocationSize;
        gctUINT32 address = 0;
        gcsCMDBUFFER_PTR commandBuffer;
        gctUINT8_PTR endCommand;

        /* Determine the aligned header size. */
        alignedHeaderSize
            = gcmALIGN(gcmSIZEOF(gcsCMDBUFFER), Command->info.addressAlignment);

        /* Align the requested size. */
        requestedSize
            = gcmALIGN(Size, Command->info.commandAlignment);

        /* Determine the size of the buffer to allocate. */
        allocationSize
            = alignedHeaderSize
            + requestedSize
            + Command->info.staticTailSize;

        /* Allocate the command buffer. */
        gcmkERR_BREAK(_AllocateLinear(
            Command,
            allocationSize,
            Command->info.addressAlignment,
            &node,
            &address,
            (gctPOINTER *) &commandBuffer
            ));

        /* Initialize the structure. */
        commandBuffer->completion    = gcvVACANT_BUFFER;
        commandBuffer->node          = node;
        commandBuffer->address       = address + alignedHeaderSize;
        commandBuffer->bufferOffset  = alignedHeaderSize;
        commandBuffer->size          = requestedSize;
        commandBuffer->offset        = requestedSize;
        commandBuffer->nextAllocated = gcvNULL;
        commandBuffer->nextSubBuffer = gcvNULL;

        /* Determine the data count. */
        commandBuffer->dataCount
            = (requestedSize + Command->info.staticTailSize)
            / Command->info.commandAlignment;

        /* Determine the location of the END command. */
        endCommand
            = (gctUINT8_PTR) commandBuffer
            + alignedHeaderSize
            + requestedSize;

        /* Append an END command. */
        gcmkERR_BREAK(gckVGCOMMAND_EndCommand(
            Command,
            endCommand,
            Command->info.feBufferInt,
            gcvNULL
            ));

        /* Set the return pointer. */
        * CommandBuffer = commandBuffer;

        /* Success. */
        return gcvSTATUS_OK;
    }
    while (gcvFALSE);

    /* Roll back. */
    if (node != gcvNULL)
    {
        /* Free the command buffer. */
        gcmkCHECK_STATUS(_FreeLinear(Command->kernel, node));
    }

    /* Return status. */
    return status;
}

static gceSTATUS
_FreeCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsCMDBUFFER_PTR CommandBuffer
    )
{
    gceSTATUS status;

    /* Free the buffer. */
    status = _FreeLinear(Kernel, CommandBuffer->node);

    /* Return status. */
    return status;
}


/******************************************************************************\
****************************** TS Overflow Handler *****************************
\******************************************************************************/

static gceSTATUS
_EventHandler_TSOverflow(
    IN gckVGKERNEL Kernel
    )
{
    gcmkTRACE(
        gcvLEVEL_ERROR,
        "%s(%d): **** TS OVERFLOW ENCOUNTERED ****\n",
        __FUNCTION__, __LINE__
        );

    return gcvSTATUS_OK;
}


/******************************************************************************\
****************************** Bus Error Handler *******************************
\******************************************************************************/

static gceSTATUS
_EventHandler_BusError(
    IN gckVGKERNEL Kernel
    )
{
    gcmkTRACE(
        gcvLEVEL_ERROR,
        "%s(%d): **** BUS ERROR ENCOUNTERED ****\n",
        __FUNCTION__, __LINE__
        );

    return gcvSTATUS_OK;
}


/******************************************************************************\
******************************** Task Routines *********************************
\******************************************************************************/

typedef gceSTATUS (* gctTASKROUTINE) (
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskLink(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskCluster(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskIncrement(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskDecrement(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskSignal(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskLockdown(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskUnlockVideoMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskFreeVideoMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskFreeContiguousMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskUnmapUserMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gceSTATUS
_TaskUnmapMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    );

static gctTASKROUTINE _taskRoutine[] =
{
    _TaskLink,                  /* gcvTASK_LINK                   */
    _TaskCluster,               /* gcvTASK_CLUSTER                */
    _TaskIncrement,             /* gcvTASK_INCREMENT              */
    _TaskDecrement,             /* gcvTASK_DECREMENT              */
    _TaskSignal,                /* gcvTASK_SIGNAL                 */
    _TaskLockdown,              /* gcvTASK_LOCKDOWN               */
    _TaskUnlockVideoMemory,     /* gcvTASK_UNLOCK_VIDEO_MEMORY    */
    _TaskFreeVideoMemory,       /* gcvTASK_FREE_VIDEO_MEMORY      */
    _TaskFreeContiguousMemory,  /* gcvTASK_FREE_CONTIGUOUS_MEMORY */
    _TaskUnmapUserMemory,       /* gcvTASK_UNMAP_USER_MEMORY      */
    _TaskUnmapMemory,           /* gcvTASK_UNMAP_MEMORY           */
};

static gceSTATUS
_TaskLink(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    /* Cast the task pointer. */
    gcsTASK_LINK_PTR task = (gcsTASK_LINK_PTR) TaskHeader->task;

    /* Save the pointer to the container. */
    gcsTASK_CONTAINER_PTR container = TaskHeader->container;

    /* No more tasks in the list? */
    if (task->task == gcvNULL)
    {
        /* Reset the entry. */
        TaskHeader->container = gcvNULL;
        TaskHeader->task      = gcvNULL;
        TaskHeader->link      = gcvNULL;
    }
    else
    {
        /* Update the entry. */
        TaskHeader->container = task->cotainer;
        TaskHeader->task      = task->task;
    }

    /* Decrement the task buffer reference. */
    gcmkASSERT(container->referenceCount >= 0);
    if (container->referenceCount == 0)
    {
        /* Free the container. */
        _FreeTaskContainer(Command, container);
    }

    /* Success. */
    return gcvSTATUS_OK;
}

static gceSTATUS
_TaskCluster(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status = gcvSTATUS_OK;

    /* Cast the task pointer. */
    gcsTASK_CLUSTER_PTR cluster = (gcsTASK_CLUSTER_PTR) TaskHeader->task;

    /* Get the number of tasks. */
    gctUINT taskCount = cluster->taskCount;

    /* Advance to the next task. */
    TaskHeader->task = (gcsTASK_HEADER_PTR) (cluster + 1);

    /* Perform all tasks in the cluster. */
    while (taskCount)
    {
        /* Perform the current task. */
        gcmkERR_BREAK(_taskRoutine[TaskHeader->task->id](
            Command,
            TaskHeader
            ));

        /* Update the task count. */
        taskCount -= 1;
    }

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskIncrement(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_INCREMENT_PTR task = (gcsTASK_INCREMENT_PTR) TaskHeader->task;

        /* Convert physical into logical address. */
        gctUINT32_PTR logical;
        gcmkERR_BREAK(gckOS_MapPhysical(
            Command->os,
            task->address,
            gcmSIZEOF(gctUINT32),
            (gctPOINTER *) &logical
            ));

        /* Increment data. */
        (* logical) += 1;

        /* Unmap the physical memory. */
        gcmkERR_BREAK(gckOS_UnmapPhysical(
            Command->os,
            logical,
            gcmSIZEOF(gctUINT32)
            ));

        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskDecrement(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_DECREMENT_PTR task = (gcsTASK_DECREMENT_PTR) TaskHeader->task;

        /* Convert physical into logical address. */
        gctUINT32_PTR logical;
        gcmkERR_BREAK(gckOS_MapPhysical(
            Command->os,
            task->address,
            gcmSIZEOF(gctUINT32),
            (gctPOINTER *) &logical
            ));

        /* Decrement data. */
        (* logical) -= 1;

        /* Unmap the physical memory. */
        gcmkERR_BREAK(gckOS_UnmapPhysical(
            Command->os,
            logical,
            gcmSIZEOF(gctUINT32)
            ));

        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskSignal(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_SIGNAL_PTR task = (gcsTASK_SIGNAL_PTR) TaskHeader->task;

        /* Map the signal into kernel space. */
        gcmkERR_BREAK(gckOS_UserSignal(
            Command->os, task->signal, task->process
            ));
        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskLockdown(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;
    gctUINT32_PTR userCounter   = gcvNULL;
    gctUINT32_PTR kernelCounter = gcvNULL;
    gctSIGNAL signal            = gcvNULL;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_LOCKDOWN_PTR task = (gcsTASK_LOCKDOWN_PTR) TaskHeader->task;

        /* Convert physical addresses into logical. */
        gcmkERR_BREAK(gckOS_MapPhysical(
            Command->os,
            task->userCounter,
            gcmSIZEOF(gctUINT32),
            (gctPOINTER *) &userCounter
            ));

        gcmkERR_BREAK(gckOS_MapPhysical(
            Command->os,
            task->kernelCounter,
            gcmSIZEOF(gctUINT32),
            (gctPOINTER *) &kernelCounter
            ));

        /* Update the kernel counter. */
        (* kernelCounter) += 1;

        /* Are the counters equal? */
        if ((* userCounter) == (* kernelCounter))
        {
            /* Map the signal into kernel space. */
            gcmkERR_BREAK(gckOS_MapSignal(
                Command->os, task->signal, task->process, &signal
                ));

            if (signal == gcvNULL)
            {
                /* Signal. */
                gcmkERR_BREAK(gckOS_Signal(
                    Command->os, task->signal, gcvTRUE
                    ));
            }
            else
            {
                /* Signal. */
                gcmkERR_BREAK(gckOS_Signal(
                    Command->os, signal, gcvTRUE
                    ));
            }
        }

        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Destroy the mapped signal. */
    if (signal != gcvNULL)
    {
        gcmkVERIFY_OK(gckOS_DestroySignal(
            Command->os, signal
            ));
    }

    /* Unmap the physical memory. */
    if (kernelCounter != gcvNULL)
    {
        gcmkVERIFY_OK(gckOS_UnmapPhysical(
            Command->os,
            kernelCounter,
            gcmSIZEOF(gctUINT32)
            ));
    }

    if (userCounter != gcvNULL)
    {
        gcmkVERIFY_OK(gckOS_UnmapPhysical(
            Command->os,
            userCounter,
            gcmSIZEOF(gctUINT32)
            ));
    }

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskUnlockVideoMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_UNLOCK_VIDEO_MEMORY_PTR task
            = (gcsTASK_UNLOCK_VIDEO_MEMORY_PTR) TaskHeader->task;

        /* Unlock video memory. */
        gcmkERR_BREAK(gckVIDMEM_Unlock(
            Command->kernel->kernel,
            task->node,
            gcvSURF_TYPE_UNKNOWN,
            gcvNULL));

        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskFreeVideoMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_FREE_VIDEO_MEMORY_PTR task
            = (gcsTASK_FREE_VIDEO_MEMORY_PTR) TaskHeader->task;

        /* Free video memory. */
        gcmkERR_BREAK(gckVIDMEM_Free(task->node));

        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskFreeContiguousMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_FREE_CONTIGUOUS_MEMORY_PTR task
            = (gcsTASK_FREE_CONTIGUOUS_MEMORY_PTR) TaskHeader->task;

        /* Free contiguous memory. */
        gcmkERR_BREAK(gckOS_FreeContiguous(
            Command->os, task->physical, task->logical, task->bytes
            ));

        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskUnmapUserMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_UNMAP_USER_MEMORY_PTR task
            = (gcsTASK_UNMAP_USER_MEMORY_PTR) TaskHeader->task;

        /* Unmap the user memory. */
        gcmkERR_BREAK(gckOS_UnmapUserMemoryEx(
            Command->os, gcvCORE_VG, task->memory, task->size, task->info, task->address
            ));

        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_TaskUnmapMemory(
    gckVGCOMMAND Command,
    gcsBLOCK_TASK_ENTRY_PTR TaskHeader
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the task pointer. */
        gcsTASK_UNMAP_MEMORY_PTR task
            = (gcsTASK_UNMAP_MEMORY_PTR) TaskHeader->task;

        /* Unmap memory. */
        gcmkERR_BREAK(gckKERNEL_UnmapMemory(
            Command->kernel->kernel, task->physical, task->bytes, task->logical
            ));

        /* Update the reference counter. */
        TaskHeader->container->referenceCount -= 1;

        /* Update the task pointer. */
        TaskHeader->task = (gcsTASK_HEADER_PTR) (task + 1);
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}


/******************************************************************************\
************ Hardware Block Interrupt Handlers For Scheduled Events ************
\******************************************************************************/

static gceSTATUS
_EventHandler_Block(
    IN gckVGKERNEL Kernel,
    IN gcsBLOCK_TASK_ENTRY_PTR TaskHeader,
    IN gctBOOL ProcessAll
    )
{
    gceSTATUS status, last;

    gcmkHEADER_ARG("Kernel=0x%x TaskHeader=0x%x ProcessAll=0x%x", Kernel, TaskHeader, ProcessAll);
    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Kernel, gcvOBJ_KERNEL);

    do
    {
        gckVGCOMMAND command;

        /* Get the command buffer object. */
        command = Kernel->command;

        /* Increment the interrupt usage semaphore. */
        gcmkERR_BREAK(gckOS_IncrementSemaphore(
            command->os, TaskHeader->interruptSemaphore
            ));

        /* Acquire the mutex. */
        gcmkERR_BREAK(gckOS_AcquireMutex(
            command->os,
            command->taskMutex,
            gcvINFINITE
            ));

        /* Verify inputs. */
        gcmkASSERT(TaskHeader            != gcvNULL);
        gcmkASSERT(TaskHeader->container != gcvNULL);
        gcmkASSERT(TaskHeader->task      != gcvNULL);
        gcmkASSERT(TaskHeader->link      != gcvNULL);

        /* Process tasks. */
        do
        {
            /* Process the current task. */
            gcmkERR_BREAK(_taskRoutine[TaskHeader->task->id](
                command,
                TaskHeader
                ));

            /* Is the next task is LINK? */
            if (TaskHeader->task->id == gcvTASK_LINK)
            {
                gcmkERR_BREAK(_taskRoutine[TaskHeader->task->id](
                    command,
                    TaskHeader
                    ));

                /* Done. */
                break;
            }
        }
        while (ProcessAll);

        /* Release the mutex. */
        gcmkCHECK_STATUS(gckOS_ReleaseMutex(
            command->os,
            command->taskMutex
            ));
    }
    while (gcvFALSE);

    gcmkFOOTER();
    /* Return status. */
    return status;
}

gcmDECLARE_INTERRUPT_HANDLER(COMMAND, 0)
{
    gceSTATUS status, last;

    gcmkHEADER_ARG("Kernel=0x%x ", Kernel);

    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Kernel, gcvOBJ_KERNEL);

    do
    {
        gckVGCOMMAND command;
        gcsKERNEL_QUEUE_HEADER_PTR mergeQueue;
        gcsKERNEL_QUEUE_HEADER_PTR queueTail;
        gcsKERNEL_CMDQUEUE_PTR entry;
        gctUINT entryCount;

        /* Get the command buffer object. */
        command = Kernel->command;

        /* Acquire the mutex. */
        gcmkERR_BREAK(gckOS_AcquireMutex(
            command->os,
            command->queueMutex,
            gcvINFINITE
            ));

        /* Get the current queue. */
        queueTail = command->queueTail;

        /* Get the current queue entry. */
        entry = queueTail->currentEntry;

        /* Get the number of entries in the queue. */
        entryCount = queueTail->pending;

        /* Process all entries. */
        while (gcvTRUE)
        {
            /* Call post-execution function. */
            status = entry->handler(Kernel, entry);

            /* Failed? */
            if (gcmkIS_ERROR(status))
            {
                gcmkTRACE_ZONE(
                    gcvLEVEL_ERROR,
                    gcvZONE_COMMAND,
                    "[%s] line %d: post action failed.\n",
                    __FUNCTION__, __LINE__
                    );
            }

            /* Executed the next buffer? */
            if (status == gcvSTATUS_EXECUTED)
            {
                /* Update the queue. */
                queueTail->pending      = entryCount;
                queueTail->currentEntry = entry;

                /* Success. */
                status = gcvSTATUS_OK;

                /* Break out of the loop. */
                break;
            }

            /* Advance to the next entry. */
            entry      += 1;
            entryCount -= 1;

            /* Last entry? */
            if (entryCount == 0)
            {
                /* Reset the queue to idle. */
                queueTail->pending = 0;

                /* Get a shortcut to the queue to merge with. */
                mergeQueue = command->mergeQueue;

                /* Merge the queues if necessary. */
                if (mergeQueue != queueTail)
                {
                    gcmkASSERT(mergeQueue < queueTail);
                    gcmkASSERT(mergeQueue->next == queueTail);

                    mergeQueue->size
                        += gcmSIZEOF(gcsKERNEL_QUEUE_HEADER)
                        + queueTail->size;

                    mergeQueue->next = queueTail->next;
                }

                /* Advance to the next queue. */
                queueTail = queueTail->next;

                /* Did it wrap around? */
                if (command->queue == queueTail)
                {
                    /* Reset merge queue. */
                    command->mergeQueue = queueTail;
                }

                /* Set new queue. */
                command->queueTail = queueTail;

                /* Is the next queue scheduled? */
                if (queueTail->pending > 0)
                {
                    gcsCMDBUFFER_PTR commandBuffer;

                    /* The first entry must be a command buffer. */
                    commandBuffer = queueTail->currentEntry->commandBuffer;

                    /* Start the command processor. */
                    status = gckVGHARDWARE_Execute(
                        command->hardware,
                        commandBuffer->address,
                        commandBuffer->dataCount
                        );

                    /* Failed? */
                    if (gcmkIS_ERROR(status))
                    {
                        gcmkTRACE_ZONE(
                            gcvLEVEL_ERROR,
                            gcvZONE_COMMAND,
                            "[%s] line %d: failed to start the next queue.\n",
                            __FUNCTION__, __LINE__
                            );
                    }
                }

                /* Break out of the loop. */
                break;
            }
        }

        /* Release the mutex. */
        gcmkCHECK_STATUS(gckOS_ReleaseMutex(
            command->os,
            command->queueMutex
            ));
    }
    while (gcvFALSE);

    gcmkFOOTER();
    /* Return status. */
    return status;
}

/* Define standard block interrupt handlers. */
gcmDEFINE_INTERRUPT_HANDLER(TESSELLATOR, 0)
gcmDEFINE_INTERRUPT_HANDLER(VG,          0)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       0)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       1)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       2)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       3)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       4)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       5)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       6)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       7)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       8)
gcmDEFINE_INTERRUPT_HANDLER(PIXEL,       9)

/* The entries in the array are arranged by event priority. */
static gcsBLOCK_INTERRUPT_HANDLER _blockHandlers[] =
{
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(TESSELLATOR, 0),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(VG,          0),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       0),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       1),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       2),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       3),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       4),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       5),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       6),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       7),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       8),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(PIXEL,       9),
    gcmDEFINE_INTERRUPT_HANDLER_ENTRY(COMMAND,     0),
};


/******************************************************************************\
************************* Static Command Buffer Handlers ***********************
\******************************************************************************/

static gceSTATUS
_UpdateStaticCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
    gcmkTRACE_ZONE(
        gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
        "%s(%d)\n",
        __FUNCTION__, __LINE__
        );

    /* Success. */
    return gcvSTATUS_OK;
}

static gceSTATUS
_ExecuteStaticCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
    gceSTATUS status;

    do
    {
        gcsCMDBUFFER_PTR commandBuffer;

        /* Cast the command buffer header. */
        commandBuffer = Entry->commandBuffer;

        /* Set to update the command buffer next time. */
        Entry->handler = _UpdateStaticCommandBuffer;

        gcmkTRACE_ZONE(
            gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
            "%s(%d): executing next buffer @ 0x%08X, data count = %d\n",
            __FUNCTION__, __LINE__,
            commandBuffer->address,
            commandBuffer->dataCount
            );

        /* Start the command processor. */
        gcmkERR_BREAK(gckVGHARDWARE_Execute(
            Kernel->hardware,
            commandBuffer->address,
            commandBuffer->dataCount
            ));

        /* Success. */
        return gcvSTATUS_EXECUTED;
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_UpdateLastStaticCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
#if gcvDEBUG || gcdFORCE_MESSAGES
    /* Get the command buffer header. */
    gcsCMDBUFFER_PTR commandBuffer = Entry->commandBuffer;

    /* Validate the command buffer. */
    gcmkASSERT(commandBuffer->completion != gcvNULL);
    gcmkASSERT(commandBuffer->completion != gcvVACANT_BUFFER);

#endif

    gcmkTRACE_ZONE(
        gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
        "%s(%d): processing all tasks scheduled for FE.\n",
        __FUNCTION__, __LINE__
        );

    /* Perform scheduled tasks. */
    return _EventHandler_Block(
        Kernel,
        &Kernel->command->taskTable[gcvBLOCK_COMMAND],
        gcvTRUE
        );
}

static gceSTATUS
_ExecuteLastStaticCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the command buffer header. */
        gcsCMDBUFFER_PTR commandBuffer = Entry->commandBuffer;

        /* Set to update the command buffer next time. */
        Entry->handler = _UpdateLastStaticCommandBuffer;

        gcmkTRACE_ZONE(
            gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
            "%s(%d): executing next buffer @ 0x%08X, data count = %d\n",
            __FUNCTION__, __LINE__,
            commandBuffer->address,
            commandBuffer->dataCount
            );

        /* Start the command processor. */
        gcmkERR_BREAK(gckVGHARDWARE_Execute(
            Kernel->hardware,
            commandBuffer->address,
            commandBuffer->dataCount
            ));

        /* Success. */
        return gcvSTATUS_EXECUTED;
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}


/******************************************************************************\
************************* Dynamic Command Buffer Handlers **********************
\******************************************************************************/

static gceSTATUS
_UpdateDynamicCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
    gcmkTRACE_ZONE(
        gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
        "%s(%d)\n",
        __FUNCTION__, __LINE__
        );

    /* Success. */
    return gcvSTATUS_OK;
}

static gceSTATUS
_ExecuteDynamicCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the command buffer header. */
        gcsCMDBUFFER_PTR commandBuffer = Entry->commandBuffer;

        /* Set to update the command buffer next time. */
        Entry->handler = _UpdateDynamicCommandBuffer;

        gcmkTRACE_ZONE(
            gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
            "%s(%d): executing next buffer @ 0x%08X, data count = %d\n",
            __FUNCTION__, __LINE__,
            commandBuffer->address,
            commandBuffer->dataCount
            );

        /* Start the command processor. */
        gcmkERR_BREAK(gckVGHARDWARE_Execute(
            Kernel->hardware,
            commandBuffer->address,
            commandBuffer->dataCount
            ));

        /* Success. */
        return gcvSTATUS_EXECUTED;
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_UpdateLastDynamicCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
#if gcvDEBUG || gcdFORCE_MESSAGES
    /* Get the command buffer header. */
    gcsCMDBUFFER_PTR commandBuffer = Entry->commandBuffer;

    /* Validate the command buffer. */
    gcmkASSERT(commandBuffer->completion != gcvNULL);
    gcmkASSERT(commandBuffer->completion != gcvVACANT_BUFFER);

#endif

    gcmkTRACE_ZONE(
        gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
        "%s(%d): processing all tasks scheduled for FE.\n",
        __FUNCTION__, __LINE__
        );

    /* Perform scheduled tasks. */
    return _EventHandler_Block(
        Kernel,
        &Kernel->command->taskTable[gcvBLOCK_COMMAND],
        gcvTRUE
        );
}

static gceSTATUS
_ExecuteLastDynamicCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
    gceSTATUS status;

    do
    {
        /* Cast the command buffer header. */
        gcsCMDBUFFER_PTR commandBuffer = Entry->commandBuffer;

        /* Set to update the command buffer next time. */
        Entry->handler = _UpdateLastDynamicCommandBuffer;

        gcmkTRACE_ZONE(
            gcvLEVEL_VERBOSE, gcvZONE_COMMAND,
            "%s(%d): executing next buffer @ 0x%08X, data count = %d\n",
            __FUNCTION__, __LINE__,
            commandBuffer->address,
            commandBuffer->dataCount
            );

        /* Start the command processor. */
        gcmkERR_BREAK(gckVGHARDWARE_Execute(
            Kernel->hardware,
            commandBuffer->address,
            commandBuffer->dataCount
            ));

        /* Success. */
        return gcvSTATUS_EXECUTED;
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}


/******************************************************************************\
********************************* Other Handlers *******************************
\******************************************************************************/

static gceSTATUS
_FreeKernelCommandBuffer(
    IN gckVGKERNEL Kernel,
    IN gcsKERNEL_CMDQUEUE_PTR Entry
    )
{
    gceSTATUS status;

    /* Free the command buffer. */
    status = _FreeCommandBuffer(Kernel, Entry->commandBuffer);

    /* Return status. */
    return status;
}


/******************************************************************************\
******************************* Queue Management *******************************
\******************************************************************************/

#if gcvDUMP_COMMAND_BUFFER
static void
_DumpCommandQueue(
    IN gckVGCOMMAND Command,
    IN gcsKERNEL_QUEUE_HEADER_PTR QueueHeader,
    IN gctUINT EntryCount
    )
{
    gcsKERNEL_CMDQUEUE_PTR entry;
    gctUINT queueIndex;

#if defined(gcvCOMMAND_BUFFER_NAME)
    static gctUINT arrayCount = 0;
#endif

    /* Is dumpinng enabled? */
    if (!Commad->enableDumping)
    {
        return;
    }

#if !defined(gcvCOMMAND_BUFFER_NAME)
    gcmkTRACE_ZONE(
        gcvLEVEL_INFO, gcvZONE_COMMAND,
        "COMMAND QUEUE DUMP: %d entries\n", EntryCount
        );
#endif

    /* Get the pointer to the first entry. */
    entry = QueueHeader->currentEntry;

    /* Iterate through the queue. */
    for (queueIndex = 0; queueIndex < EntryCount; queueIndex += 1)
    {
        gcsCMDBUFFER_PTR buffer;
        gctUINT bufferCount;
        gctUINT bufferIndex;
        gctUINT i, count;
        gctUINT size;
        gctUINT32_PTR data;

#if gcvDUMP_COMMAND_LINES
        gctUINT lineNumber;
#endif

#if !defined(gcvCOMMAND_BUFFER_NAME)
        gcmkTRACE_ZONE(
            gcvLEVEL_INFO, gcvZONE_COMMAND,
            "ENTRY %d\n", queueIndex
            );
#endif

        /* Reset the count. */
        bufferCount = 0;

        /* Set the initial buffer. */
        buffer = entry->commandBuffer;

        /* Loop through all subbuffers. */
        while (buffer)
        {
            /* Update the count. */
            bufferCount += 1;

            /* Advance to the next subbuffer. */
            buffer = buffer->nextSubBuffer;
        }

#if !defined(gcvCOMMAND_BUFFER_NAME)
        if (bufferCount > 1)
        {
            gcmkTRACE_ZONE(
                gcvLEVEL_INFO,
                gcvZONE_COMMAND,
                "  COMMAND BUFFER SET: %d buffers.\n",
                bufferCount
                );
        }
#endif

        /* Reset the buffer index. */
        bufferIndex = 0;

        /* Set the initial buffer. */
        buffer = entry->commandBuffer;

        /* Loop through all subbuffers. */
        while (buffer)
        {
            /* Determine the size of the buffer. */
            size = buffer->dataCount * Command->info.commandAlignment;

#if !defined(gcvCOMMAND_BUFFER_NAME)
            /* A single buffer? */
            if (bufferCount == 1)
            {
                gcmkTRACE_ZONE(
                    gcvLEVEL_INFO,
                    gcvZONE_COMMAND,
                    "  COMMAND BUFFER: count=%d (0x%X), size=%d bytes @ %08X.\n",
                    buffer->dataCount,
                    buffer->dataCount,
                    size,
                    buffer->address
                    );
            }
            else
            {
                gcmkTRACE_ZONE(
                    gcvLEVEL_INFO,
                    gcvZONE_COMMAND,
                    "  COMMAND BUFFER %d: count=%d (0x%X), size=%d bytes @ %08X\n",
                    bufferIndex,
                    buffer->dataCount,
                    buffer->dataCount,
                    size,
                    buffer->address
                    );
            }
#endif

            /* Determine the number of double words to print. */
            count = size / 4;

            /* Determine the buffer location. */
            data = (gctUINT32_PTR)
            (
                (gctUINT8_PTR) buffer + buffer->bufferOffset
            );

#if defined(gcvCOMMAND_BUFFER_NAME)
            gcmkTRACE_ZONE(
                gcvLEVEL_INFO,
                gcvZONE_COMMAND,
                "unsigned int _" gcvCOMMAND_BUFFER_NAME "_%d[] =\n",
                arrayCount
                );

            gcmkTRACE_ZONE(
                gcvLEVEL_INFO,
                gcvZONE_COMMAND,
                "{\n"
                );

            arrayCount += 1;
#endif

#if gcvDUMP_COMMAND_LINES
            /* Reset the line number. */
            lineNumber = 0;
#endif

#if defined(gcvCOMMAND_BUFFER_NAME)
            count -= 2;
#endif

            for (i = 0; i < count; i += 1)
            {
                if ((i % 8) == 0)
                {
#if defined(gcvCOMMAND_BUFFER_NAME)
                    gcmkTRACE_ZONE(gcvLEVEL_INFO, gcvZONE_COMMAND, "\t");
#else
                    gcmkTRACE_ZONE(gcvLEVEL_INFO, gcvZONE_COMMAND, "    ");
#endif
                }

#if gcvDUMP_COMMAND_LINES
                if (lineNumber == gcvDUMP_COMMAND_LINES)
                {
                    gcmkTRACE_ZONE(gcvLEVEL_INFO, gcvZONE_COMMAND, " . . . . . . . . .\n");
                    break;
                }
#endif
                gcmkTRACE_ZONE(gcvLEVEL_INFO, gcvZONE_COMMAND, "0x%08X", data[i]);

                if (i + 1 == count)
                {
                    gcmkTRACE_ZONE(gcvLEVEL_INFO, gcvZONE_COMMAND, "\n");

#if gcvDUMP_COMMAND_LINES
                    lineNumber += 1;
#endif
                }
                else
                {
                    if (((i + 1) % 8) == 0)
                    {
                        gcmkTRACE_ZONE(gcvLEVEL_INFO, gcvZONE_COMMAND, ",\n");

#if gcvDUMP_COMMAND_LINES
                        lineNumber += 1;
#endif
                    }
                    else
                    {
                        gcmkTRACE_ZONE(gcvLEVEL_INFO, gcvZONE_COMMAND, ", ");
                    }
                }
            }

#if defined(gcvCOMMAND_BUFFER_NAME)
            gcmkTRACE_ZONE(
                gcvLEVEL_INFO,
                gcvZONE_COMMAND,
                "};\n\n"
                );
#endif

            /* Advance to the next subbuffer. */
            buffer = buffer->nextSubBuffer;
            bufferIndex += 1;
        }

        /* Advance to the next entry. */
        entry += 1;
    }
}
#endif

static gceSTATUS
_LockCurrentQueue(
    IN gckVGCOMMAND Command,
    OUT gcsKERNEL_CMDQUEUE_PTR * Entries,
    OUT gctUINT_PTR EntryCount
    )
{
    gceSTATUS status;

    do
    {
        gcsKERNEL_QUEUE_HEADER_PTR queueHead;

        /* Get a shortcut to the head of the queue. */
        queueHead = Command->queueHead;

        /* Is the head buffer still being worked on? */
        if (queueHead->pending)
        {
            /* Increment overflow count. */
            Command->queueOverflow += 1;

            /* Wait until the head becomes idle. */
            gcmkERR_BREAK(_WaitForIdle(Command, queueHead));
        }

        /* Acquire the mutex. */
        gcmkERR_BREAK(gckOS_AcquireMutex(
            Command->os,
            Command->queueMutex,
            gcvINFINITE
            ));

        /* Determine the first queue entry. */
        queueHead->currentEntry = (gcsKERNEL_CMDQUEUE_PTR)
        (
            (gctUINT8_PTR) queueHead + gcmSIZEOF(gcsKERNEL_QUEUE_HEADER)
        );

        /* Set the pointer to the first entry. */
        * Entries = queueHead->currentEntry;

        /* Determine the number of available entries. */
        * EntryCount = queueHead->size / gcmSIZEOF(gcsKERNEL_CMDQUEUE);

        /* Success. */
        return gcvSTATUS_OK;
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}

static gceSTATUS
_UnlockCurrentQueue(
    IN gckVGCOMMAND Command,
    IN gctUINT EntryCount
    )
{
    gceSTATUS status;

    do
    {
#if !gcdENABLE_INFINITE_SPEED_HW
        gcsKERNEL_QUEUE_HEADER_PTR queueTail;
        gcsKERNEL_QUEUE_HEADER_PTR queueHead;
        gcsKERNEL_QUEUE_HEADER_PTR queueNext;
        gctUINT queueSize;
        gctUINT newSize;
        gctUINT unusedSize;

        /* Get shortcut to the head and to the tail of the queue. */
        queueTail = Command->queueTail;
        queueHead = Command->queueHead;

        /* Dump the command buffer. */
#if gcvDUMP_COMMAND_BUFFER
        _DumpCommandQueue(Command, queueHead, EntryCount);
#endif

        /* Get a shortcut to the current queue size. */
        queueSize = queueHead->size;

        /* Determine the new queue size. */
        newSize = EntryCount * gcmSIZEOF(gcsKERNEL_CMDQUEUE);
        gcmkASSERT(newSize <= queueSize);

        /* Determine the size of the unused area. */
        unusedSize = queueSize - newSize;

        /* Is the unused area big enough to become a buffer? */
        if (unusedSize >= gcvMINUMUM_BUFFER)
        {
            gcsKERNEL_QUEUE_HEADER_PTR nextHead;

            /* Place the new header. */
            nextHead = (gcsKERNEL_QUEUE_HEADER_PTR)
            (
                (gctUINT8_PTR) queueHead
                    + gcmSIZEOF(gcsKERNEL_QUEUE_HEADER)
                    + newSize
            );

            /* Initialize the buffer. */
            nextHead->size    = unusedSize - gcmSIZEOF(gcsKERNEL_QUEUE_HEADER);
            nextHead->pending = 0;

            /* Link the buffer in. */
            nextHead->next  = queueHead->next;
            queueHead->next = nextHead;
            queueNext       = nextHead;

            /* Update the size of the current buffer. */
            queueHead->size = newSize;
        }

        /* Not big enough. */
        else
        {
            /* Determine the next queue. */
            queueNext = queueHead->next;
        }

        /* Mark the buffer as busy. */
        queueHead->pending = EntryCount;

        /* Advance to the next buffer. */
        Command->queueHead = queueNext;

        /* Start the command processor if the queue was empty. */
        if (queueTail == queueHead)
        {
            gcsCMDBUFFER_PTR commandBuffer;

            /* The first entry must be a command buffer. */
            commandBuffer = queueTail->currentEntry->commandBuffer;

            /* Start the command processor. */
            gcmkERR_BREAK(gckVGHARDWARE_Execute(
                Command->hardware,
                commandBuffer->address,
                commandBuffer->dataCount
                ));
        }

        /* The queue was not empty. */
        else
        {
            /* Advance the merge buffer if needed. */
            if (queueHead == Command->mergeQueue)
            {
                Command->mergeQueue = queueNext;
            }
        }
#endif

        /* Release the mutex. */
        gcmkERR_BREAK(gckOS_ReleaseMutex(
            Command->os,
            Command->queueMutex
            ));

        /* Success. */
        return gcvSTATUS_OK;
    }
    while (gcvFALSE);

    /* Return status. */
    return status;
}


/******************************************************************************\
****************************** gckVGCOMMAND API Code *****************************
\******************************************************************************/

gceSTATUS
gckVGCOMMAND_Construct(
    IN gckVGKERNEL Kernel,
    IN gctUINT TaskGranularity,
    IN gctUINT QueueSize,
    OUT gckVGCOMMAND * Command
    )
{
    gceSTATUS status, last;
    gckVGCOMMAND command = gcvNULL;
    gcsKERNEL_QUEUE_HEADER_PTR queue;
    gctUINT i, j;

    gcmkHEADER_ARG("Kernel=0x%x TaskGranularity=0x%x QueueSize=0x%x Command=0x%x",
        Kernel, TaskGranularity, QueueSize, Command);
    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Kernel, gcvOBJ_KERNEL);
    gcmkVERIFY_ARGUMENT(QueueSize >= gcvMINUMUM_BUFFER);
    gcmkVERIFY_ARGUMENT(Command != gcvNULL);

    do
    {
        /***********************************************************************
        ** Generic object initialization.
        */

        /* Allocate the gckVGCOMMAND structure. */
        gcmkERR_BREAK(gckOS_Allocate(
            Kernel->os,
            gcmSIZEOF(struct _gckVGCOMMAND),
            (gctPOINTER *) &command
            ));

        /* Initialize the object. */
        command->object.type = gcvOBJ_COMMAND;

        /* Set the object pointers. */
        command->kernel      = Kernel;
        command->os          = Kernel->os;
        command->hardware    = Kernel->hardware;

        /* Reset pointers. */
        command->queue       = gcvNULL;
        command->queueMutex  = gcvNULL;
        command->taskMutex   = gcvNULL;
        command->commitMutex = gcvNULL;

        /* Reset context states. */
        command->contextCounter = 0;
        command->currentContext = 0;

        /* Enable command buffer dumping. */
        command->enableDumping = gcvTRUE;

        /* Set features. */
        command->fe20 = Kernel->hardware->fe20;
        command->vg20 = Kernel->hardware->vg20;
        command->vg21 = Kernel->hardware->vg21;

        /* Reset task table .*/
        gcmkVERIFY_OK(gckOS_ZeroMemory(
            command->taskTable, gcmSIZEOF(command->taskTable)
            ));

        /* Query command buffer attributes. */
        gcmkERR_BREAK(gckVGCOMMAND_InitializeInfo(command));

        /* Create the control mutexes. */
        gcmkERR_BREAK(gckOS_CreateMutex(Kernel->os, &command->queueMutex));
        gcmkERR_BREAK(gckOS_CreateMutex(Kernel->os, &command->taskMutex));
        gcmkERR_BREAK(gckOS_CreateMutex(Kernel->os, &command->commitMutex));


        /***********************************************************************
        ** Command queue initialization.
        */

        /* Allocate the command queue. */
        gcmkERR_BREAK(gckOS_Allocate(
            Kernel->os,
            QueueSize,
            (gctPOINTER *) &command->queue
            ));

        /* Initialize the command queue. */
        queue = command->queue;

        queue->size    = QueueSize - gcmSIZEOF(gcsKERNEL_QUEUE_HEADER);
        queue->pending = 0;
        queue->next    = queue;

        command->queueHead  =
        command->queueTail  =
        command->mergeQueue = command->queue;

        command->queueOverflow = 0;


        /***********************************************************************
        ** Enable TS overflow interrupt.
        */

        gcmkERR_BREAK(gckVGINTERRUPT_Enable(
            Kernel->interrupt,
            &command->info.tsOverflowInt,
            _EventHandler_TSOverflow
            ));

        /* Mask out the interrupt. */
        Kernel->hardware->eventMask &= ~(1 << command->info.tsOverflowInt);


        /***********************************************************************
        ** Enable Bus Error interrupt.
        */

        /* Hardwired to bit 31. */
        command->busErrorInt = 31;

        /* Enable the interrupt. */
        gcmkERR_BREAK(gckVGINTERRUPT_Enable(
            Kernel->interrupt,
            &command->busErrorInt,
            _EventHandler_BusError
            ));


        /***********************************************************************
        ** Task management initialization.
        */

        command->taskStorage            = gcvNULL;
        command->taskStorageGranularity = TaskGranularity;
        command->taskStorageUsable      = TaskGranularity - gcmSIZEOF(gcsTASK_STORAGE);

        command->taskFreeHead = gcvNULL;
        command->taskFreeTail = gcvNULL;

        /* Enable block handlers. */
        for (i = 0; i < gcmCOUNTOF(_blockHandlers); i += 1)
        {
            /* Get the target hardware block. */
            gceBLOCK block = _blockHandlers[i].block;

            /* Get the interrupt array entry. */
            gcsBLOCK_TASK_ENTRY_PTR entry = &command->taskTable[block];

            /* Determine the interrupt value index. */
            gctUINT index = entry->interruptCount;

            /* Create the block semaphore. */
            if (entry->interruptSemaphore == gcvNULL)
            {
                gcmkERR_BREAK(gckOS_CreateSemaphoreVG(
                    command->os, &entry->interruptSemaphore
                    ));
            }

            /* Enable auto-detection. */
            entry->interruptArray[index] = -1;

            /* Enable interrupt for the block. */
            gcmkERR_BREAK(gckVGINTERRUPT_Enable(
                Kernel->interrupt,
                &entry->interruptArray[index],
                _blockHandlers[i].handler
                ));

            /* Update the number of registered interrupts. */
            entry->interruptCount += 1;

            /* Inrement the semaphore to allow the usage of the registered
               interrupt. */
            gcmkERR_BREAK(gckOS_IncrementSemaphore(
                command->os, entry->interruptSemaphore
                ));

        }

        /* Error? */
        if (gcmkIS_ERROR(status))
        {
            break;
        }

        /* Get the FE interrupt. */
        command->info.feBufferInt
            = command->taskTable[gcvBLOCK_COMMAND].interruptArray[0];

        /* Return gckVGCOMMAND object pointer. */
        *Command = command;

        /* Success. */
        return gcvSTATUS_OK;
    }
    while (gcvFALSE);

    /* Roll back. */
    if (command != gcvNULL)
    {
        /* Disable block handlers. */
        for (i = 0; i < gcvBLOCK_COUNT; i += 1)
        {
            /* Get the task table entry. */
            gcsBLOCK_TASK_ENTRY_PTR entry = &command->taskTable[i];

            /* Destroy the semaphore. */
            if (entry->interruptSemaphore != gcvNULL)
            {
                gcmkCHECK_STATUS(gckOS_DestroySemaphore(
                    command->os, entry->interruptSemaphore
                    ));
            }

            /* Disable all enabled interrupts. */
            for (j = 0; j < entry->interruptCount; j += 1)
            {
                /* Must be a valid value. */
                gcmkASSERT(entry->interruptArray[j] >= 0);
                gcmkASSERT(entry->interruptArray[j] <= 31);

                /* Disable the interrupt. */
                gcmkCHECK_STATUS(gckVGINTERRUPT_Disable(
                    Kernel->interrupt,
                    entry->interruptArray[j]
                    ));
            }
        }

        /* Disable the bus error interrupt. */
        gcmkCHECK_STATUS(gckVGINTERRUPT_Disable(
            Kernel->interrupt,
            command->busErrorInt
            ));

        /* Disable TS overflow interrupt. */
        if (command->info.tsOverflowInt != -1)
        {
            gcmkCHECK_STATUS(gckVGINTERRUPT_Disable(
                Kernel->interrupt,
                command->info.tsOverflowInt
                ));
        }

        /* Delete the commit mutex. */
        if (command->commitMutex != gcvNULL)
        {
            gcmkCHECK_STATUS(gckOS_DeleteMutex(
                Kernel->os, command->commitMutex
                ));
        }

        /* Delete the command queue mutex. */
        if (command->taskMutex != gcvNULL)
        {
            gcmkCHECK_STATUS(gckOS_DeleteMutex(
                Kernel->os, command->taskMutex
                ));
        }

        /* Delete the command queue mutex. */
        if (command->queueMutex != gcvNULL)
        {
            gcmkCHECK_STATUS(gckOS_DeleteMutex(
                Kernel->os, command->queueMutex
                ));
        }

        /* Delete the command queue. */
        if (command->queue != gcvNULL)
        {
            gcmkCHECK_STATUS(gckOS_Free(
                Kernel->os, command->queue
                ));
        }

        /* Free the gckVGCOMMAND structure. */
        gcmkCHECK_STATUS(gckOS_Free(
            Kernel->os, command
            ));
    }

    gcmkFOOTER();
    /* Return the error. */
    return status;
}

gceSTATUS
gckVGCOMMAND_Destroy(
    OUT gckVGCOMMAND Command
    )
{
    gceSTATUS status = gcvSTATUS_OK;

    gcmkHEADER_ARG("Command=0x%x", Command);

    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Command, gcvOBJ_COMMAND);

    do
    {
        gctUINT i;
        gcsTASK_STORAGE_PTR nextStorage;

        if (Command->queueHead != gcvNULL)
        {
            /* Wait until the head becomes idle. */
            gcmkERR_BREAK(_WaitForIdle(Command, Command->queueHead));
        }

        /* Disable block handlers. */
        for (i = 0; i < gcvBLOCK_COUNT; i += 1)
        {
            /* Get the interrupt array entry. */
            gcsBLOCK_TASK_ENTRY_PTR entry = &Command->taskTable[i];

            /* Determine the index of the last interrupt in the array. */
            gctINT index = entry->interruptCount - 1;

            /* Destroy the semaphore. */
            if (entry->interruptSemaphore != gcvNULL)
            {
                gcmkERR_BREAK(gckOS_DestroySemaphore(
                    Command->os, entry->interruptSemaphore
                    ));
            }

            /* Disable all enabled interrupts. */
            while (index >= 0)
            {
                /* Must be a valid value. */
                gcmkASSERT(entry->interruptArray[index] >= 0);
                gcmkASSERT(entry->interruptArray[index] <= 31);

                /* Disable the interrupt. */
                gcmkERR_BREAK(gckVGINTERRUPT_Disable(
                    Command->kernel->interrupt,
                    entry->interruptArray[index]
                    ));

                /* Update to the next interrupt. */
                index                 -= 1;
                entry->interruptCount -= 1;
            }

            /* Error? */
            if (gcmkIS_ERROR(status))
            {
                break;
            }
        }

        /* Error? */
        if (gcmkIS_ERROR(status))
        {
            break;
        }

        /* Disable the bus error interrupt. */
        gcmkERR_BREAK(gckVGINTERRUPT_Disable(
            Command->kernel->interrupt,
            Command->busErrorInt
            ));

        /* Disable TS overflow interrupt. */
        if (Command->info.tsOverflowInt != -1)
        {
            gcmkERR_BREAK(gckVGINTERRUPT_Disable(
                Command->kernel->interrupt,
                Command->info.tsOverflowInt
                ));

            Command->info.tsOverflowInt = -1;
        }

        /* Delete the commit mutex. */
        if (Command->commitMutex != gcvNULL)
        {
            gcmkERR_BREAK(gckOS_DeleteMutex(
                Command->os, Command->commitMutex
                ));

            Command->commitMutex = gcvNULL;
        }

        /* Delete the command queue mutex. */
        if (Command->taskMutex != gcvNULL)
        {
            gcmkERR_BREAK(gckOS_DeleteMutex(
                Command->os, Command->taskMutex
                ));

            Command->taskMutex = gcvNULL;
        }

        /* Delete the command queue mutex. */
        if (Command->queueMutex != gcvNULL)
        {
            gcmkERR_BREAK(gckOS_DeleteMutex(
                Command->os, Command->queueMutex
                ));

            Command->queueMutex = gcvNULL;
        }

        if (Command->queue != gcvNULL)
        {
            /* Delete the command queue. */
            gcmkERR_BREAK(gckOS_Free(
                Command->os, Command->queue
                ));
        }

        /* Destroy all allocated buffers. */
        while (Command->taskStorage)
        {
            /* Copy the buffer pointer. */
            nextStorage = Command->taskStorage->next;

            /* Free the current container. */
            gcmkERR_BREAK(gckOS_Free(
                Command->os, Command->taskStorage
                ));

            /* Advance to the next one. */
            Command->taskStorage = nextStorage;
        }

        /* Error? */
        if (gcmkIS_ERROR(status))
        {
            break;
        }

        /* Mark the object as unknown. */
        Command->object.type = gcvOBJ_UNKNOWN;

        /* Free the gckVGCOMMAND structure. */
        gcmkERR_BREAK(gckOS_Free(Command->os, Command));

        /* Success. */
        return gcvSTATUS_OK;
    }
    while (gcvFALSE);

    /* Restore the object type if failed. */
    Command->object.type = gcvOBJ_COMMAND;

    gcmkFOOTER();
    /* Return the error. */
    return status;
}

gceSTATUS
gckVGCOMMAND_QueryCommandBuffer(
    IN gckVGCOMMAND Command,
    OUT gcsCOMMAND_BUFFER_INFO_PTR Information
    )
{
    gcmkHEADER_ARG("Command=0x%x Information=0x%x", Command, Information);
    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Command, gcvOBJ_COMMAND);
    gcmkVERIFY_ARGUMENT(Information != gcvNULL);

    /* Copy the information. */
    gcmkVERIFY_OK(gckOS_MemCopy(
        Information, &Command->info, sizeof(gcsCOMMAND_BUFFER_INFO)
        ));

    gcmkFOOTER_NO();
    /* Success. */
    return gcvSTATUS_OK;
}

gceSTATUS
gckVGCOMMAND_Allocate(
    IN gckVGCOMMAND Command,
    IN gctSIZE_T Size,
    OUT gcsCMDBUFFER_PTR * CommandBuffer,
    OUT gctPOINTER * Data
    )
{
    gceSTATUS status;

    gcmkHEADER_ARG("Command=0x%x Size=0x%x CommandBuffer=0x%x Data=0x%x",
        Command, Size, CommandBuffer, Data);

    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Command, gcvOBJ_COMMAND);
    gcmkVERIFY_ARGUMENT(Data != gcvNULL);

    do
    {
        /* Allocate the buffer. */
        gcmkERR_BREAK(_AllocateCommandBuffer(Command, Size, CommandBuffer));

        /* Determine the data pointer. */
        * Data = (gctUINT8_PTR) CommandBuffer + (* CommandBuffer)->bufferOffset;
    }
    while (gcvFALSE);

    gcmkFOOTER();
    /* Return status. */
    return status;
}

gceSTATUS
gckVGCOMMAND_Free(
    IN gckVGCOMMAND Command,
    IN gcsCMDBUFFER_PTR CommandBuffer
    )
{
    gceSTATUS status;

    gcmkHEADER_ARG("Command=0x%x CommandBuffer=0x%x",
        Command, CommandBuffer);

    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Command, gcvOBJ_COMMAND);
    gcmkVERIFY_ARGUMENT(CommandBuffer != gcvNULL);

    /* Free command buffer. */
    status = _FreeCommandBuffer(Command->kernel, CommandBuffer);

    gcmkFOOTER();
    /* Return status. */
    return status;
}

gceSTATUS
gckVGCOMMAND_Execute(
    IN gckVGCOMMAND Command,
    IN gcsCMDBUFFER_PTR CommandBuffer
    )
{
    gceSTATUS status;

    gcmkHEADER_ARG("Command=0x%x CommandBuffer=0x%x",
        Command, CommandBuffer);

    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Command, gcvOBJ_COMMAND);
    gcmkVERIFY_ARGUMENT(CommandBuffer != gcvNULL);

    do
    {
        gctUINT queueLength;
        gcsKERNEL_CMDQUEUE_PTR kernelEntry;

        /* Lock the current queue. */
        gcmkERR_BREAK(_LockCurrentQueue(
            Command, &kernelEntry, &queueLength
            ));

        /* Set the buffer. */
        kernelEntry->commandBuffer = CommandBuffer;
        kernelEntry->handler = _FreeKernelCommandBuffer;

        /* Lock the current queue. */
        gcmkERR_BREAK(_UnlockCurrentQueue(
            Command, 1
            ));
    }
    while (gcvFALSE);

    gcmkFOOTER();
    /* Return status. */
    return status;
}

gceSTATUS
gckVGCOMMAND_Commit(
    IN gckVGCOMMAND Command,
    IN gcsVGCONTEXT_PTR Context,
    IN gcsVGCMDQUEUE_PTR Queue,
    IN gctUINT EntryCount,
    IN gcsTASK_MASTER_TABLE_PTR TaskTable
    )
{
    /*
        The first buffer is executed through a direct gckVGHARDWARE_Execute call,
        therefore only an update is needed after the execution is over. All
        consequent buffers need to be executed upon the first update call from
        the FE interrupt handler.
    */

    static gcsQUEUE_UPDATE_CONTROL _dynamicBuffer[] =
    {
        {
            _UpdateDynamicCommandBuffer,
            _UpdateDynamicCommandBuffer,
            _UpdateLastDynamicCommandBuffer,
            _UpdateLastDynamicCommandBuffer
        },
        {
            _ExecuteDynamicCommandBuffer,
            _UpdateDynamicCommandBuffer,
            _ExecuteLastDynamicCommandBuffer,
            _UpdateLastDynamicCommandBuffer
        }
    };

    static gcsQUEUE_UPDATE_CONTROL _staticBuffer[] =
    {
        {
            _UpdateStaticCommandBuffer,
            _UpdateStaticCommandBuffer,
            _UpdateLastStaticCommandBuffer,
            _UpdateLastStaticCommandBuffer
        },
        {
            _ExecuteStaticCommandBuffer,
            _UpdateStaticCommandBuffer,
            _ExecuteLastStaticCommandBuffer,
            _UpdateLastStaticCommandBuffer
        }
    };

    gceSTATUS status, last;

    gcmkHEADER_ARG("Command=0x%x Context=0x%x Queue=0x%x EntryCount=0x%x TaskTable=0x%x",
        Command, Context, Queue, EntryCount, TaskTable);

    /* Verify the arguments. */
    gcmkVERIFY_OBJECT(Command, gcvOBJ_COMMAND);
    gcmkVERIFY_ARGUMENT(Context != gcvNULL);
    gcmkVERIFY_ARGUMENT(Queue != gcvNULL);
    gcmkVERIFY_ARGUMENT(EntryCount > 1);

    do
    {
        gctBOOL haveFETasks;
        gctUINT queueSize;
        gcsVGCMDQUEUE_PTR mappedQueue;
        gcsVGCMDQUEUE_PTR userEntry;
        gcsKERNEL_CMDQUEUE_PTR kernelEntry;
        gcsQUEUE_UPDATE_CONTROL_PTR queueControl;
        gctUINT currentLength;
        gctUINT queueLength;
        gctUINT entriesQueued;
        gctUINT8_PTR previousEnd;
        gctBOOL previousDynamic;
        gctBOOL previousExecuted;
        gctUINT controlIndex;

        /* Acquire the mutex. */
        gcmkERR_BREAK(gckOS_AcquireMutex(
            Command->os,
            Command->commitMutex,
            gcvINFINITE
            ));

        do
        {
            /* Assign a context ID if not yet assigned. */
            if (Context->id == 0)
            {
                /* Assign the next context number. */
                Context->id = ++ Command->contextCounter;

                /* See if we overflowed. */
                if (Command->contextCounter == 0)
                {
                    /* We actually did overflow, wow... */
                    status = gcvSTATUS_OUT_OF_RESOURCES;
                    break;
                }
            }

            /* The first entry in the queue is always the context buffer.
               Verify whether the user context is the same as the current
               context and if that's the case, skip the first entry. */
            if (Context->id == Command->currentContext)
            {
                /* Same context as before, skip the first entry. */
                EntryCount -= 1;
                Queue      += 1;

                /* Set the signal to avoid user waiting. */
                gcmkERR_BREAK(gckOS_UserSignal(
                    Command->os, Context->signal, Context->process
                    ));
            }
            else
            {
                /* Different user context - keep the first entry.
                   Set the user context as the current one. */
                Command->currentContext = Context->id;
            }

            /* Reset pointers. */
            queueControl = gcvNULL;
            previousEnd  = gcvNULL;

            /* Determine whether there are FE tasks to be performed. */
            haveFETasks = (TaskTable->table[gcvBLOCK_COMMAND].head != gcvNULL);

            /* Determine the size of the queue. */
            queueSize = EntryCount * gcmSIZEOF(gcsVGCMDQUEUE);

            /* Map the command queue into the kernel space. */
            gcmkERR_BREAK(gckOS_MapUserPointer(
                Command->os,
                Queue,
                queueSize,
                (gctPOINTER *) &mappedQueue
                ));

            /* Set the first entry. */
            userEntry = mappedQueue;

            /* Process the command queue. */
            while (EntryCount)
            {
                /* Lock the current queue. */
                gcmkERR_BREAK(_LockCurrentQueue(
                    Command, &kernelEntry, &queueLength
                    ));

                /* Determine the number of entries to process. */
                currentLength = (queueLength < EntryCount)
                    ? queueLength
                    : EntryCount;

                /* Update the number of the entries left to process. */
                EntryCount -= currentLength;

                /* Reset previous flags. */
                previousDynamic  = gcvFALSE;
                previousExecuted = gcvFALSE;

                /* Set the initial control index. */
                controlIndex = 0;

                /* Process entries. */
                for (entriesQueued = 0; entriesQueued < currentLength; entriesQueued += 1)
                {
                    /* Get the kernel pointer to the command buffer header. */
                    gcsCMDBUFFER_PTR commandBuffer;
                    gcmkERR_BREAK(_ConvertUserCommandBufferPointer(
                        Command,
                        userEntry->commandBuffer,
                        &commandBuffer
                        ));

                    /* Is it a dynamic command buffer? */
                    if (userEntry->dynamic)
                    {
                        /* Select dynamic buffer control functions. */
                        queueControl = &_dynamicBuffer[controlIndex];
                    }

                    /* No, a static command buffer. */
                    else
                    {
                        /* Select static buffer control functions. */
                        queueControl = &_staticBuffer[controlIndex];
                    }

                    /* Set the command buffer pointer to the entry. */
                    kernelEntry->commandBuffer = commandBuffer;

                    /* If the previous entry was a dynamic command buffer,
                       link it to the current. */
                    if (previousDynamic)
                    {
                        gcmkERR_BREAK(gckVGCOMMAND_FetchCommand(
                            Command,
                            previousEnd,
                            commandBuffer->address,
                            commandBuffer->dataCount,
                            gcvNULL
                            ));

                        /* The buffer will be auto-executed, only need to
                           update it after it has been executed. */
                        kernelEntry->handler = queueControl->update;

                        /* The buffer is only being updated. */
                        previousExecuted = gcvFALSE;
                    }
                    else
                    {
                        /* Set the buffer up for execution. */
                        kernelEntry->handler = queueControl->execute;

                        /* The buffer is being updated. */
                        previousExecuted = gcvTRUE;
                    }

                    /* The current buffer's END command becomes the last END. */
                    previousEnd
                        = ((gctUINT8_PTR) commandBuffer)
                        + commandBuffer->bufferOffset
                        + commandBuffer->dataCount * Command->info.commandAlignment
                        - Command->info.staticTailSize;

                    /* Update the last entry info. */
                    previousDynamic = userEntry->dynamic;

                    /* Advance entries. */
                    userEntry   += 1;
                    kernelEntry += 1;

                    /* Update the control index. */
                    controlIndex = 1;
                }

                /* If the previous entry was a dynamic command buffer,
                   terminate it with an END. */
                if (previousDynamic)
                {
                    gcmkERR_BREAK(gckVGCOMMAND_EndCommand(
                        Command,
                        previousEnd,
                        Command->info.feBufferInt,
                        gcvNULL
                        ));
                }

                /* Last buffer? */
                if (EntryCount == 0)
                {
                    /* Modify the last command buffer's routines to handle
                       tasks if any.*/
                    if (haveFETasks)
                    {
                        if (previousExecuted)
                        {
                            kernelEntry[-1].handler = queueControl->lastExecute;
                        }
                        else
                        {
                            kernelEntry[-1].handler = queueControl->lastUpdate;
                        }
                    }

                    /* Release the mutex. */
                    gcmkERR_BREAK(gckOS_ReleaseMutex(
                        Command->os,
                        Command->queueMutex
                        ));
                    /* Schedule tasks. */
                    gcmkERR_BREAK(_ScheduleTasks(Command, TaskTable, previousEnd));

                    /* Acquire the mutex. */
                    gcmkERR_BREAK(gckOS_AcquireMutex(
                        Command->os,
                        Command->queueMutex,
                        gcvINFINITE
                        ));
                }

                /* Unkock and schedule the current queue for execution. */
                gcmkERR_BREAK(_UnlockCurrentQueue(
                    Command, currentLength
                    ));
            }

            /* Unmap the user command buffer. */
            gcmkERR_BREAK(gckOS_UnmapUserPointer(
                Command->os,
                Queue,
                queueSize,
                mappedQueue
                ));
        }
        while (gcvFALSE);

        /* Release the mutex. */
        gcmkCHECK_STATUS(gckOS_ReleaseMutex(
            Command->os,
            Command->commitMutex
            ));
    }
    while (gcvFALSE);

    gcmkFOOTER();
    /* Return status. */
    return status;
}

#endif /* gcdENABLE_VG */