summaryrefslogtreecommitdiffstats
path: root/private/mvdm/dpmi/dxutil.asm
blob: ab4930cc4b321d32738f76ee26444dd151f3f267 (plain) (blame)
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
        PAGE    ,132
        TITLE   DXUTIL.ASM -- Dos Extender Miscellaneous Routines

; Copyright (c) Microsoft Corporation 1988-1991. All Rights Reserved.

;****************************************************************
;*                                                              *
;*      DXUTIL.ASM      -   Dos Extender Miscellaneous          *
;*                                                              *
;****************************************************************
;*                                                              *
;*  Module Description:                                         *
;*                                                              *
;*  This module contains miscellaneous routines for the Dos     *
;*  Extender.                                                   *
;*                                                              *
;****************************************************************
;*  Revision History:                                           *
;*                                                              *
;*  08/08/90 earleh DOSX and client privilege ring determined   *
;*      by equate in pmdefs.inc                                 *
;*  04/09/90 jimmat   If 286 with 287, put 287 into pMode too.  *
;*  08/20/89 jimmat   Removed local A20 code since HIMEM 2.07   *
;*                    works properly across processor resets    *
;*  07/28/89 jimmat   Added A20 check/set routines, added       *
;*                    SelOff2SegOff & Lma2SegOff routines.      *
;*  06/19/89 jimmat   Set direction flag before REP MOVS        *
;*  05/25/89 jimmat   Added GetSegmentAccess routine            *
;*  03/30/89 jimmat   Set IOPL = 3 when entering protect mode   *
;*  03/16/89 jimmat   Added more debug sanity checks            *
;*  03/15/89 jimmat   Minor changes to run child in ring 1      *
;*  03/13/89 jimmat   Added support for LDT & TSS               *
;*  02/10/89 (GeneA): changed Dos Extender from small model to  *
;*      medium model.  Also added MoveMemBlock function.        *
;*  01/25/89 (GeneA): changed initialization of real mode code  *
;*      segment address in EnterRealMode.  caused by adding     *
;*      new method of relocationg dos extender for PM operation *
;*  12/13/88 (GeneA): moved EnterProtectedMode and EnterReal-   *
;*      Mode here from dxinit.asm                               *
;*  09/16/88 (GeneA):   created by extracting code from the     *
;*      SST debugger modules DOSXTND.ASM, VIRTMD.ASM,           *
;*      VRTUTIL.ASM, and INTERRPT.ASM                           *
;*  18-Dec-1992 sudeepb Changed cli/sti to faster FCLI/FSTI     *
;*  24-Jan-1992 v-simonf Added WOW callout when INT 8 hooked    *
;*                                                              *
;****************************************************************

.286p
.287

; -------------------------------------------------------
;           INCLUDE FILE DEFINITIONS
; -------------------------------------------------------

; .sall
; .xlist
include segdefs.inc
include gendefs.inc
include pmdefs.inc
include dpmi.inc
if 0
ifdef WOW
include bop.inc
endif
endif
if VCPI
include dxvcpi.inc
endif
IFDEF   ROM
include dxrom.inc
ENDIF
include intmac.inc
.list

; -------------------------------------------------------
;           GENERAL SYMBOL DEFINITIONS
; -------------------------------------------------------

SHUT_DOWN   =   8Fh         ;address in CMOS ram of the shutdown code
CMOS_ADDR   =   70h         ;i/o address of the cmos ram address register
CMOS_DATA   =   71h         ;i/o address of the cmos ram data register

DMAServiceSegment       equ     040h    ;40:7B bit 5 indicates DMA services
DMAServiceByte          equ     07Bh    ;  are currently required
DMAServiceBit           equ     020h

; -------------------------------------------------------
;           EXTERNAL SYMBOL DEFINITIONS
; -------------------------------------------------------


; -------------------------------------------------------
;           DATA SEGMENT DEFINITIONS
; -------------------------------------------------------

DXDATA  segment

        extrn   segGDT:WORD
        extrn   segIDT:WORD
        extrn   selGDT:WORD
        extrn   selIDT:WORD
        extrn   selGDTFree:WORD
        extrn   bpGDT:FWORD
        extrn   bpIDT:FWORD
        extrn   bpRmIVT:FWORD
        extrn   idCpuType:WORD
        extrn   rgbXfrBuf1:BYTE
        extrn   i31HWReset:BYTE
ifdef NOT_NTVDM_NOT
        extrn   fHPVectra:BYTE
endif
        extrn   PMIntelVector:DWORD
        extrn   PMFaultVector:DWORD
        extrn   lpfnXMSFunc:DWORD
        extrn   PMInt24Handler:DWORD

if VCPI
        extrn   fVCPI:BYTE
endif

IFDEF   ROM
        extrn   segDXCode:WORD
        extrn   segDXData:WORD
ENDIF
        extrn   pbReflStack:WORD
        extrn   HwIntHandlers:DWORD

bIntMask        db      0

bpBogusIDT      df      0       ;This is loaded into the IDT register to
                                ; force a bogus IDT to be defined.  When we
                                ; then do an interrupt a triple fault will
                                ; occur forcing the processor to reset.  This
                                ; is when doing a mode switch to real mode.

IDTSaveArea     dw      3 DUP (?)       ;save area for IDT during mode switch

        public  A20EnableCount

A20EnableCount  dw      0

ShutDownSP      dw      0       ;stack pointer during 286 reset

        public  f286_287

f286_287        db      0       ;NZ if this is a 286 with 287 coprocessor


        EXTRN   FasterModeSwitch:WORD

if DEBUG   ;------------------------------------------------------------

        extrn   fTraceA20:WORD
        extrn   fTraceMode:WORD

        public  fA20

fA20    db      0

endif   ;DEBUG  --------------------------------------------------------

selPmodeFS      dw      0
selPmodeGS      dw      0

        public HighestSel
HighestSel dw 0

ifndef WOW
        public IretBopTable
IretBopTable label byte
        irp x,<0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15>
        db  0c4h, 0c4h, 05dh, x
        endm
else
        public FastBop
FastBop         df 0

IretBopTable label byte
        irp x,<0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15>
        db  02eh, 066h, 0FFh, 01eh, 00h, 00h, 05dh, x
        endm

        extrn   DpmiFlags:WORD
NullSel dd      0
        dd      0
endif
DXDATA  ends

; -------------------------------------------------------
;               CODE SEGMENT VARIABLES
; -------------------------------------------------------

DXCODE  segment

IFNDEF  ROM
        extrn   segDXData:WORD
        extrn   segDXCode:WORD
        extrn   selDgroup:WORD
ENDIF

if VCPI
        extrn   fnVCPI:FWORD

        EXTRN   laVTP:DWORD

endif

DXCODE  ends


DXPMCODE    segment

        extrn selDgroupPM:WORD

DXPMCODE    ends

; -------------------------------------------------------
        subttl  Real/Protected Mode Switch Routines
        page

; -------------------------------------------------------

DXCODE  segment
        assume  cs:DXCODE

; -------------------------------------------------------
;       REAL/PROTECTED MODE SWITCH ROUTINES
; -------------------------------------------------------
;
;  EnterProtectedMode   -- This routine will switch the processor
;       into protected mode.  It will return with the processor
;       in protected mode and all of the segment registers loaded
;       with the selectors for the protected mode segments.
;       (CS with the selector for DXCODE and DS,ES,SS with the
;       selector for DXDATA)
;       It will also switch mode dependent memory variables.
;       It assumes that InitGlobalDscrTable and InitIntrDscrTable
;       have been called to set up the descriptor tables appropriately.
;
;   Note:   Except for a very brief time in this routine and in
;           EnterRealMode, the DOS Extender runs in the same ring along
;           with it's child app.  This has the benefit of eliminating
;           ring transitions on hardware and software interrupts.
;           It also makes it possible for the child to hook their
;           own interrupt routine into the IDT.
;
;   Input:  none
;   Output: none
;   Errors: none
;   Uses:   AX, DS, ES, SS, CS modified, all others preserved
;
;   NOTE:   This routine turns interrupts of and does not turn them
;           back on.

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  EnterProtectedMode

EnterProtectedMode  proc  near

        FCLI

IFNDEF  ROM
; Update the mode dependent variables.

        mov     ax,SEL_DXDATA or STD_RING
        mov     selDgroup,ax
ENDIF

; Set the DMA services required bit for pMode users.

        mov     ax,DMAServiceSegment
        mov     es,ax
        or      byte ptr es:[DMAServiceByte],DMAServiceBit

if VCPI
        cmp     fVCPI,0                 ;if vcpi, don't touch
        jne     epmVCPIstart            ; the a20 line, et al
endif

; 'local enable' the A20 line via HIMEM before switching to pMode.
; This is more complicated than you might think.  Some real mode code
; (like old versions of SMARTDRV.SYS) may diddle with A20 on their own.
; These programs may not want us to change A20 on them.  RMIntrReflector
; may do a XMS 'local enable' to turn A20 back on for one of these pgms.
; Also, on a 386 where we actually do the mode switch, we try to leave
; A20 enabled so as to not waste time diddling for nothing.  The
; A20EnabledCount variable tracks if we've 'local enabled' A20 or not.
; Since we can't really trust real mode to leave A20 alone, we double
; check that it's really really on when we think it should be.

        push    bx                      ;save bx around XMS calls

        cmp     A20EnableCount,0        ;should A20 already be enabled?
        jz      enpm10                  ;  no, (normal 4 286) just go enable it

        xmssvc  7                       ;  yes, is it really enabled?
        or      ax,ax
        jnz     enpm15                  ;  yes, we be done!

if DEBUG   ;------------------------------------------------------------
        or      fA20,1                  ;  somebody done us wrong
endif   ;---------------------------------------------------------------

        xmssvc  6                       ;keep enable/disable calls balanced
        dec     A20EnableCount
enpm10:
        xmssvc  5                       ;local enable A20
        inc     A20EnableCount

if DEBUG   ;------------------------------------------------------------

        or      ax,ax
        jnz     @f
        or      fA20,2                  ;enable failed!
@@:
        cmp     fTraceA20,0
        jz      @f
        xmssvc  7                       ;in debug mode, make double sure
        or      ax,ax                   ;  A20 was enabled.  Slows things
        jnz     @f                      ;  down, but it's better to know.
        or      fA20,2
@@:
endif   ;DEBUG  --------------------------------------------------------

enpm15: pop     bx

ifndef WOW
; Make sure that the nested task flag is clear

        pushf
        pop     ax
        and     ax,NOT 4000h
        push    ax
        npopf

; Make sure that we have the appropriate descriptor tables in effect,
; and switch the machine into protected mode

enpr20: smsw    ax              ;get current machine state
        or      ax,1            ;set the protected mode bit
        lgdt    bpGDT
        lidt    bpIDT
        lmsw    ax              ;and away we go

; Flush the instruction queue and load the code segment selector
; by doing a far jump.

        db      0EAh            ;jump far opcode
        dw      offset enpm40   ;offset of far pointer
        dw      SEL_DXCODE0     ;selector part of PM far pointer (ring 0)

if VCPI

; Switch when we are under VCPI

epmVCPIstart:

        .386

        push    esi             ;save regs modified by VCPI server
        push    eax             ;  (saving high word of EAX)

        push    bp              ;save bp on stack & sp in bp
        mov     bp,sp

        mov     esi, laVTP      ;linear address of structure

        RMvcpi  vcpiSWITCHTOPM  ;go for it

; Entry point (PM) when running under vcpi

PUBLIC  epmVCPI
epmVCPI:
        mov     ax,SEL_DXDATA0  ;stack has gotta be ring 0
        mov     ss,ax
        mov     sp,bp           ;restore sp

        pop     bp              ;restore old bp

        pop     eax             ;restore regs that VCPI server may have zapped
        pop     esi

        .286p

        mov     ax,SEL_DXDATA or STD_RING
        mov     ds,ax                           ;ds to our DGROUP
        mov     es,ax                           ;es too

        jmp     short enpmSwitchRing    ;rejoin common code
endif


; Load the other segment registers with valid selectors (not under VCPI)

enpm40: mov     ax,SEL_DXDATA0  ;stack has gotta be ring 0 also
        mov     ss,ax

        mov     ax,SEL_DXDATA or STD_RING
        mov     ds,ax                           ;ds to our DGROUP

; Load the LDT register and the Task Register

        mov     ax,SEL_LDT
        lldt    ax                      ;load the LDT register

        mov     ax,SEL_GDT
        mov     es,ax                           ;es to GDT

        push    si                              ;make sure busy bit is off
        mov     si,SEL_TSS                      ;  in the TSS descriptor
        mov     es:[si].arbSegAccess,STD_TSS    ;    before trying to load it
        ltr     si                              ;now load the task register
        pop     si
else
        .386p
        push    ebp
if 0
        movzx   ebp,sp
else
        mov     ebp,esp
endif
        push    SEL_DXCODE or STD_RING  ; new cs
        push    0                       ; high half eip
        push    offset epmwow           ; new eip
        push    SEL_DXDATA or STD_RING  ; new ss
        push    ebp
        push    SEL_DXDATA or STD_RING  ; new ds
        DPMIBOP DPMISwitchToProtectedMode
epmwow:
        pop     ebp
        .286p
endif

        push    ds                      ;point es to DGROUP
        pop     es

; If this is a 286 machine with a 287 math coprocessor, put the coprocessor
; into protected mode also.

        cmp     f286_287,0              ;286 and 287?
        jz      @f

        xor     al,al                   ;  yup, clear co-processor busy line
        out     0F0h,al
        fsetpm                          ;     and put it in pMode
@@:

; We're currently running in ring 0.  Setup an interlevel iret frame
; to switch to our normal ring, and also force IOPL=3.  I spent 1+ day
; debugging on a 286 system (with no debugger!) because the 286 seemed
; switch into protected mode with IOPL=0, and once we got to an outer
; ring, we would fault on things like CLI instructions.

enpmSwitchRing:
ifndef WOW
        mov     ax,sp                   ;still points to return address
        push    SEL_DXDATA or STD_RING  ;new ss
        push    ax                      ;new sp
        pushf
        pop     ax
        or      ah,30h
        push    ax                      ;new flags, with IOPL=3
        push    SEL_DXCODE or STD_RING  ;new cs
        push    offset DXCODE:epm_ret   ;new ip
        iret
endif
; When we get here, we are now in an outer ring.

epm_ret:

        cmp     idCpuType, 3
        jc      SegRegsOK
.386
        mov     ax, selPmodeFS
        mov     fs, ax
        mov     ax, selPmodeGS
        mov     gs, ax
.286p

SegRegsOK:
if DEBUG   ;------------------------------------------------------------

        cmp     fTraceMode,0
        jz      @f
        Trace_Out "^",x
@@:
if      VCPI
        cmp     fVCPI,0
        jz      @f
        jmp     a20okay
@@:
endif   ; VCPI
        cmp     A20EnableCount,1
        jz      @f
        Debug_Out "EnterProtectedMode: A20EnableCount != 1"
@@:
        cmp     fTraceA20,0
        jz      a20okay
        test    fA20,0FFh
        jz      a20okay
        test    fA20,01h
        jz      @f
        Trace_Out "EPM: A20 was wrong!"
@@:
        test    fA20,02h
        jz      @f
        Trace_Out "EPM: A20 enable failed!"
@@:
        test    fA20,04h
        jz      @f
        Trace_Out "rM2pMInt: A20 was on"
@@:
        mov     fA20,0
a20okay:
endif   ;DEBUG  --------------------------------------------------------

        ret                     ;near return to caller in pMode

EnterProtectedMode endp


; -------------------------------------------------------
; EnterRealMode     -- This routine will switch the processor
;       from protected mode back into real mode.  It will also
;       reset the various mode dependent variables to their
;       real mode values and load the segment registers with
;       the real mode segment addresses.
;
;   Input:  none
;   Output: none
;   Errors: none
;   Uses:   AX, DS, ES, SS, CS modified
;
;   NOTE:   This routine must be called with the stack segment set
;           to the Dos Extender data segment, as it resets the stack
;           segment register to the Dos Extender real mode data segment
;           but does not modify the stack pointer.
;   NOTE:   This routine turns interrupts off and and does not turn
;           them back on.

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  EnterRealMode

EnterRealMode   proc    near


if DEBUG        ;--------------------------------------------------------

        cmp     fTraceMode,0
        jz      @f
        Trace_Out "v",x
@@:
endif   ;DEBUG  ---------------------------------------------------------

        cmp     idCpuType,3
        jc      RegsOkay
.386
        mov     ax,fs
        mov     selPmodeFS, ax
        mov     ax,gs
        mov     selPmodeGS, ax
RegsOkay:
.286p

        FCLI

IFDEF   ROM
        push    ds
        pop     es
ELSE
        mov     es,selDgroup
ENDIF

IFNDEF WOW
; If we are running on an 80386, we can do the switch more efficiently.

        cmp     idCpuType,3     ;80386?
        jc      enrm20

; We're on an 386 (or better)--do a faster mode switch.  Call a ring 0 proc
; to actually do the switch.  The call gate has been setup to select either
; the roll-our-own 386 switch, or the VCPI switch.

enrm10:
        db      9Ah                         ;call  far SEL_RESET:0
        dw      0,SEL_RESET or STD_RING

; The Reset386 routine does a near return (cause the far CS on the stack
; is for protected mode, and it returns in real mode).  Discard the PM
; CS value.

        pop     ax              ;discard old PM CS from stack

; The transition to the ring 0 procedure caused a stack switch.  The return
; back to here (in real mode) didn't restore the old stack, so do it now...

        pop     sp              ;restore previous sp offset

        jmp     enrm70  ;jmp to common exit code


; On the 80286, it is a lot more complicated.  The PC BIOS start up code
; will check some special locations in the BIOS data segment to see if the
; machine was reset because it wants to do a mode switch.  If this is the
; case, it will restore the machine state from these variables and return
; to the original process.  We need to set up the state so that the BIOS
; will return control to us, and then generate a reset.  The reset is
; generated by causing the machine to triple fault.  This is an undocumented
; feature (i.e. bug) in the '286.

enrm20:

; Set up the stack for the BIOS to use after the reset.

        cmp     [FasterModeSwitch],0
        jne     enrm21

        pushf                   ;Push an IRET type return address of where
                                ; we want to come back to after the reset
        push    segDXCode
        push    offset enrm50

enrm21:

        mov     ax,segDXData    ;Our real mode data segment address

IFNDEF  ROM
ifdef NOT_NTVDM_NOT
        test    fHPVectra,HP_CLASSIC    ;HP Vectra A & A+ systems have a bug
        jz      enrm25                  ;  in their rom that requires a
                                        ;  different stack setup

        push    0               ;HP Vectra A & A+ trashes this
        push    ax              ;real mode data seg
        pusha
        push    ax              ;es?
        jmp     short enrm30

enrm25:
endif
ENDIF

        pusha                   ;The BIOS will do a POPA, so put all of the
                                ; registers on the stack for it.
        push    ax              ;It will also pop these into ES and DS
        push    ax
enrm30:

        push    SEL_BIOSDATA    ;BIOS data segment selector
        pop     es
        assume  es:BIOS_DATA

        cmp     [FasterModeSwitch],0
        jne     enrm31
; Tell the BIOS where the stack is.

        mov     IO_ROM_SEG,ax   ;Set up the address of the stack for the
        mov     IO_ROM_INIT,sp  ; BIOS to use after the reset
        jmp     enrm32
enrm31:
; Tell the BIOS where to transfer control.
        mov     bx,segDXCode
        mov     IO_ROM_SEG,bx
        mov     IO_ROM_INIT,offset DXCODE:enrm45

        mov     ShutDownSP,sp   ;save stack pointer in data seg
enrm32:
; IDT save/restore taken from OS/2 mode switching code...
;
; Now preserve three words of the vector table at 03FAh
; so we can restore it after the mode switch. The ROM
; trashes the top three words of the real mode IDT by
; putting a stack at 30:100.

        push    ds
        pop     es
        push    SEL_RMIVT or STD_RING   ;address real mode IDT
        pop     ds
        assume  ds:NOTHING,es:DGROUP

        MOV     SI,03FAH                        ;BIOS will pop regs, so
        MOV     DI,OFFSET DGROUP:IDTSaveArea    ;  we don't need to save
        CLD                                     ;  them here
        MOVSW
        MOVSW
        MOVSW

        push    es
        pop     ds
        assume  ds:DGROUP

; Write the shutdown type code into the CMOS ram.  Code 9 causes the BIOS
; to load SS:SP from IO_ROM_SEG:IO_ROM_INIT, restore the registers and then
; do an IRET.  Code 0Ah loads a CS:IP and jumps to it.

        mov     al,SHUT_DOWN
        out     CMOS_ADDR,al
        mov     al,9
        cmp     [FasterModeSwitch],0
        je      enrm33
        mov     al,0ah
enrm33:
        out     CMOS_DATA,al

; Shut out all interrupts while we are resetting the processor.

        in      al,INTA01
        mov     bIntMask,al
        mov     al,0FFh
        out     INTA01,al

; Now, force a reset by causing a triple fault.  We do this via a far call
; to a call gate.  The ring 0 procedure (Reset286) then loads the IDT
; register with a bogus IDT and does an INT 3.  This causes the infamous
; "triple fault" which resets the processor.

        db      9Ah                         ;call  far SEL_RESET:0
        dw      0,SEL_RESET or STD_RING

; After the BIOS has finished its reset processing, control will come back
; to here in real mode.  We will be using the same stack as before, all
; regular registers have been preserved, and DS and ES contain the real mode
; address of DXDATA.

enrm45:
        FCLI

IFDEF   ROM
        %OUT What stack is in use here?
        GetRMDataSeg
        mov     ss,ax
ELSE
        mov     ss,segDXData            ;restore our stack
ENDIF
        mov     sp,ss:ShutDownSP

        pop     es                      ;restore registers from stack
        pop     ds
        popa

; Reset processing is almost finished.  We are using the same stack as
; before, all regular registers have been preserved, and DS and ES
; contain the real mode seg of DXDATA.

        assume  ds:DGROUP,es:DGROUP,SS:DGROUP

enrm50:
        FCLI

if DEBUG
        lgdt    bpGDT           ;We need to do this so that DEB386 can still
                                ; dump things after we switch to real mode.
                                ;When we went through the reset for '286 we
                                ; have trashed the GDTR in the cpu.
endif

; Restore trashed interrupt vector area

        xor     ax,ax                   ;address real mode IDT
        mov     es,ax

        push    si                      ;restore the three IDT words
        push    di
        mov     si,offset DGROUP:IDTSaveArea
        mov     di,03FAh
        cld
        movsw
        movsw
        movsw

        pop     di
        pop     si

        push    ds                      ;resotre es -> DXDATA
        pop     es

; Restore the state of the interrupt mask register

        mov     al,bIntMask
        out     INTA01,al

        cmp     [FasterModeSwitch],0
        jne     enrm51

; Back in real mode, 'local disable' the A20 line via HIMEM.  We only do
; this on a 286 'cause the BIOS has already turned off A20.  The 'local
; disable' lets the XMS driver know A20 is off, and possibly causes it to
; actually enable A20 if someone loaded prior to DOSX (like a TSR) wanted
; A20 on.

        push    bx
        xmssvc  6
        dec     A20EnableCount
        pop     bx

        jmp     enrm70

enrm51:
; Enable NMIs

        mov     al,0Dh
        out     CMOS_ADDR,al

; This is common exit code that is performed for both '386 and '286
; processors.
else ; wow

        push    SegDxCode
        push    offset DXCODE:enrmwow
        push    SegDxData
        push    sp
        push    SegDxData
.386p
        FBOP    BOP_SWITCHTOREALMODE,,FastBop
.286p
enrmwow: add    sp,6                    ; remove rest of parameters
        push    ds
        pop     es                      ; es not set by mode switch
endif ; wow

enrm70:
        push    es                              ;clear DMA services required
        mov     ax,DMAServiceSegment            ;  bit for real mode
        mov     es,ax
        and     byte ptr es:[DMAServiceByte],not DMAServiceBit
        pop     es

IFNDEF  ROM
        mov     ax,segDXData
        mov     selDgroup,ax
ENDIF

        ret

EnterRealMode   endp


; -------------------------------------------------------
;  Reset286  -- This procedure is called via a gate as
;               part of the switch to real mode.  Most of
;               the DOS Extender runs in the child application's
;               ring.  The lidt instruction has to execute in ring 0.

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  Reset286

Reset286 proc    far

ifndef  KBD_RESET               ;----------------------------------------

        lidt    bpBogusIDT      ;Load up IDTR with 0 length IDT

        int     3               ;Interrupt thru interrupt table with 0 length
                                ;Causes "triple fault" which resets the 286

else                            ;----------------------------------------

        call    Sync8042
        mov     al,0feh         ; Send 0feh - system reset command
        out     64h,al
@@:
        hlt
        jmp     short @b

endif                           ;----------------------------------------

Reset286 endp

ifdef   KBD_RESET               ;----------------------------------------

Sync8042    proc    near

        xor     cx,cx
S8InSync:
        in      al,64h
        and     al,2
        loopnz  S8InSync
        ret

Sync8042    endp

endif                           ;----------------------------------------


; -------------------------------------------------------
;  Reset386  -- This procedure is called via a gate as
;               part of the switch to real mode.  Most of
;               the DOS Extender runs in ring 1.  This
;               routine has a few ring 0 instructions.

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  Reset386

Reset386 proc    far

        .386p

        push    dx
        push    eax                 ;save high word of eax

        mov     dx,segDXData        ;get the real mode data segment

        mov     eax,cr0             ;turn off protected mode bit
        and     al,0FEh
        lidt    fword ptr bpRmIVT   ;Load real-mode IDT

        mov     cr0,eax

IFDEF   ROM     ;--------------------------------------------------------

        extrn   segRomDXCODE:ABS

        db      0EAh                ;jmp far to purge prefetch queue
        dw      r386_10
        public  lCodeSegLoc
lCodeSegLoc     label   word
        dw      segRomDXCODE

ELSE    ;ROM    ---------------------------------------------------------

; Note, the following far jmp has special dispensation to use a SEG DXCODE
; operand which would normally require a fixup.  DOSX used to relocate its
; code for protected mode and plug the segment value in at lCodeSegLoc.  It
; doesn't perform the relocation any longer, but debug only code still
; checks for fix ups that might require fix ups.  It knows lCodeSegLoc is ok.

        db      0EAh                ;jmp far to purge prefetch queue
        dw      r386_10
        public  lCodeSegLoc
lCodeSegLoc     label   word
        dw      seg DXCODE

ENDIF   ;ROM    ---------------------------------------------------------

r386_10:
        mov     ss,dx           ;real mode data segment address
        mov     ds,dx
        mov     es,dx

        pop     eax
        pop     dx

        .286p

; We entered this routine via a far call, even though it was from code in
; the same segment.  However, the CS value on the stack is a protected
; mode selector, not a real mode segment.  Do a near return, the caller
; will pop off the PM CS value.

        retn                    ;NOTE: near return even though far call!

Reset386        endp

if VCPI ;----------------------------------------------------------------

; -------------------------------------------------------
;  ResetVCPI -- This procedure is called via a gate as
;               part of the switch to real (V86) mode when
;               running under a VCPI server.  Most of
;               the DOS Extender runs in the user code ring.  This
;               routine runs in ring 0.

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  ResetVCPI

ResetVCPI proc  far

        .386p

        push    eax                     ;save eax & edx for after switch
        push    edx

IFDEF   ROM
        GetPMDataSeg
        movzx   edx, ax
ELSE
        movzx   edx,segDXData           ;real mode DGROUP segment
ENDIF
        mov     eax, esp                ;save esp for stack frame of dosext

        push    0                       ;gs  begin frame for VCPI
        push    0                       ;gs
        push    0                       ;fs
        push    0                       ;fs
        push    edx                     ;ds
        push    edx                     ;es
        push    edx                     ;ss
        push    eax                     ;esp
        push    eax                     ;eflags reserved
        push    0                       ;cs
        push    cs:[lCodeSegLoc]        ;cs
        push    0                       ;eip (high)
        push    offset DXCODE:retVCPI   ;eip (low)

        mov     ax, SEL_VCPIALLMEM      ;setup ds to be
        mov     ds, ax                  ; selector for all memory

        mov     ax, vcpiSWITCHTOV86
        call    [fnVCPI]                ;call the VCPI server

; Return point for pMode to V86 switch.  The VCPI server sets up
; segment registers & stack pointer.

retVCPI:
        pop     edx                     ;restore eax & edx
        pop     eax

        .286p

; We entered this routine via a far call, even though it was from code in
; the same segment.  However, the CS value on the stack is a protected
; mode selector, not a real mode segment.  Do a near return, the caller
; will pop off the PM CS value.

        retn                    ;NOTE: near return even though far call!

ResetVCPI  endp


; -------------------------------------------------------
;  CallVCPI --  This procedure is invoked via a call gate in
;               order to call the VCPI protected mode entry
;               point in ring 0.  Most of the DOS Extender
;               runs in the user code ring, this routine runs in ring 0.
;
;       Note: This routine requires DS to point to the DOSX
;             DGROUP, not a parameter to VCPI!

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  CallVCPI

CallVCPI proc  far

        .386p

        call    [fnVCPI]                ;call the VCPI server

        .286p

        ret

CallVCPI endp

endif   ;VCPI   ---------------------------------------------------------

IFDEF WOW
        public RmUnsimulateProc

RmUnsimulateProc proc far
        BOP     BOP_UNSIMULATE
RmUnsimulateProc endp

ENDIF

; -------------------------------------------------------
DXCODE ends

DXPMCODE    segment
        assume cs:DXPMCODE
; -------------------------------------------------------
;       RAW MODE SWITCH ROUTINES
; -------------------------------------------------------

; ------------------------------------------------------
; PmRawModeSwitch       -- This routine performs a raw mode switch from
;       protected mode to real mode.  NOTE: applications will JUMP at this
;       routine
;
;   Input:   ax - new DS
;            cx - new ES
;            dx - new SS
;            bx - new sp
;            si - new CS
;            di - new ip
;    Output: DS, ES, SS, sp, CS, ip contain new values
;    Errors: none
;    Uses:
;
;
;
        assume ds:nothing, ss:nothing, es:nothing
        public PmRawModeSwitch
PmRawModeSwitch proc far

        push    ss
        pop     ds
        push    bx
IFNDEF WOW
        mov     bx,sp
ELSE
.386p
        mov     bx,ss
        movzx   ebx,bx
        lar     ebx,ebx
        test    ebx,(AB_BIG SHL 8)
        mov     ebx,esp
        jnz     prms10

        movzx   ebx,bx
prms10:
.286p
ENDIF

; Switch to dosx stack (since switch to real mode will do that to us anyway
; NOTE: no-one can call EnterIntHandler or ExitIntHandler until we switch to
;       the user's new stack.  If they do, they will use the area we stored
;       the parameters for this call for a stack frame

        rpushf
        FCLI
        push    SEL_DXDATA OR STD_RING
        pop     ss
        assume ss:DGROUP
IFNDEF WOW
        mov     sp,pbReflStack
ELSE
.386p
        movzx   esp,word ptr pbReflStack
.286p
ENDIF

; Save user registers

        push    dx              ; ss
IFDEF WOW
.386p
        push    word ptr [ebx]
        push    word ptr [ebx - 2]; flags pushed before cli
.286p
ELSE
        push    word ptr [bx]   ; sp
        push    word ptr [bx - 2] ; flags pushed before cli
ENDIF
        push    si              ; cs
        push    di              ; ip
        push    ax              ; ds
        push    cx              ; es

; switch modes

        mov     ax,SEL_DXDATA OR STD_RING
        mov     ds,ax
        SwitchToRealMode

; set the registers, switch stacks, and return to the user

        pop     es
        pop     ds
        pop     ax              ; ip
        pop     bx              ; cs
        pop     cx              ; flags
        pop     si              ; sp
        pop     ss
        assume ss:nothing
        mov     sp,si
        push    cx
        popf
        push    bx
        push    ax
        ret

PmRawModeSwitch endp

; NOTE: this is now the DXCODE segment, NOT the DXPMCODE segment (courtesy
;       of SwitchToRealMode

; ------------------------------------------------------
; RmRawModeSwitch       -- This routine performs a raw mode switch from
;       protected mode to real mode.  NOTE: applications will JUMP at this
;       routine
;
;   Input:   ax - new DS
;            cx - new ES
;            dx - new SS
;            bx - new sp
;            si - new CS
;            di - new ip
;    Output: DS, ES, SS, sp, CS, ip contain new values
;    Errors: none
;    Uses:
;
;
;
        assume ds:nothing, ss:nothing, es:nothing
        public RmRawModeSwitch
RmRawModeSwitch proc far

        push    ss
        pop     ds
        push    bx
        mov     bx,sp

; Switch to dosx stack (since switch to real mode will do that to us anyway
; NOTE: no-one can call EnterIntHandler or ExitIntHandler until we switch to
;       the user's new stack.  If they do, they will use the area we stored
;       the parameters for this call for a stack frame

        pushf
        FCLI
        push    segDxData
        pop     ss
        assume ss:DGROUP
        mov     sp,pbReflStack

; Save user registers

        push    dx              ; ss
        push    word ptr [bx]   ; sp
        push    word ptr [bx - 2] ; flags from before cli
        push    si              ; cs
        push    di              ; ip
        push    ax              ; ds
        push    cx              ; es

; switch modes

        mov     ax,segDxData
        mov     ds,ax
        SwitchToProtectedMode

; set the registers, switch stacks, and return to the user

        pop     es
        pop     ds
IFDEF WOW
.386p
        test    DpmiFlags,DPMI_32BIT
        jnz     rrms10

        xor     eax,eax         ; clear high 16 bits
        xor     edi,edi         ; clear high 16 bits
.286p
ENDIF
rrms10: pop     di              ; ip
        pop     ax              ; cs
        pop     cx              ; flags from before cli
        pop     bx              ; sp
        assume ss:nothing
        pop     ss
IFDEF WOW
.386p
        mov     esp,ebx
.286p
ELSE
        mov     sp,bx
ENDIF
        push    cx
        rpopf

IFDEF WOW
.386p
        push    eax
        push    edi
        db      066h
        retf
.286p
ELSE
        push    ax
        push    di
        retf
ENDIF

RmRawModeSwitch endp

DXPMCODE ENDS

DXCODE SEGMENT

; -------------------------------------------------------
;       STATE SAVE/RESTORE ROUTINES
; -------------------------------------------------------

; -------------------------------------------------------
; RmSaveRestoreState     -- This routine exists as a placeholder.  It
;       is not currently necessary to perform any state saving/restoring
;       for raw mode switch.  The DPMI spec states that the user can call
;       this routine with no adverse effect.
;
;   Input:  none
;   Output: none
;   Errors: none
;   Uses:   none
;
        assume ds:nothing, ss:nothing, es:nothing
        public RmSaveRestoreState
RmSaveRestoreState proc far
        ret
RmSaveRestoreState endp

DXCODE  ends

; -------------------------------------------------------

DXPMCODE  segment
        assume  cs:DXPMCODE

; -------------------------------------------------------
; RmSaveRestoreState     -- This routine exists as a placeholder.  It
;       is not currently necessary to perform any state saving/restoring
;       for raw mode switch.  The DPMI spec states that the user can call
;       this routine with no adverse effect.
;
;   Input:  none
;   Output: none
;   Errors: none
;   Uses:   none
;
        assume ds:nothing, ss:nothing, es:nothing
        public PmSaveRestoreState
PmSaveRestoreState proc far
        ret
PmSaveRestoreState endp

IFNDEF WOW
; -------------------------------------------------------
;   GetIntrVector   -- This routine will return the interrupt
;       vector from the Interrupt Descriptor Table for the
;       specified interrupt.
;
;   Input:  AX      - interrupt number of interrupt to return
;   Output: CX      - selector of the interrupt service routine
;           DX      - offset of the interrupt service routine
;   Errors: none
;   Uses:   CX, DX modified, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  GetIntrVector

GetIntrVector   proc    near

        push    si

        mov     si,ax
        cmp     si,8
        jb      @f

        cmp     si,0fh
        jbe     giv30

        cmp     si,070h
        jb      @f

        cmp     si,077h
        jbe     giv30
                                        ;if the Int # is below CRESERVED
@@:     cmp     ax,CRESERVED            ;  then the handler address is
        jnb     @f                      ;  in PMIntelVector
        shl     si,2
        mov     dx,word ptr PMIntelVector[si]
        mov     cx,word ptr PMIntelVector[si+2]
        jmp     short giv90
@@:
        push    es
        shl     si,3                    ;otherwise it's in the IDT
        mov     es,selIDT
giv20:  mov     dx,es:[si].offDest
        mov     cx,es:[si].selDest
        pop     es
        jmp     short giv90

giv30:  sub     si,8
        cmp     si,8
        jb      @f

        sub     si,070h - 16
@@:     shl     si,3
        mov     dx,word ptr HwIntHandlers[si]
        mov     cx,word ptr HwIntHandlers[si + 4]
giv90:
        pop     si
        return

GetIntrVector   endp

; -------------------------------------------------------
;   PutIntrVector   -- This routine will place the specified
;       interrupt vector address into the Interrupt Descriptor
;       Table entry for the specified interrupt.
;
;   Input:  AX      - interrupt number
;           CX      - selector of interrupt routine
;           DX      - offset of interrupt routine
;   Output: none
;   Errors: none
;   Uses:   all registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  PutIntrVector

PutIntrVector   proc    near

        push    di

        mov     di,ax
        mov     di,ax
        cmp     di,8
        jb      @f

        cmp     di,0fh
        jbe     piv30

        cmp     di,070h
        jb      @f

        cmp     di,077h
        jbe     piv30
                                        ;if the Int # is below CRESERVED
@@:     cmp     ax,CRESERVED            ;  then the handler address gets
        jnb     @f                      ;  put into PMIntelVector

        shl     di,2
        mov     word ptr PMIntelVector[di],dx
        mov     word ptr PMIntelVector[di+2],cx
        jmp     piv90

@@:
        push    es
        shl     di,3                    ;otherwise it goes directly in the IDT
        mov     es,selIDT
        FCLI

piv20:  mov     es:[di].offDest,dx
        mov     es:[di].selDest,cx
        FSTI
        pop     es

; If setting the Critical Error Handler, store the routine's address for
; easy access later.

        cmp     al,24h
        jnz     piv90

        mov     word ptr PMInt24Handler+2,cx
        mov     word ptr PMInt24Handler,dx
        jmp     piv90

piv30:  sub     di,8
        cmp     di,8
        jb      @f

        sub     di,070h - 16
@@:     shl     di,3
        mov     word ptr HwIntHandlers[di],dx
        mov     word ptr HwIntHandlers[di + 4],cx

piv90:
        pop     di
        ret

PutIntrVector   endp

ELSE

; -------------------------------------------------------
;   GetIntrVector   -- This routine will return the interrupt
;       vector from the Interrupt Descriptor Table for the
;       specified interrupt.
;
;   Input:  AX      - interrupt number of interrupt to return
;   Output: CX      - selector of the interrupt service routine
;           DX      - offset of the interrupt service routine
;   Errors: none
;   Uses:   CX, DX modified, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  GetIntrVector

GetIntrVector   proc    near

        push    si

        mov     si,ax
        cmp     si,8
        jb      @f

        cmp     si,0fh
        jbe     giv30

        cmp     si,070h
        jb      @f

        cmp     si,077h
        jbe     giv30

@@:     push    es
        shl     si,3                    ;otherwise it's in the IDT
        mov     es,selIDT
        test    DpmiFlags,DPMI_32BIT
        je     giv20

        ; Get upper 16 bits of ip
.386p
        mov     dx,es:[si + 6]
        shl     edx,16
.286p
giv20:  mov     dx,es:[si].offDest
        mov     cx,es:[si].selDest
        pop     es
        jmp     giv90

giv30:  sub     si,8
        cmp     si,8
        jb      giv40

        sub     si,070h - 16
giv40:  shl     si,3
        test    DpmiFlags,DPMI_32BIT
        jz      giv50

.386p
        mov     edx,HwIntHandlers[si]
.286p
        jmp     giv60

giv50:  mov     dx,word ptr HwIntHandlers[si]
giv60:  mov     cx,word ptr HwIntHandlers[si + 4]
giv90:
        pop     si
        return

GetIntrVector   endp
; -------------------------------------------------------
;   PutIntrVector   -- This routine will place the specified
;       interrupt vector address into the Interrupt Descriptor
;       Table entry for the specified interrupt.
;
;   Input:  AX      - interrupt number
;           CX      - selector of interrupt routine
;           DX      - offset of interrupt routine
;   Output: none
;   Errors: none
;   Uses:   all registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  PutIntrVector

PutIntrVector   proc    near
.386p
        push    di
        push    ax
        push    ebx
        push    edx

        test    DpmiFlags,DPMI_32BIT
        jz      piv10

        mov     ebx,VDM_INT_32
        jmp     piv20

piv10:  mov     ebx,VDM_INT_16
        movzx   edx,dx

piv20:  mov     di,ax
        cmp     di,8
        jb      @f

        cmp     di,0fh
        jbe     piv21

        cmp     di,070h
        jb      @f

        cmp     di,077h
        jbe     piv21

@@:     push    es
        shl     di,3                    ;otherwise it goes directly in the IDT
        mov     es,selIDT

        FCLI


        ; Put upper 16 bits of ip
        push    edx
        shr     edx,16
        mov     es:[di + 6],dx
        pop     edx


        mov     es:[di].offDest,dx
        mov     es:[di].selDest,cx
        FSTI
        pop     es

; If setting the Critical Error Handler, store the routine's address for
; easy access later.

        cmp     al,24h
        jnz     piv23

        mov     word ptr PMInt24Handler+4,cx
        mov     dword ptr PMInt24Handler,edx
        jmp     piv23

piv21:  sub     di,8
        cmp     di,8
        jb      @f

        sub     di,070h - 16
@@:     shl     di,3
        mov     HwIntHandlers[di],edx
        mov     word ptr HwIntHandlers[di + 4],cx

        ;
        ; Don't put the users handler into the "system ivt" otherwise,
        ; stack switch doesn't happen!!
        ;
        jmp     piv90

;
; set the handler in the actual "ivt", so it will get called on interrupts
;
piv23:  cmp     ax,70h
        jb      piv30

        cmp     ax,77h
        ja      piv30

;
; Hardware interrupts get interrupt gates
;
        or      ebx,VDM_INT_INT_GATE
        jmp     piv40

;
; Everyone else gets trap gates
;
piv30:  or      ebx,VDM_INT_TRAP_GATE
piv40:  push    bx
        push    ax
        push    cx
        push    edx
        DPMIBOP SetProtectedModeInterrupt
        add     sp,10

piv90:
        pop     edx
        pop     ebx
        pop     ax
        pop     di
        ret

PutIntrVector   endp
.286p
ENDIF

; -------------------------------------------------------
;   GetFaultVector   -- This routine will return the fault
;       handler address from the fault handler vector.
;
;   Input:  AX      - fault number of fault handler to return
;   Output: CX      - selector of the fault handler routine
;           DX      - offset of the fault handler routine
;   Errors: none
;   Uses:   CX, DX modified, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  GetFaultVector

GetFaultVector  proc    near

        push    si

        mov     si,ax                   ;if the Int # is below CRESERVED
        cmp     ax,CRESERVED            ;  then we do it
        jnb     @f

IFNDEF WOW
        shl     si,2
        mov     dx,word ptr PMFaultVector[si]
        mov     cx,word ptr PMFaultVector[si+2]
ELSE
        shl     si,3
.386p
        mov     edx,dword ptr PMFaultVector[si]
.286p
        mov     cx,word ptr PMFaultVector[si+4]
ENDIF
@@:
        pop     si
        return

GetFaultVector  endp


; -------------------------------------------------------
;   PutFaultVector   -- This routine will place the specified
;       fault handler address into the fault handler vector.
;
;   Input:  AX      - fault number
;           CX      - selector of fault handler routine
;           DX      - offset of fault handler routine
;   Output: none
;   Errors: none
;   Uses:   all registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  PutFaultVector

PutFaultVector  proc    near

        push    di

        mov     di,ax                   ;if the fault # is below CRESERVED
        cmp     ax,CRESERVED            ;  then we do it
        jnb     @f

IFNDEF WOW
        shl     di,2
        mov     word ptr PMFaultVector[di],dx
        mov     word ptr PMFaultVector[di+2],cx
ELSE
        shl     di,3
.386p
        mov     dword ptr PMFaultVector[di],edx
.286p
        mov     word ptr PMFaultVector[di+4],cx
ENDIF
@@:
        pop     di
        ret

PutFaultVector  endp

; -------------------------------------------------------
;   GTPARA      -- This routine will return the real mode paragraph
;       address of the specified protected mode memory segment.
;
;   Input:  SI      - selector of the segment
;   Output: returns ZR true if segment is in lower 1MB range
;           AX      - real mode paragraph address
;           returns ZR false if segment is in extended memory
;   Errors: returns CY true if selector isn't valid
;   Uses:   AX modified, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  gtpara

gtpara:
        push    cx
        push    es
        push    si

        push    bx
        mov     bx,selGDT           ;selector for the GDT segment
        mov     es,bx
        lsl     bx,bx
        and     bx,SELECTOR_INDEX
        and     si,SELECTOR_INDEX
        cmp     si,bx   ;check the given selector against
                                    ; the GDT segment limit
        pop     bx
        jc      gtpr20

; The given selector is beyond the end of the GDT, so return error.

        or      sp,sp
        stc

        Debug_Out "gtpara: invalid selector (#si)"

        jmp     short gtpr90

; The selector specified is inside the range of defined descriptors in
; the GDT.  Get the address from the descriptor.

gtpr20: mov     cl,es:[si].adrBaseHigh
        test    cl,0F0h
        jnz     gtpr90

        shl     cl,4
        mov     ax,es:[si].adrBaseLow

if DEBUG   ;------------------------------------------------------------
        test    al,0Fh
        jz      @f
        Debug_Out "gtpara: segment not on para boundry, sel #si at #cl#ax"
@@:
endif   ;DEBUG  --------------------------------------------------------

        shr     ax,4
        or      ah,cl
        cmp     ax,ax
;
gtpr90:
        pop     si
        pop     es
        pop     cx
        ret


; -------------------------------------------------------
;   SelOff2SegOff  -- This routine will return will translate a
;       protected mode selector:offset address to the corresponding
;       real mode segment:offset address.
;
;   Input:  AX      - PM selector
;           DX      - PM offset
;   Output: if Z set:
;           AX      - RM segment
;           DX      - RM offset
;           if NZ set, address is not in conventional memory, and
;             cannot be translated
;
;   Errors: none
;   Uses:   AX, DX; all else preserved
;
;   Note:  This routine is very similar to gtpara, and could replace it!

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  SelOff2SegOff

SelOff2SegOff   proc    near

        push    bx
        push    cx
        push    dx

        call    GetSegmentAddress       ;bx:dx = lma of segment

        pop     cx                      ;cx = offset

        test    bl,0f0h                 ;above 1 Meg line?
        jnz     @f                      ;  yes, cut out now

        add     dx,cx
        adc     bx,0                    ;bx:dx = lma of segment:offset

        call    Lma2SegOff              ;bx:dx = seg:off
        mov     ax,bx                   ;dx:ax = seg:off

        cmp     ax,ax                   ;under 1 Meg, set Z flag
@@:
        pop     cx
        pop     bx

        ret

SelOff2SegOff   endp


; ------------------------------------------------------
;   Lma2SegOff -- This routine converts a linear memory address
;       in BX:DX to a normalized SEG:OFF in BX:DX.
;
;   Input:  BX:DX = lma
;   Output: BX:DX = normalized SEG:OFF
;   Uses:   none


        public  Lma2SegOff

Lma2SegOff      proc    near

        push    dx
        shl     bx,12
        shr     dx,4
        or      bx,dx
        pop     dx
        and     dx,0fh

        ret

Lma2SegOff      endp


; -------------------------------------------------------
;   GetSegmentAddress   -- This routine will return with
;       the linear address of the specified segment.
;
;   Input:  AX      - segment selector
;   Output: DX      - low word of segment address
;           BX      - high word of segment address
;   Errors: none
;   Uses:   BX, DX, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  GetSegmentAddress

GetSegmentAddress:
        push    es
        push    di

        mov     es,selGDT
        mov     di,ax
        and     di,SELECTOR_INDEX
        mov     dx,es:[di].adrBaseLow
        mov     bl,es:[di].adrBaseHigh
        mov     bh,es:[di].adrbBaseHi386

        pop     di
        pop     es
        ret

; -------------------------------------------------------
;   SetSegmentAddress   -- This routine will modify the
;       segment base address of the specified segment.
;
;   Input:  AX      - segment selector
;   Output: DX      - low word of segment address
;           BX      - high word of segment address
;   Errors: None
;   Uses:   All registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  SetSegmentAddress

SetSegmentAddress:
        push    si
        push    es

        mov     es,selGDT
        mov     si,ax
        and     si,SELECTOR_INDEX
        mov     es:[si].adrBaseLow,dx
        mov     es:[si].adrBaseHigh,bl
        mov     es:[si].adrbBaseHi386,bh
IF 1  ; was IFDEF WOW, but I need this on MIPS too
        push    ax
        push    bx
        push    cx
        mov     ax,si
        mov     cx,1
        mov     bx,si
IFDEF I386
.386p
        FBOP BOP_DPMI,<SetDescriptorTableEntries>,FastBop
.286p
ELSE
        DPMIBOP SetDescriptorTableEntries
ENDIF
        pop     cx
        pop     bx
        pop     ax
ENDIF
        pop     es
        pop     si
        ret

; -------------------------------------------------------
;   NSetSegmentAccess   -- This routine will modify the
;       access rights byte of a specified segment.
;
;   Input:  Selector    - segment selector
;           Access      - Access rights byte value
;   Output: none
;   Errors: Carry set, AX = error code
;   Uses:   All registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
cProc   NSetSegmentAccess,<PUBLIC,NEAR>,<es,si>
        parmW   Selector
        parmW   Access
cBegin
        mov     es,selGDT
        mov     si,Selector
        and     si,SELECTOR_INDEX
        mov     ax,Access
        mov     es:[si].arbSegAccess,al      ; Set access byte.
        and     ah,0F0h                      ; Mask off reserved bits.
        and     es:[si].cbLimitHi386,0fh     ; Clear old extended bits.
        or      es:[si].cbLimitHi386,ah      ; Set new extended bits.
IFDEF WOW
        push    ax
        push    bx
        push    cx
        mov     ax,si
        mov     cx,1
        mov     bx,si
.386p
        FBOP    BOP_DPMI,<SetDescriptorTableEntries>,FastBop
.286p
        pop     cx
        pop     bx
        pop     ax
ENDIF

cEnd

ifdef WOW

; -------------------------------------------------------
;   NSetSegmentLimit    -- This routine will modify the
;       limit of a specified segment.
;
;   Input:  Selector    - segment selector
;           Limit       - Limit value
;   Output: none
;   Errors: Carry set, AX = error code
;   Uses:   All registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
cProc   NSetSegmentLimit,<PUBLIC,NEAR>,<es,si>
        parmW   Selector
cBegin
        mov     es,selGDT
        mov     si,Selector
        and     si,SELECTOR_INDEX
        push    ax
        push    bx
        push    cx
        mov     ax,si
        mov     cx,1
        mov     bx,si
.386p
        FBOP    BOP_DPMI,<SetDescriptorTableEntries>,FastBop
.286p
        pop     cx
        pop     bx
        pop     ax
cEnd

; -------------------------------------------------------
;   NSetSegmentBase     -- This routine will modify the
;       base address of a specified segment.
;
;   Input:  Selector    - segment selector
;           Base        - base address
;   Output: none
;   Errors: Carry set, AX = error code
;   Uses:   All registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
cProc   NSetSegmentBase,<PUBLIC,NEAR>,<es,si>
        parmW   Selector
        parmD   Base
cBegin
        mov     es,selGDT
        mov     si,Selector
        and     si,SELECTOR_INDEX
        mov     ax,word ptr Base
        mov     es:[si].adrBaseLow,ax
        mov     ax,word ptr Base + 2
        mov     es:[si].adrbBaseMid386,al
        mov     es:[si].adrbBaseHi386,ah
        clc
        push    ax
        push    bx
        push    cx
        mov     ax,si
        mov     cx,1
        mov     bx,si
.386p
        FBOP    BOP_DPMI,<SetDescriptorTableEntries>,FastBop
.286p
        pop     cx
        pop     bx
        pop     ax

cEnd

; -------------------------------------------------------
;   NMoveDescriptor -- This routine copy a descriptor from
;       the source address to the destination address.  This
;       can be to or from the descriptor table.  If it copied
;       to the descriptor table, the system will be notified as
;       appropriate.
;
;   Input:  Source      -- address of source descriptor
;           Dest        -- address of destination descriptor
;   Output: none
;   Errors: Carry set, AX = error code
;   Uses:   All registers preserved

        assume  ds:NOTHING,es:NOTHING,ss:NOTHING
.386p
cProc   NMoveDescriptor,<PUBLIC,NEAR>,<es,esi,ds,edi,ebx,ecx>
        ParmW   SourceSel
        ParmD   SourceOff
        ParmW   DestSel
        ParmD   DestOff
cBegin
.386p
        xor     ecx,ecx
        mov     cx,SourceSel
        mov     ds,cx
        mov     esi,SourceOff
        mov     cx,DestSel
        mov     es,cx
        mov     edi,DestOff
        mov     cx,8
        rep movs byte ptr [esi], byte ptr [edi]
        mov     ds,selDgroupPM
        assume ds:DGROUP
        mov     cx,es
        cmp     cx,ds:selGdt
        jne     nm20

        mov     cx,1
        mov     ebx,DestOff
        mov     ax,bx
        FBOP    BOP_DPMI,<SetDescriptorTableEntries>,FastBop
.386p
nm20:
cEnd
.286p

; -------------------------------------------------------
;   NWOWSetDescriptor --
;       The Descriptors are set on the system side.
;
;   Input:  Source      -- address of source descriptors
;           Count       -- count of descriptors to set
;   Output: none
;   Errors: Carry set, AX = error code
;   Uses:   All registers preserved

        assume  ds:NOTHING,es:NOTHING,ss:NOTHING
cProc   NWOWSetDescriptor,<PUBLIC,NEAR>,<es,ds,bx,cx>
        ParmW   Count
        ParmD   Source
cBegin
        les     bx, Source
        mov     cx, Count
        mov     ax, bx

        mov     ds,selDgroupPM
        assume ds:DGROUP
.386p
        FBOP    BOP_DPMI,<SetDescriptorTableEntries>,FastBop
.286p
cEnd
endif
; -------------------------------------------------------
;   ParaToLDTSelector    -- This routine will convert a segment
;       address relative to the start of the exe file into the
;       corresponding selector for the segment.  It searches the
;       LDT to see if a segment is already defined at that address.
;       If so, its selector is returned.  If not, a new segment
;       descriptor will be defined.
;
;   Note:   The LDT and GDT are currently one and the same.
;
;   Input:  AX      - paragraph aaddress of real mode segment
;           BX      - access rights byte for the segment
;   Output: AX      - selector for the segment
;   Errors: returns CY set if unable to define a new segment
;   Uses:   AX, all other registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  ParaToLDTSelector

ParaToLDTSelector  proc near

        push    bx
        push    cx
        push    dx

; Convert the paragraph address to a linear address and see if there
; is a segment defined at that address.

        mov     dx,ax
        call    FindLowSelector
        jnc     @f                      ;if so, we don't need to make one

; This segment isn't defined, so we need to create a descriptor for it.

        mov     ax,dx
        call    MakeLowSegment

if DEBUG   ;------------------------------------------------------------
        jnc     ptos80
        Debug_Out "ParaToLDTSelector: can't make selector!"
ptos80:
endif   ;DEBUG  --------------------------------------------------------

        jc      ptos90

@@:     or      al,SELECTOR_TI or STD_RING      ;look like LDT selector

; All done

ptos90: pop     dx
        pop     cx
        pop     bx
        ret

ParaToLDTSelector       endp

        public FarParaToLDTSelector
FarParaToLDTSelector proc far
        call ParaToLDTSelector
        ret
FarParaToLDTSelector endp

; -------------------------------------------------------
        page
; -------------------------------------------------------
;       DESCRIPTOR TABLE MANIPULATION ROUTINES
; -------------------------------------------------------
;
;   AllocateLDTSelector -- This function will obtain the
;       next free descriptor in the local descriptor table.
;
;   Note:   Currently the LDT and GDT are in the same table!
;
;   Note:   The function InitGlobalDscrTable must have been
;           called before calling this function.
;
;   Input:  none
;   Output: AX      - selector if one is available
;   Errors: CY clear if successful, AX=0 and CY set if not free selectors
;   Uses:   AX, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  AllocateLDTSelector

AllocateLDTSelector     proc    near

        call    AllocateSelector                ;get a GDT selector
        jc      @f

        or      al,SELECTOR_TI or STD_RING      ;say it's in the LDT

@@:     ret

AllocateLDTSelector     endp


; -------------------------------------------------------
;   AllocateSelector    -- This function will obtain the
;       next free descriptor in the global descriptor table.
;       The descriptors in the GDT are stored on a linked list
;       of free descriptors.  The cbLimit field of the descriptor
;       is used as the link to the next element of the list. In
;       addition, free descriptors have the access rights byte
;       set to 0.
;
;   Note:   The function InitGlobalDscrTable must have been
;           called before calling this function.
;
;   Input:  none
;   Output: AX      - selector if one is available
;   Errors: CY clear if successful, AX=0 and CY set if not free selectors
;   Uses:   AX, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  AllocateSelector

AllocateSelector  proc  near

; Get the next free descriptor on the list.

        mov     ax,selGDTFree       ;get head of free list
        or      ax,ax               ;is the list empty
        jnz     alsl20              ;if so, report error.
        stc                         ;set error flag

        Debug_Out "AllocateSelector: out of selectors!"

        jmp     short alsl90        ;and get out

; We now need to update the new head of list to point to the
; following one on the list.
; Whenever we allocate a descriptor, the access rights byte is set
; to 0Fh.  This marks it as a '386 task gate, which is not legal to
; have in the GDT.  We need to stick something in this byte, because
; having the access rights byte be 0 means that it is free, which is
; no longer the case.

alsl20:

if DEBUG   ;------------------------------------------------------------
        test    al,not SELECTOR_INDEX
        jz      @f
        Debug_Out "AllocateSelector: selGDTFree invalid! #AX"
        and     al,SELECTOR_INDEX
@@:
endif   ;DEBUG  --------------------------------------------------------

        push    bx
        push    es
        mov     bx,ax           ;BX points to the descriptor
        mov     es,selGDT       ;ES points to the GDT segment
        push    es:[bx].cbLimit ;push the link field of the descriptor
        pop     selGDTFree      ;make it be the new head of the list

        mov     es:[bx].adrbBaseHi386,0
        mov     es:[bx].arbSegAccess,0Fh
        pop     es
        pop     bx

        or      al,SELECTOR_TI
        ;
        ; Remember the highest selector alloced, so we can reinit the ldt
        ;
        cmp     ax,HighestSel
        jbe     alsl50

        mov     HighestSel,ax
alsl50: clc

;
; All done
alsl90: ret

AllocateSelector  endp


; -------------------------------------------------------
;   AllocateSelectorBlock   -- This function will allocate
;       a set of contiguous descriptors from the global
;       descriptor table.  It will search the GDT from the
;       beginning looking for a sufficiently large contiguous
;       set of descriptors.  When if finds a set, it will
;       then remove each one from the free descriptor list.
;
;   Input:  AX      - Number of selectors needed
;   Output: AX      - starting selector of the block
;   Errors: return CY set if error occurs
;   Uses:   AX modified, all other registers preserved
;           modifies global descriptor table free list

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  AllocateSelectorBlock

AllocateSelectorBlock  proc  near

        push    cx
        push    dx
        push    si
        push    di
        push    es

        mov     es,selGDT
        mov     dx,ax               ;remember descriptor count in DX
        lsl     di,selGDT           ;stop search at table limit

; Start at the first user selector and search until we find a
; sufficiently large block of contiguous selectors.

        mov     si,SEL_USER
alsb20: mov     ax,si       ;remember the starting one
        mov     cx,dx       ;number of descriptors to check
if 0
alsb30: cmp     es:[si].arbSegAccess,0  ;is this one free
else
alsb30: cmp     word ptr es:[si].arbSegAccess,0 ;is this one free
endif
        jnz     alsb40      ;if not, we have to continue looking
        add     si,8        ;bump to next descriptor
        cmp     si,di       ;check if at end of table
        jae     alsb80      ;if so, get out with error
        loop    alsb30      ;repeat for the number of selectors requested
        jmp     short alsb50;we found the block

; This one wasn't free, try the next one

alsb40: add     si,8        ;bump to next descriptor
        cmp     si,di       ;are we at the end of the table.
        jc      alsb20      ;and repeat if not
        jmp     short alsb80;we didn't find it, so report error

; AX has the starting selector of the block of descriptors.  We need
; to remove each of them from the free list.

alsb50: push    ax          ;remember the starting point
        mov     cx,dx       ;get descriptor count
        mov     dx,ax       ;remember current selector number
alsb52: mov     ax,dx
        call    RemoveFreeDescriptor
        add     dx,8
        loop    alsb52
        ;
        ; Remember the highest number
        ;
        or      dl,SELECTOR_TI
        cmp     dx,HighestSel
        jbe     alsb60

        mov     HighestSel,dx
alsb60: pop     ax          ;restore starting selector

        or      al,SELECTOR_TI

        clc
        jmp     short alsb90

; Couldn't find them, so return error.

alsb80: stc

        Debug_Out "AllocSelectorBlock: Failed!"

alsb90: pop     es
        pop     di
        pop     si
        pop     dx
        pop     cx
        ret

AllocateSelectorBlock  endp


; -------------------------------------------------------
;   RemoveFreeDescriptor    -- This routine will remove the
;       specified descriptor from the free descriptor list
;       of the GDT.
;
;   Input:  AX      - selector of the descriptor to remove
;           ES      - segment address of GDT
;   Output: none
;   Errors: none
;   Uses:   AX used, all other registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  RemoveFreeDescriptor

RemoveFreeDescriptor  proc  near

        push    si
        push    di

        and     ax,SELECTOR_INDEX       ;clear table/pl bits

; Check that the segment is really free.

        mov     si,ax           ;Segment index
if 0
        cmp     es:[si].arbSegAccess,0 ; Should be 0 if free
else
        cmp     word ptr es:[si].arbSegAccess,0 ; Should be 0 if free
endif
        jnz     rmfd80          ;Error if segment is not free!
;
        xor     di,di
        mov     si,selGDTFree   ;start at the head of the list.

; Look for a selector matching the one to free

rmfd20: or      si,si           ;check for end of list.
        jz      rmfd90          ;and get out if so
        cmp     ax,si           ;is this the one we are looking for
        jz      rmfd40
        mov     di,si
        mov     si,es:[si].cbLimit  ;point SI at next one in the list
        jmp     rmfd20          ;and repeat

; We found the one we want, so now remove it from the list.

rmfd40: mov     es:[si].adrbBaseHi386,0
        mov     es:[si].arbSegAccess,0Fh
        mov     ax,es:[si].cbLimit
        or      di,di           ;is it the head of the list
        jz      rmfd50

; The one we have isn't the head of the list, so make the previous
; list element point at the one beyond the one being removed.

        mov     es:[di].cbLimit,ax
        jmp     short rmfd90

; The one we have is the head of the list. Make the head of the list
; point to the one following the one being removed.

rmfd50:
        mov     selGDTFree,ax
        jmp     short rmfd90

rmfd80: stc                     ;Flag allocation error

        Debug_Out "RemoveFreeDescriptor: Failed!"

rmfd90: pop     di
        pop     si
        ret

RemoveFreeDescriptor  endp

; -------------------------------------------------------
;   IsSelectorFree -- This routine determines if the specified
;       selector is on the free list.  It is used to prevent
;       apps from corrupting the free list by doing things like
;       set selector on a descriptor in the free list.
;
;   Input:  BX - Descriptor index
;   Output: CY - set if decriptor is not free
;                clear otherwise
;
        assume ds:dgroup,es:nothing,ss:nothing
        public IsSelectorFree
IsSelectorFree proc near

        push    es
        push    si

        mov     si,selGdt
        mov     es,si

        test    byte ptr es:[bx].adrbBaseHi386,080h
        jnz     isf30

        stc
        jmp     isf40

isf30:  clc
isf40:  pop     si
        pop     es
        ret

IsSelectorFree endp


; -------------------------------------------------------
;   FreeSelector        --  This routine will mark the segment
;       descriptor for the specified selector as free.  This
;       is used to release a temporary selector when no longer
;       needed.  The descriptor is marked as free by setting the
;       access rights byte to 0 and placing it on the free list.
;
;   Note:   This routine can only be called in protected mode.
;
;   Input:  AX      - selector to free
;   Output: none
;   Errors: CY clear if no error, set if selector is invalid
;   Uses:   AX used, all other registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  FreeSelector

FreeSelector    proc    near
        push    bx
        push    es

; Check for this being a valid selector.

        cmp     ax,SEL_USER     ;make sure it is a user selector
        jb      frsl80
        mov     bx,SEL_LDT_ALIAS
        mov     es,selGDT
        mov     bx,es
        lsl     bx,bx
        cmp     ax,bx   ;make sure it is in the range of the table
        jnc     frsl80

; We have a legitimate selector, so set the access rights byte to 0, and
; place it at the head of the free list.

        mov     bx,ax
        and     bx,SELECTOR_INDEX       ;clear unwanted bits

if 0
        cmp     es:[bx].arbSegAccess,0  ;already marked as free?
else
        cmp     word ptr es:[bx].arbSegAccess,0 ;already marked as free?
endif
        jz      frsl80                  ;  yes, don't free it again!

if 0
        mov     es:[bx].arbSegAccess,0
else
        mov     word ptr es:[bx].arbSegAccess,0
        mov     byte ptr es:[bx].adrbBaseHi386,080h
endif
        mov     ax,selGDTFree           ;pointer to current head of list
        mov     es:[bx].cbLimit,ax      ;store in link field of this dscr.
        mov     selGDTFree,bx           ;make this one be the head of list.
if 0
BUGBUG fix this
IF 1  ; DaveHart was IFDEF WOW, need it for MIPS too
        int     3; debugbug
        push    ax
        push    bx
        push    cx
        mov     ax,bx
        mov     bx,offset NullSel
        push    ds
        pop     es
        mov     cx,1
IFDEF I386
.386p
        FBOP    BOP_DPMI,<SetDescriptorTableEntries>,FastBop
.286p
ELSE
        DPMIBOP SetDescriptorTableEntries
ENDIF
        pop     cx
        pop     bx
        pop     ax
ENDIF
endif
        clc
        jmp     short frsl90

; Bogus selector given.  Return error.

frsl80: stc

        Debug_Out "FreeSelector failed, #AX invalid or not used!?"

frsl90: pop     es
        pop     bx
frsl99: ret

FreeSelector    endp

; -------------------------------------------------------
;   FreeSelectorBlock   -- This routine will free the specified
;       range of segment descriptors in the global descriptor
;       table.
;
;   Input:  AX      - starting selector in the range
;           CX      - number of selectors to free
;   Output: none
;   Errors: returns CY set if error occurs
;   Uses:   AX, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  FreeSelectorBlock

FreeSelectorBlock  proc  near

        jcxz    frsb99
        push    cx
frsb20: push    ax
        call    FreeSelector
        pop     ax
        jc      frsb90
        add     ax,8
        loop    frsb20
frsb90: pop     cx
frsb99: ret

FreeSelectorBlock  endp


; -------------------------------------------------------
;   FindLowSelector  -- This function will search the global
;       descriptor table for a descriptor matching the given
;       address.
;
;   Input:  AX      - real mode paragraph to search for
;           BX      - access rights byte for the segment
;   Output: AX      - selector corresponding to input paragraph address
;   Errors: returns CY set if specified descriptor not found
;   Uses:   AX, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  FindLowSelector

FindLowSelector:
        push    bx
        push    dx
;
        mov     dx,ax
        push    bx
        call    ParaToLinear
        pop     ax
        mov     bh,al
        call    FindSelector
;
        pop     dx
        pop     bx
        ret

if 0
; -------------------------------------------------------
;   FindLDTSelector    -- This function will search the local
;       descriptor table for a segment descriptor matching
;       the specified linear byte address.
;
;   Note:   The LDT and GDT are currently one and the same!
;
;   Input:  DX      - low word of linear byte address
;           BL      - high byte of linear address
;           BH      - access rights byte for the segment
;   Output: AX      - selector of corresponding segment
;   Errors: returns CY set if specified descriptor not found
;   Uses:   AX used, all other registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  FindLDTSelector

FindLDTSelector proc    near

        call    FindSelector
        jc      @f

        or      al,SELECTOR_TI or STD_RING      ;say it's in the LDT

@@:     ret

FindLDTSelector endp
endif

; -------------------------------------------------------
;   FindSelector    -- This function will search the global
;       descriptor table for a segment descriptor matching
;       the specified linear byte address.
;
;       Note that this routine cannot be used to find
;       selectors pointing to addresses above 16 Megabytes.
;       This is not really a problem, since the routine
;       is used to find selectors in real mode DOS land
;       most of the time.
;
;   Input:  DX      - low word of linear byte address
;           BL      - high byte of linear address
;           BH      - access rights byte for the segment
;   Output: AX      - selector of corresponding segment
;   Errors: returns CY set if specified descriptor not found
;   Uses:   AX used, all other registers preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  FindSelector

FindSelector    proc    near

        push    si
        push    di
        push    es
        push    cx

; Get segment limit of the GDT to use as a limit on the search.

        lsl     di,selGDT
        mov     es,selGDT

; Look for a descriptor matching the address in BL:AX

        mov     si,SEL_USER     ;search starting here
if 0
fnds20: cmp     es:[si].arbSegAccess,0
else
fnds20: cmp     word ptr es:[si].arbSegAccess,0
endif
        jz      fnds28          ;skip if unused descriptor
        cmp     bl,es:[si].adrBaseHigh
        jnz     fnds28
        cmp     dx,es:[si].adrBaseLow
        jnz     fnds28
if      0
        cmp     es:[si].cbLimit,0
        jz      fnds28          ;skip if dscr has 0 limit
else
        cmp     es:[si].cbLimit,0ffffh
        jnz     fnds28          ;skip unless dscr has 64k limit
endif
        mov     cl,bh
        xor     cl,es:[si].arbSegAccess
        and     cl,NOT AB_ACCESSED
        jz      fnds90
fnds28: add     si,8            ;bump to next descriptor
        jc      fnds80
        cmp     si,di           ;check against end of GDT
        jc      fnds20          ;if still less, continue on.

; Hit the end of the GDT and didn't find one.  So return error.

fnds80: stc
        jmp     short fnds99

; We found it, so return the selector

fnds90: mov     ax,si
fnds99: pop     cx
        pop     es
        pop     di
        pop     si
        ret

FindSelector    endp



; -------------------------------------------------------
; DupSegmentDscr        -- This function will duplicate the specified
;   segment descriptor into the specified destination descriptor.  The
;   end result is a second segment descriptor pointing to the same place
;   in memory as the first.
;
;   Input:  AX      - selector of segment descriptor to duplicate
;           BX      - selector of the segment descriptor to receive duplicate
;   Output: none
;   Errors: none
;   Uses:   All registers preserved.    Modifies the segment
;           descriptor for the specified segment.  If this selector happens
;           to be in a segment register when this routine is called, that
;           segment register may end up pointing to the new location.

        assume  ds:DGROUP,es:NOTHING
        public  DupSegmentDscr

DupSegmentDscr  proc    near

        push    cx
        push    si
        push    di
        push    ds
        push    es

        mov     si,ax
        mov     di,bx
        and     si,SELECTOR_INDEX
        and     di,SELECTOR_INDEX
        mov     es,selGDT
        mov     ds,selGDT
        assume  ds:NOTHING
        mov     cx,4
        cld
        rep     movs word ptr [di],word ptr [si]

        pop     es
        pop     ds
        pop     di
        pop     si
        pop     cx
        ret

DupSegmentDscr  endp

IFDEF   ROM
; -------------------------------------------------------

DXPMCODE ends

; -------------------------------------------------------

DXCODE  segment
        assume  cs:DXCODE
ENDIF

; -------------------------------------------------------
; NSetSegmentDscr    -- This function will initialize the
;       specified descriptor table entry with the specified data.
;
;   This function can be called in real mode or protected mode.
;
;   Input:
;               Param1  - WORD segment selector
;               Param2  - DWORD 32-bit segment base address
;               Param3  - DWORD 32-bit segment limit
;               param4  - WORD segment access/type
;   Output: returns selector for the segment
;   Errors: none
;   Uses:   Flags

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
cProc   NSetSegmentDscr,<PUBLIC,FAR>,<es,di,ax,bx>
        parmW   Selector
        parmD   Base
        parmD   Limit
        parmW   Access
cBegin
        mov     es,selGDT
        mov     di,Selector
        and     di,SELECTOR_INDEX

        mov     ax,off_Base                     ; Set segment base
        mov     es:[di].adrBaseLow,ax
        mov     ax,seg_Base
        mov     es:[di].adrBaseHigh,al
        mov     es:[di].adrbBaseHi386,ah

        mov     ax,word ptr Access
        and     ax,070ffh                       ; clear 'G' bit and
                                                ; extended limit bits
        mov     word ptr es:[di].arbSegAccess,ax
                                                ; set access
        mov     ax,seg_Limit
        mov     bx,off_Limit                    ; AX:BX = segment limit
        test    ax,0fff0h                       ; big?
        jz      ssd_0                           ; No
        shr     bx,12d                          ; Yes, make it page granular.
        shl     ax,4d
        or      bx,ax
        mov     ax,seg_Limit
        shr     ax,12d
        or      al,080h                         ; set 'G' bit
ssd_0:
        or      es:[di].cbLimitHi386,al         ; set high limit
        mov     es:[di].cbLimit,bx              ; set low limit
IF 1;  DaveHart was IFDEF WOW, I need it on MIPS too
        push    ax
        push    bx
        push    cx
        mov     ax,di
        mov     cx,1
        mov     bx,di
IFDEF I386
.386p
        FBOP    BOP_DPMI,<SetDescriptorTableEntries>,FastBop
.286p
ELSE
        DPMIBOP SetDescriptorTableEntries
ENDIF
        pop     cx
        pop     bx
        pop     ax
ENDIF
cEnd

ifndef WOW
; -------------------------------------------------------
; NSetGDTSegmentDscr    -- This function will initialize the
;       specified descriptor table entry with the specified data.
;
;   This function can be called in real mode or protected mode.
;
;   Input:
;               Param1  - WORD segment selector
;               Param2  - DWORD 32-bit segment base address
;               Param3  - DWORD 32-bit segment limit
;               param4  - WORD segment access/type
;   Output: returns selector for the segment
;   Errors: none
;   Uses:   Flags

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
cProc   NSetGDTSegmentDscr,<PUBLIC,FAR>,<es,di,ax,bx>
        parmW   Selector
        parmD   Base
        parmD   Limit
        parmW   Access
cBegin
        mov     ax,SEL_GDT
        mov     es,ax
        mov     di,Selector
        and     di,SELECTOR_INDEX

        mov     ax,off_Base                     ; Set segment base
        mov     es:[di].adrBaseLow,ax
        mov     ax,seg_Base
        mov     es:[di].adrBaseHigh,al
        mov     es:[di].adrbBaseHi386,ah

        mov     ax,word ptr Access
        and     ax,070ffh                       ; clear 'G' bit and
                                                ; extended limit bits
        mov     word ptr es:[di].arbSegAccess,ax
                                                ; set access
        mov     ax,seg_Limit
        mov     bx,off_Limit                    ; AX:BX = segment limit
        test    ax,0fff0h                       ; big?
        jz      @f                              ; No
        shr     bx,12d                          ; Yes, make it page granular.
        shl     ax,4d
        or      bx,ax
        mov     ax,seg_Limit
        shr     ax,12d
        or      al,080h                         ; set 'G' bit
@@:
        or      es:[di].cbLimitHi386,al         ; set high limit
        mov     es:[di].cbLimit,bx              ; set low limit
cEnd
endif ; WOW


IFDEF   ROM
; -------------------------------------------------------

DXCODE  ends

; -------------------------------------------------------

DXPMCODE  segment
        assume  cs:DXPMCODE
ENDIF

; -------------------------------------------------------
;   MakeLowSegment      -- This function will create a segment
;       descriptor for the specified low memory paragraph address.
;       The segment length will be set to 64k.  The difference
;       between this and MakeScratchSelector is that this function
;       allocates a new segment descriptor in the user area of
;       the global descriptor table, thus creating a more or less
;       permanent selector.  MakeScratchSelector always uses the
;       same descriptor location in the descriptor table, thus
;       creating a very temporary selector.
;
;   Input:  AX      - paragraph address in low memory
;           BX     - access rights word for the segment
;   Output: AX      - selector to use to access the memory
;   Errors: returns CY clear if no error, CY set if unable to
;           allocate a segment descriptor
;   Uses:   AX used, all else preserved

        assume  ds:DGROUP,es:NOTHING,ss:NOTHING
        public  MakeLowSegment

MakeLowSegment  proc    near

; We need to allocate a segment descriptor, convert the paragraph address
; to a linear byte address, and then initialize the allocated segment
; descriptor.

        push    dx
        push    cx

        mov     cx,bx
        mov     dx,ax               ;paragraph address to DX
        call    AllocateSelector    ;get a segment descriptor to use
        jc      mksl90              ;get out if error
        call    ParaToLinear
        cCall   NSetSegmentDscr,<ax,bx,dx,0,0FFFFh,cx>

        clc
        pop     cx
mksl90: pop     dx
        ret

MakeLowSegment  endp

; -------------------------------------------------------
;   ParaToLinear
;
;   This function will convert a paragraph address in the lower
;   megabyte of memory space into a linear address for use in
;   a descriptor table.
;
;   Input:  DX      - paragraph address
;   Output: DX      - lower word of linear address
;           BX     - high word of linear address
;   Errors: none
;   Uses:   DX, BL used, all else preserved

        assume  ds:NOTHING,es:NOTHING,ss:NOTHING
        public  ParaToLinear

ParaToLinear    proc    near

        mov     bl,dh
        shr     bl,4
        shl     dx,4
        xor     bh,bh
        ret

ParaToLinear    endp


; -------------------------------------------------------
;   MoveMemBlock        -- This routine will copy a block
;       from one place to another.  It copies from the bottom
;       up, so if the address ranges overlap it can only be
;       used to copy down.
;
;   Input:  BX      - selector of GDT
;           CX      - low word of block length
;           DX      - high word of block length
;           DS      - selector pointing to source address
;           ES      - selector pointing to destination address
;   Output: none
;   Errors: none
;   Uses:   modifies segment descriptors selected by ES and DS
;           AX used, other registers preserved

        assume  ds:NOTHING,es:NOTHING,ss:NOTHING
        public  MoveMemBlock

MoveMemBlock:
        cld
        push    cx
        push    dx
        push    si
        push    di
;
mvsd30: xor     si,si
        mov     di,si
        or      dx,dx               ;is there more than 64k left to move
        jz      mvsd32              ;if not, move the amount left
        dec     dx
        push    cx
        mov     cx,8000h            ;move 64k bytes this time
        rep movs word ptr [di],word ptr [si]
        pop     cx
        jmp     short mvsd36
mvsd32: jcxz    mvsd90
        shr     cx,1
        rep movs word ptr [di],word ptr [si]
        jnc     mvsd90
        movs    byte ptr [di],byte ptr [si]
        jmp     short mvsd90
;
; There is still something to move, so bump the segment descriptors to
; point to the next chunk of memory and repeat.
mvsd36:
        mov     di,es
        push    di
        and     di,SELECTOR_INDEX
        mov     es,bx
        inc     es:[di].adrBaseHigh     ;bump the destination segment to
        pop     di                      ; the next 64k boundary

        mov     si,ds
        push    si
        and     si,SELECTOR_INDEX
        inc     es:[si].adrBaseHigh     ;bump the source segment to the
        pop     si                      ; next 64k boundary

        mov     ds,si
        mov     es,di
        jmp     mvsd30
;
; All done
mvsd90: pop     di
        pop     si
        pop     dx
        pop     cx
        ret

; -------------------------------------------------------
        subttl  Utility Routines
        page
; -------------------------------------------------------
;       UTILITY ROUTINES
; -------------------------------------------------------

BeginLowSegment

; -------------------------------------------------------
if DEBUG
; MemCopy       -- This routine is for use in a debugger to
;       copy a block of extended memory down to real mode
;       memory so that it can be looked at.  The data is
;       copied to rgbXfrBuf1.  (This buffer is 4k bytes in
;       size, so don't copy more than this amount)
;
;   Input:  CX      - Number of bytes to copy
;           DS:SI   - protected mode address of start of copy
;   Output; none
;   Errors: none
;   Uses:   all registers trashed.

        assume  ds:NOTHING,es:NOTHING,ss:NOTHING
        public  MemCopy

MemCopy:
        in      al,INTA01
        mov     dl,al
        mov     al,0FFh
        out     INTA01,al
        push    ds
IFDEF   ROM
        SetRMDataSeg
ELSE
        mov     ds,segDXData
ENDIF
        call    EnterProtectedMode
        pop     ds
        push    SEL_DXDATA
        pop     es
        mov     di,offset DGROUP:rgbXfrBuf1
        cld
        rep     movsb
IFDEF   ROM
        push    SEL_DXDATA OR STD_RING
        pop     ds
ELSE
        mov     ds,selDgroup
ENDIF
        call    EnterRealMode
        mov     al,dl
        out     INTA01,al
        int     3

endif

; -------------------------------------------------------

EndLowSegment

;
; -------------------------------------------------------
; -------------------------------------------------------
; -------------------------------------------------------
; -------------------------------------------------------
; -------------------------------------------------------
; -------------------------------------------------------
; -------------------------------------------------------
; -------------------------------------------------------

DXPMCODE    ends

;
;****************************************************************

        end