aboutsummaryrefslogtreecommitdiff
path: root/usr.bin/doscmd/ems.c
blob: 14bbd94fb84267aba4025a184c3c568369d7788c (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
/*-
 * Copyright (c) 1997 Helmut Wirth <hfwirth@ping.at>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice immediately at the beginning of the file, witout modification,
 *    this list of conditions, and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $FreeBSD$
 */

/* 
 * EMS memory emulation
 *
 * To emulate Expanded Memory we use a DOS driver (emsdriv.sys) which
 * routes calls to int 0x67 to this emulator routine. The main entry point
 * is ems_entry(..). The emulator needs to be initialized before the first
 * call. The first step of the initialization is done during program startup
 * the second part is done during DOS boot, from a call of the DOS driver.
 * The DOS driver is neccessary because DOS programs look for it to
 * determine if EMS is available.
 *
 * To emulate a configurable amount of EMS memory we use a file created
 * at startup with the size of the configured EMS memory. This file is
 * mapped into the EMS window like any DOS memory manager would do, using
 * mmap calls.
 *
 * The emulation follows the LIM EMS 4.0 standard. Not all functions of it
 * are implemented yet. The "alter page map and jump" and "alter page map
 * and call" functions are not implemented, because they are rather hard to
 * do. (It would mean a call to the emulator executes a routine in EMS 
 * memory and returns to the emulator, the emulator switches the page map
 * and then returns to the DOS program.) LINUX does not emulate this 
 * functions and I think they were very rarely used by DOS applications.
 *
 * Credits: To the writers of LINUX dosemu, I looked at their code
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/mman.h>
#include <unistd.h>

#include "doscmd.h"
#include "ems.h"

/* Will be configurable */
u_long	ems_max_size = EMS_MAXSIZE * 1024;
u_long ems_frame_addr = EMS_FRAME_ADDR;

/*
 * Method for EMS: Allocate a mapfile with the size of EMS memory
 * and map the needed part into the page frame 
 */

#define EMS_MAP_PATH	"/var/tmp/"	/* Use a big file system */
#define EMS_MAP_FILE	"doscmd.XXXXXX"
static int mapfile_fd = -1;

/* Pages are always 16 kB in size. The page frame is 64 kB, there are
 * 4 positions (0..3) for a page to map in. The pages are numbered from 0 to
 * the highest 16 kB page in the mapfile, depending on the EMS size
 */

EMS_mapping_context ems_mapping_context;

/* Handle and page management (see ems.h) */

/* The handle array. If the pointer is NULL, the handle is unallocated */
static EMS_handle *ems_handle[EMS_NUM_HANDLES];
static u_long ems_alloc_handles;
/* The active handle, if any */
static short active_handle;

/* The page array. It is malloced at runtime, depending on the total
 * allocation size
 */

static EMS_page *ems_page = NULL;
static u_long ems_total_pages;
static u_long ems_alloc_pages;
static u_long ems_free_pages;

/* Local structure used for region copy and move operations */

struct copydesc {
#define SRC_EMS 1
#define DST_EMS 2
    short     copytype;		/* Type of source and destination memory */
    EMS_addr  src_addr;		/* Combined pointer for source */
    EMS_addr  dst_addr;		/* Combined pointer for destination */
    u_long  rest_len;		/* Lenght to copy */
};


/* Local prototypes */
static int init_mapfile();
static void map_page(u_long pagenum, u_char position, short handle, 
	int unmaponly);
static EMS_handle *get_new_handle(long npages);
static void context_to_handle(short handle);
static long find_next_free_handle();
static short lookup_handle(Hname *hp);
static void allocate_pages_to_handle(u_short handle, long npages);
static void allocate_handle(short handle, long npages);
static void reallocate_pages_to_handle(u_short handle, long npages);
static void free_handle(short handle);
static void free_pages_of_handle(short handle);
static void restore_context(EMS_mapping_context *emc);
static void save_context_to_dos(EMScontext *emp);
static int check_saved_context(EMScontext *emp);
static void *get_valid_pointer(u_short seg, u_short offs, u_long size);
static u_long move_ems_to_conv(short handle, u_short src_seg, 
			u_short src_offset, u_long dst_addr, u_long length);
static u_long move_conv_to_ems(u_long src_addr, u_short dst_handle, 
			u_short dst_seg, u_short dst_offset, u_long length);
static u_long move_ems_to_ems(u_short src_hande, u_short src_seg,
			u_short src_offset, u_short dst_handle, 
			u_short dst_seg, u_short dst_offset, u_long length);


/* 
 * EMS initialization routine: Return 1, if successful, return 0 if
 * init problem or EMS disabled
 */

int
ems_init()
{
    int i;

    if (ems_max_size == 0)
	return 0;
    if (init_mapfile() == 0)
	return 0;
    /* Sanity */
    bzero((void *)(&ems_handle[0]), sizeof(ems_handle));
    ems_total_pages = ems_max_size / EMS_PAGESIZE;
    ems_alloc_pages = 0;
    ems_free_pages = ems_total_pages;
    ems_alloc_handles = 0;
    active_handle = 0;
    /* Malloc the page array */
    ems_page = (EMS_page *)malloc(sizeof(EMS_page) * ems_total_pages);
    if (ems_page == NULL) {
	debug(D_ALWAYS, "Could not malloc page array, EMS disabled\n");
	ems_frame_addr = 0;
	ems_max_size = 0;
	ems_total_pages = 0;
	return 0;
    }
    for (i = 0; i < ems_total_pages; i++) {
	ems_page[i].handle = 0;
	ems_page[i].status = EMS_FREE;
    }
    debug(D_EMS, "EMS: Emulation init OK.\n");
    return 1;
}


/* Main entry point */

void
ems_entry(regcontext_t *REGS)
{
    /*
     * If EMS is not enabled, the DOS ems.exe module should not have
     * been loaded. If it is loaded anyway, report software malfunction
     */
    if (ems_max_size == 0) {
	R_AH = EMS_SW_MALFUNC;
	debug(D_EMS, "EMS emulation not enabled\n");
	return;
    }

    switch (R_AH)
    {
	case GET_MANAGER_STATUS:
	    debug(D_EMS, "EMS: Get manager status\n");
	    R_AH = EMS_SUCCESS;	    
	    break;

	case GET_PAGE_FRAME_SEGMENT:
	    debug(D_EMS, "EMS: Get page frame segment\n");
	    R_BX = ems_frame_addr >> 4;
	    R_AH = EMS_SUCCESS;	    
	    break;

	case GET_PAGE_COUNTS:
	    R_BX = ems_total_pages - ems_alloc_pages;
	    R_DX = ems_total_pages;
	    debug(D_EMS, "EMS: Get page count: Returned total=%d, free=%d\n", 
		R_DX, R_BX);
	    R_AH = EMS_SUCCESS;	    
	    break;

	case GET_HANDLE_AND_ALLOCATE:
        {
	    u_short npages;
	    short handle;

	    npages = R_BX;
	    debug(D_EMS, "EMS: Get handle and allocate %d pages: ", npages);

	    /* Enough handles? */
	    if ((handle = find_next_free_handle())  < 0) {
		debug(D_EMS,"Return error:No handles\n");
		R_AH = EMS_OUT_OF_HANDLES;
		break;
	    }
	    /* Enough memory for this request ? */
	    if (npages > ems_free_pages) {
		debug(D_EMS,"Return error:Request too big\n");
		R_AH = EMS_OUT_OF_LOG;
		break;
	    }
	    if (npages > ems_total_pages) {
		debug(D_EMS,"Return error:Request too big\n");
		R_AH = EMS_OUT_OF_PHYS;
		break;
	    }
	    /* Not allowed to allocate zero pages with this function */
	    if (npages == 0) {
		debug(D_EMS,"Return error:Cannot allocate 0 pages\n");
		R_AH = EMS_ZERO_PAGES;
		break;
	    }
	    /* Allocate the handle */
	    allocate_handle(handle, npages);

	    /* Allocate the pages */
	    allocate_pages_to_handle(handle, npages);
	    R_DX = handle;
	    R_AH = EMS_SUCCESS;	    
	    debug(D_EMS,"Return success:Handle = %d\n", handle);
	    break;
	}

	case MAP_UNMAP:
	{
	    u_char position;
	    u_short hpagenum, spagenum;
	    short handle;
	    
	    debug(D_EMS, "EMS: Map/Unmap handle=%d, pos=%d, pagenum=%d ", 
		R_DX, R_AL, R_BX);
	    handle = R_DX;
	    position = R_AL;
	    if (position > 3) {
		debug(D_EMS, "invalid position\n");
		R_AH = EMS_ILL_PHYS;
		break;
	    }
	    hpagenum = R_BX;
	    /* This succeeds without a valid handle ! */
	    if (hpagenum == 0xffff) {
		/* Unmap only */
		map_page(0, position, handle, 1);
		debug(D_EMS, "(unmap only) success\n");
		R_AH = EMS_SUCCESS;
		break;
	    }
	    if (handle > 255 || handle == 0 || ems_handle[handle] == NULL) {
		R_AH = EMS_INV_HANDLE;
		debug(D_EMS, "invalid handle\n");
		break;
	    }
	    if (hpagenum >= ems_handle[handle]->npages) {
		R_AH = EMS_LOGPAGE_TOOBIG;
		debug(D_EMS, "invalid pagenumber\n");
		break;
	    }
	    spagenum = ems_handle[handle]->pagenum[hpagenum];
	    map_page(spagenum, position, handle, 0);
	    debug(D_EMS, "success\n");
	    R_AH = EMS_SUCCESS;
	    break;
	}

	case DEALLOCATE_HANDLE:
	{
	    short handle;

	    /* Handle valid ? */
	    handle = R_DX;
	    debug(D_EMS, "EMS: Deallocate handle %d\n", handle);
	    if (handle > 255 || ems_handle[handle] == NULL) {
		R_AH = EMS_INV_HANDLE;
		break;
	    }
	    /* Mapping context saved ? */
	    if (ems_handle[handle]->mcontext != NULL) {
		R_AH = EMS_SAVED_MAP;
		break;
	    }

	    free_pages_of_handle(handle);
	    free_handle(handle);
	    R_AH = EMS_SUCCESS;	    
	    break;
	}

	case GET_EMM_VERSION:
	    debug(D_EMS, "EMS: Get version\n");
	    R_AL = EMS_VERSION;
	    R_AH = EMS_SUCCESS;	    
	    break;

	case SAVE_PAGE_MAP:
	{
	    short handle;

	    debug(D_EMS, "EMS: Save page map\n");
	    handle = R_DX;
	    if (handle > 255 || handle == 0 || ems_handle[handle] == NULL) {
		R_AH = EMS_INV_HANDLE;
		break;
	    }
	    if (ems_handle[handle]->mcontext != NULL) {
		/* There is already a context saved */
		if (memcmp((void *)ems_handle[handle]->mcontext,
		           (void *)&ems_mapping_context,
			   sizeof(EMS_mapping_context)) == 0)
		     R_AH = EMS_ALREADY_SAVED;
		else 
		     R_AH = EMS_NO_ROOM_TO_SAVE;
		break;
	    }
	    context_to_handle(handle);
	    R_AH = EMS_SUCCESS;	    
	    break;
	}

	case RESTORE_PAGE_MAP:
	{
	    short handle;

	    debug(D_EMS, "EMS: Restore page map\n");
	    handle = R_DX;
	    if (handle > 255 || handle == 0 || ems_handle[handle] == NULL) {
		R_AH = EMS_INV_HANDLE;
		break;
	    }
	    if (ems_handle[handle]->mcontext == NULL) {
		R_AH = EMS_NO_SAVED_CONTEXT;
		break;
	    }
	    restore_context(ems_handle[handle]->mcontext);
	    free((void *)ems_handle[handle]->mcontext);
	    ems_handle[handle]->mcontext = NULL;
	    R_AH = EMS_SUCCESS;	    
	    break;
	}

	case RESERVED_1:
	case RESERVED_2:
	    debug(D_ALWAYS, "Reserved function called: %02x\n", R_AH);
	    R_AH = EMS_FUNC_NOSUP;
	    break;

	case GET_HANDLE_COUNT:
	    debug(D_EMS, "EMS: Get handle count\n");
	    R_BX = ems_alloc_handles + 1;
	    R_AH = EMS_SUCCESS;	    
	    break;

	case GET_PAGES_OWNED:
	{
	    short handle;

	    debug(D_EMS, "EMS: Get pages owned\n");
	    /* Handle valid ? */
	    handle = R_DX;
	    if (handle > 255 || ems_handle[handle] == NULL) {
		R_AH = EMS_INV_HANDLE;
		break;
	    }
	    if (handle == 0)
		R_BX = 0;
	    else
		R_BX = ems_handle[handle]->npages;
	    R_AH = EMS_SUCCESS;	    
	    break;
	}

	case GET_PAGES_FOR_ALL:
	{
	    EMShandlepage *ehp;
	    int safecount;
	    int i;

	    debug(D_EMS, "EMS: Get pages for all\n");
	    /* Get the address passed from DOS app */
	    ehp = (EMShandlepage *)get_valid_pointer(R_ES, R_DI,
			sizeof(EMShandlepage) * ems_alloc_handles); 
	    if (ehp == NULL) {
		R_AH = EMS_SW_MALFUNC;
		break;
	    }

	    R_BX = ems_alloc_handles;
	    safecount = 0;
	    for (i = 0; i < 255; i++) {
		if (ems_handle[i] != NULL) {
		    if (safecount > (ems_alloc_handles+1))
		        fatal("EMS: ems_alloc_handles is wrong, cannot continue\n");
		    ehp->handle = i;
		    ehp->npages = ems_handle[i]->npages;
		    ehp++;
		    safecount++;
		}
	    }
	    R_AH = EMS_SUCCESS;	    
	    break;
        }

	case PAGE_MAP:
	/* This function is a nuisance. It was invented to save time and
         * memory, but in our case it is useless. We have to support it
         * but we use the same save memory as for the page map function.
         * It uses only 20 bytes anyway. We store/restore the entire mapping
	 */
	case PAGE_MAP_PARTIAL:
	{
	    u_long addr;
	    int subfunction;
	    EMScontext *src, *dest;

	    debug(D_EMS, "EMS: Page map ");
	    subfunction = R_AL;
	    if (R_AH == PAGE_MAP_PARTIAL) {
		debug(D_EMS, "partial ");
		/* Page map partial has slightly different subfunctions
		 * GET_SET does not exist and is GET_SIZE in this case 
		 */
		if (subfunction == GET_SET)
		    subfunction = GET_SIZE;
	    }
	    switch (subfunction)
	    {
		case GET:
		{
		    debug(D_EMS, "get\n");
		    /* Get the address passed from DOS app */
		    dest = (EMScontext *)get_valid_pointer(R_ES, R_DI, 
			sizeof(EMScontext));
		    if (dest == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
		    }
		    save_context_to_dos(dest);
		    R_AH = EMS_SUCCESS;     
	            break;
		}
		case SET:
		{
		    debug(D_EMS, "set\n");
		    src = (EMScontext *)get_valid_pointer(R_DS, R_SI, 
			sizeof(EMScontext));
		    if (src == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
		    }
		    if (check_saved_context(src) == 0) {
			R_AH = EMS_SAVED_CONTEXT_BAD;
			break;
		    }
		    restore_context(&src->ems_saved_context);
		    R_AH = EMS_SUCCESS;     
	            break;
		}
		case GET_SET:
		{
		    debug(D_EMS, "get/set\n");
		    dest = (EMScontext *)get_valid_pointer(R_ES, R_DI, 
			sizeof(EMScontext));
		    if (dest == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
		    }
		    save_context_to_dos(dest);
		    src = (EMScontext *)get_valid_pointer(R_DS, R_SI, 
			sizeof(EMScontext));
		    if (src == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
		    }
		    if (check_saved_context(src) == 0) {
			R_AH = EMS_SAVED_CONTEXT_BAD;
			break;
		    }
		    restore_context(&src->ems_saved_context);
		    R_AH = EMS_SUCCESS;     
	            break;
		}
		case GET_SIZE:
		    debug(D_EMS, "get size\n");
		    R_AL = (sizeof(EMScontext) + 1) & 0xfe;
		    R_AH = EMS_SUCCESS;     
	            break;
		default:
		    debug(D_EMS, "invalid subfunction\n");
		    R_AH = EMS_INVALID_SUB;
		    break;
	    }
	    break;
	}

	case MAP_UNMAP_MULTI_HANDLE:
	{
	    u_char position;
	    u_short hpagenum, spagenum;
	    short handle;
	    EMSmapunmap *mp;
	    int n_entry, i;
	    
	    
	    debug(D_EMS, "EMS: Map/Unmap multiple ");

	    if ((n_entry = R_CX) > 3) {
		R_AH = EMS_ILL_PHYS;
	    }

	    /* This is valid according to the LIM EMS 4.0 spec */
	    if (n_entry == 0) {
		R_AH = EMS_SUCCESS;     
	        break;
	    }

	    handle = R_DX;
	    if (handle > 255 || handle == 0 || ems_handle[handle] == NULL) {
		R_AH = EMS_INV_HANDLE;
		break;
	    }

	    mp = (EMSmapunmap *)get_valid_pointer(R_DS, R_SI,
			sizeof(EMSmapunmap) * n_entry);
	    if (mp == NULL) {
		R_AH = EMS_SW_MALFUNC;
		break;
	    }

	    R_AH = EMS_SUCCESS;
	    /* Walk through the table and map/unmap */
	    for (i = 0; i < n_entry; i++) {
		hpagenum = mp->log;
		/* Method is in R_AL */
		if (R_AL == 0) {
		    debug(D_EMS, "phys page method\n");
		    if (mp->phys <= 3) {
		    	position = mp->phys;
		    } else {
			R_AH = EMS_ILL_PHYS;
			break;
		    }
		} else if (R_AL == 1) {
		    /* Compute position from segment address */
	    	    u_short p_seg;

		    debug(D_EMS, "segment method\n");
		    p_seg = mp->phys;
		    p_seg -= ems_frame_addr;
		    p_seg /= EMS_PAGESIZE;
		    if (p_seg <= 3) {
			position = p_seg;
		    } else {
			R_AH = EMS_ILL_PHYS;
			break;
		    }
		} else {
		    debug(D_EMS, "invalid subfunction\n");
		    R_AH = EMS_INVALID_SUB;
		    break;
		}

		mp++;
	        if (hpagenum == 0xffff) {
		    /* Unmap only */
		    map_page(0, position, handle, 1);
		    continue;
	        }
	        if (hpagenum >= ems_handle[handle]->npages) {
		    R_AH = EMS_LOGPAGE_TOOBIG;
		    break;
	        }
	        spagenum = ems_handle[handle]->pagenum[hpagenum];
	        map_page(spagenum, position, handle, 0);
	    }
	    break;
	}

	case REALLOC_PAGES:
	{
	    short handle;
	    u_long newpages;

	    debug(D_EMS, "EMS: Realloc pages ");

	    handle = R_DX;
	    if (handle > 255 || handle == 0 || ems_handle[handle] == NULL) {
		R_AH = EMS_INV_HANDLE;
		debug(D_EMS, "invalid handle\n");
		break;
	    }
	    newpages = R_BX;
	    debug(D_EMS, "changed from %d to %d pages\n", 
		ems_handle[handle]->npages, newpages);

	    /* Case 1: Realloc to zero pages */
	    if (newpages == 0) {
		free_pages_of_handle(handle);
		R_AH = EMS_SUCCESS;     
	        break;
	    }
	    /* Case 2: New allocation is equal to allocated number */
	    if (newpages == ems_handle[handle]->npages) {
		R_AH = EMS_SUCCESS;     
	        break;
	    }
	    /* Case 3: Reallocate to bigger and smaller sizes */
	    if (newpages > ems_handle[handle]->npages) {
		if (newpages > ems_free_pages) {
            	    R_AH = EMS_OUT_OF_LOG;
                    break;
		}
		if (newpages > ems_total_pages) {
            	    R_AH = EMS_OUT_OF_PHYS;
                    break;
		}
	    }
	    reallocate_pages_to_handle(handle, newpages);
	    R_AH = EMS_SUCCESS;     
	    break;
	}

	/* We do not support nonvolatile pages */
	case HANDLE_ATTRIBUTES:
	    debug(D_EMS, "Handle attributes called\n");
	    switch (R_AL) {
		case GET:
		case SET:
		    R_AH = EMS_FEAT_NOSUP;
		    break;
		case HANDLE_CAPABILITY:
		    R_AL = 0; 		/* Volatile only */
		    R_AH = EMS_SUCCESS;     
		    break;
		default:
		    R_AH = EMS_FUNC_NOSUP;
		    break;
	    }
	    break;

	case HANDLE_NAME:
	{
	    short handle;
	    Hname *hp;

	    handle = R_DX;
	    if (handle > 255 || handle == 0 || ems_handle[handle] == NULL) {
		R_AH = EMS_INV_HANDLE;
		debug(D_EMS, "invalid handle\n");
		break;
	    }
	    switch (R_AL) {
		case GET:
		    if ((hp = (Hname *)get_valid_pointer(R_ES, R_DI, 8))
		     == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
		    }
		    *hp = ems_handle[handle]->hname;
		    R_AH = EMS_SUCCESS;     
		    break;

		case SET:
		    if ((hp = (Hname *)get_valid_pointer(R_DS, R_SI, 8))
		     == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
		    }
		    /* If the handle name is not 0, it may not exist */
		    if ((hp->ul_hn[0] | hp->ul_hn[1]) != 0) {
			if (lookup_handle(hp) == 0) {
			    ems_handle[handle]->hname = *hp;
			    R_AH = EMS_SUCCESS;     
			} else {
			    R_AH = EMS_NAME_EXISTS;     
			    break;
			}
		    } else {
		        /* Name is deleted (set to zeros) */
			ems_handle[handle]->hname = *hp;
			R_AH = EMS_SUCCESS;     
		    }
		    break;

		default:
		    R_AH = EMS_FUNC_NOSUP;
		    break;
	    }
	    break;
	}

	case HANDLE_DIRECTORY:
	{
	    int i;
	    EMShandledir *hdp;
	    Hname *hp;
	    short handle;

	    switch(R_AL) {
		case GET:
		    hdp = (EMShandledir *)get_valid_pointer(R_ES, R_DI, 
			sizeof(EMShandledir) * ems_alloc_handles);
		    if (hdp == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
		    }
		    for (i = 0; i < EMS_NUM_HANDLES; i++) {
			if (ems_handle[i] != NULL) {
			    hdp->log = i;
			    hdp->name = ems_handle[i]->hname;
			}
		    }
		    R_AH = EMS_SUCCESS;     
		    break;

		case HANDLE_SEARCH:
		    hp = (Hname *)get_valid_pointer(R_DS, R_SI, 8);
		    if (hp == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
		    }
		    /* Cannot search for NULL handle name */
		    if ((hp->ul_hn[0] | hp->ul_hn[1]) != 0) {
			R_AH = EMS_NAME_EXISTS;
			break;
		    }
		    if ((handle = lookup_handle(hp)) == 0) {
			R_AH = EMS_HNAME_NOT_FOUND;     
		    } else {
			R_DX = handle;
			R_AH = EMS_SUCCESS;     
		    }
		    break;

		case GET_TOTAL_HANDLES:
		    R_AH = EMS_SUCCESS;     
		    R_BX = EMS_NUM_HANDLES;	/* Includes OS handle */
		    break;

		default:
		    R_AH = EMS_FUNC_NOSUP;
		    break;
	    }
	    break;
	}


	/* I do not know if we need this. LINUX emulation leaves it out
         * so I leave it out too for now.
	 */
	case ALTER_PAGEMAP_JUMP:
	    debug(D_ALWAYS, "Alter pagemap and jump used!\n");
	    R_AH = EMS_FUNC_NOSUP;
	    break;
	case ALTER_PAGEMAP_CALL:
	    debug(D_ALWAYS, "Alter pagemap and call used!\n");
	    R_AH = EMS_FUNC_NOSUP;
	    break;


	case MOVE_MEMORY_REGION:
	{
	    EMSmovemem *emvp;
	    u_long src_addr, dst_addr;
	    u_short src_handle, dst_handle;

	    if (R_AL == EXCHANGE)
	    	debug(D_EMS, "EMS: Exchange memory region ");
	    else
	    	debug(D_EMS, "EMS: Move memory region ");

	    emvp = (EMSmovemem *)get_valid_pointer(R_DS, R_SI,
			sizeof(EMSmovemem));
	    if (emvp == NULL) {
		debug(D_EMS, "Invalid structure pointer\n");
		R_AH = EMS_SW_MALFUNC;
		break;
	    }
	    /* Zero length is not an error */
	    if (emvp->length == 0) {
		debug(D_EMS, "Zero length\n");
		R_AH = EMS_SUCCESS;     
		break;
 	    }
	    /* Some checks */
	    if (emvp->src_type == EMS_MOVE_CONV) {
		/* Conventional memory source */
		src_addr = MAKEPTR(emvp->src_seg, emvp->src_offset);
		/* May not exceed conventional memory */
		if ((src_addr + emvp->length) > 640 * 1024) {
		    R_AH = EMS_SW_MALFUNC;
		    break;
		}
	    } else {
		/* Check the handle */
		src_handle = emvp->src_handle;
	    	if (src_handle > 255 || src_handle == 0 || 
			ems_handle[src_handle] == NULL) {
		    R_AH = EMS_INV_HANDLE;
		    debug(D_EMS, "invalid source handle\n");
		    break;
		}
		/* Offset may not exceed page size */
		if (emvp->src_offset >= (16 * 1024)) {
		    R_AH = EMS_PAGEOFFSET;
		    debug(D_EMS, "source page offset too big\n");
		    break;
		}
	    }

	    if (emvp->dst_type == EMS_MOVE_CONV) {
		/* Conventional memory source */
		dst_addr = MAKEPTR(emvp->dst_seg, emvp->dst_offset);
		/* May not exceed conventional memory */
		if ((dst_addr + emvp->length) > 640 * 1024) {
		    R_AH = EMS_SW_MALFUNC;
		    break;
		}
	    } else {
		/* Check the handle */
		dst_handle = emvp->dst_handle;
	    	if (dst_handle > 255 || dst_handle == 0 || 
			ems_handle[dst_handle] == NULL) {
		    R_AH = EMS_INV_HANDLE;
		    debug(D_EMS, "invalid destination handle\n");
		    break;
		}
		/* Offset may not exceed page size */
		if (emvp->dst_offset >= (16 * 1024)) {
		    R_AH = EMS_PAGEOFFSET;
		    debug(D_EMS, "destination page offset too big\n");
		    break;
		}
	    }

	    if (R_AL == MOVE) {
		/* If it is conventional memory only, do it */
	        if (emvp->src_type == EMS_MOVE_CONV &&
		    emvp->dst_type == EMS_MOVE_CONV) {
		    memmove((void *)dst_addr, (void *)src_addr, 
			(size_t) emvp->length);
		    debug(D_EMS, "conventional to conventional memory done\n");
		    R_AH = EMS_SUCCESS;     
		    break;
	        }
	        if (emvp->src_type == EMS_MOVE_EMS &&
		    emvp->dst_type == EMS_MOVE_CONV)
		    R_AH = move_ems_to_conv(src_handle, emvp->src_seg,
			emvp->src_offset, dst_addr, emvp->length);
	        else if (emvp->src_type == EMS_MOVE_CONV &&
                    emvp->dst_type == EMS_MOVE_EMS)
		    R_AH = move_conv_to_ems(src_addr, dst_handle,
		              emvp->dst_seg, emvp->dst_offset, emvp->length);
	        else
		    R_AH = move_ems_to_ems(src_handle, emvp->src_seg,
			emvp->src_offset, dst_handle, emvp->dst_seg,
			emvp->dst_offset, emvp->length);
	        debug(D_EMS, " done\n");
	        break;
	    } else {
		/* exchange memory region */

		/* We need a scratch area for the exchange */
		void *buffer;
		if ((buffer = malloc(emvp->length)) == NULL)
		    fatal("EMS: Could not malloc scratch area for exchange");

		/* If it is conventional memory only, do it */
	        if (emvp->src_type == EMS_MOVE_CONV &&
		    emvp->dst_type == EMS_MOVE_CONV) {
		    /* destination -> buffer */
		    memmove(buffer, (void *)dst_addr, (size_t) emvp->length);
		    /* Source -> destination */
		    memmove((void *)dst_addr, (void *)src_addr, 
			(size_t) emvp->length);
		    /* Buffer -> source */
		    memmove((void *)src_addr, buffer, (size_t) emvp->length);
		    free(buffer);
		    debug(D_EMS, "conventional to conventional memory done\n");
		    R_AH = EMS_SUCCESS;     
		    break;
	        }

		/* Exchange EMS with conventional */
	        if (emvp->src_type == EMS_MOVE_EMS &&
		    emvp->dst_type == EMS_MOVE_CONV) {
		    /* Destination -> buffer */
		    memmove(buffer, (void *)dst_addr, (size_t) emvp->length);
		    /* Source -> destination */
		    R_AH = move_ems_to_conv(src_handle, emvp->src_seg,
                              emvp->src_offset, dst_addr, emvp->length);
                    if (R_AH != EMS_SUCCESS) {
			free(buffer);
			break;
		    }
		    /* Buffer -> source */
		    R_AH = move_conv_to_ems((u_long)buffer, src_handle,
		              emvp->src_seg, emvp->src_offset, emvp->length);

                /* Exchange conventional with EMS */
		} else if (emvp->src_type == EMS_MOVE_CONV &&
                           emvp->dst_type == EMS_MOVE_EMS) {
		    /* Destination -> buffer */
		    R_AH = move_ems_to_conv(dst_handle, emvp->dst_seg,
			emvp->dst_offset, (u_long)buffer, emvp->length);
                    if (R_AH != EMS_SUCCESS) {
			free(buffer);
			break;
		    }
		    /* Source -> destination */
		    R_AH = move_conv_to_ems((u_long)buffer, dst_handle,
		              emvp->dst_seg, emvp->dst_offset, emvp->length);
		    /* Buffer -> source */
		    memmove(buffer, (void *)src_addr, (size_t) emvp->length);

		/* Exchange EMS with EMS */
		} else {
		    /* Destination -> buffer */
		    R_AH = move_ems_to_conv(dst_handle, emvp->dst_seg,
			emvp->dst_offset, (u_long)buffer, emvp->length);
                    if (R_AH != EMS_SUCCESS) {
			free(buffer);
			break;
		    }
		    /* Source -> destination */
		    R_AH = move_ems_to_ems(src_handle, emvp->src_seg,
			emvp->src_offset, dst_handle, emvp->dst_seg,
			emvp->dst_offset, emvp->length);
		    if (R_AH != EMS_SUCCESS) {
			free(buffer);
			break;
		    }
		    /* Buffer -> source */
		    R_AH = move_conv_to_ems((u_long)buffer, src_handle,
		              emvp->src_seg, emvp->src_offset, emvp->length);
	        }
		free(buffer);
	    }
	    debug(D_EMS, " done\n");
	    break;
	}

	case GET_MAPPABLE_PHYS_ADDR:
	{
	    switch (R_AL) {
		case GET_ARRAY:
		{
		    EMSaddrarray *eadp;
		    int i;
		    u_short seg;

		    eadp = (EMSaddrarray *)get_valid_pointer(R_ES, R_DI, 
                        sizeof(EMSaddrarray) * 4);
	    	    if (eadp == NULL) {
			R_AH = EMS_SW_MALFUNC;
			break;
	    	    }
		    for (i = 0, seg = (ems_frame_addr >> 4); i < 4; i++) {
			eadp->segm = seg;
			eadp->phys = i;
			eadp++;
			seg += 1024;
		    }
		    R_AH = EMS_SUCCESS;     
		    break;
		}
		case GET_ARRAY_ENTRIES:
		    /* There are always 4 positions, 4*16kB = 64kB */
		    R_CX = 4;
		    R_AH = EMS_SUCCESS;
		    break;
		default:
		    R_AH = EMS_FUNC_NOSUP;
		    break;
	    }
	    break;
	}

	/* This is an OS function in the LIM EMS 4.0 standard: It is
	 * usable only by an OS and its use can be disabled for all other
	 * programs. I think we do not need to support it. It is not
	 * implemented and it reports "disabled" to any caller.
	 */
	case GET_HW_CONFIGURATION:
	    R_AH = EMS_FUNCTION_DISABLED;
	    break;

	/* This function is a little different, it was defined with
	 * LIM EMS 4.0: It is allowed to allocate zero pages and raw
	 * page size (i.e. page size != 16kB) is supported. We have 
	 * only 16kB pages, so the second difference does not matter.
	 */
	case ALLOCATE_PAGES:
        {
	    u_short npages;
	    short handle;

	    npages = R_BX;
	    debug(D_EMS, "EMS: Get handle and allocate %d pages: ", npages);

	    /* Enough handles? */
	    if ((handle = find_next_free_handle()) < 0) {
		debug(D_EMS,"Return error:No handles\n");
		R_AH = EMS_OUT_OF_HANDLES;
		break;
	    }
	    /* Enough memory for this request ? */
	    if (npages > ems_free_pages) {
		debug(D_EMS,"Return error:Request too big\n");
		R_AH = EMS_OUT_OF_LOG;
		break;
	    }
	    if (npages > ems_total_pages) {
		debug(D_EMS,"Return error:Request too big\n");
		R_AH = EMS_OUT_OF_PHYS;
		break;
	    }

	    /* Allocate the handle */
	    allocate_handle(handle, npages);

	    /* Allocate the pages */
	    allocate_pages_to_handle(handle, npages);
	    R_DX = handle;
	    R_AH = EMS_SUCCESS;	    
	    debug(D_EMS,"Return success:Handle = %d\n", handle);
	    break;
	}

	/* This is an OS function in the LIM EMS 4.0 standard: It is
	 * usable only by an OS and its use can be disabled for all other
	 * programs. I think we do not need to support it. It is not
	 * implemented and it reports "disabled" to any caller.
	 */
	case ALTERNATE_MAP_REGISTER:
	    R_AH = EMS_FUNCTION_DISABLED;
	    break;

	/* We cannot support that ! */
	case PREPARE_WARMBOOT:
	    R_AH = EMS_FUNC_NOSUP;
	    break;

	case OS_FUNCTION_SET:
	    R_AH = EMS_FUNCTION_DISABLED;
	    break;

unknown:
	default:
	    debug(D_ALWAYS, "EMS: Unknown function called: %02x\n", R_AH);
	    R_AH = EMS_FUNC_NOSUP;
	    break;
    }
}

/* Initialize the EMS memory: Return 1 on success, 0 on failure */

static int
init_mapfile()
{
    char path[256];
    int mfd;

    /* Sanity */
    if (ems_max_size == 0)
	return;
    strcpy(path, EMS_MAP_PATH);
    strcat(path, EMS_MAP_FILE);

    mfd = mkstemp(path);

    if (mfd < 0) {
        debug(D_ALWAYS, "Could not create EMS mapfile, ");
	goto fail;
    }
    unlink(path);
    mapfile_fd = squirrel_fd(mfd);

    if (lseek(mapfile_fd, (off_t)(ems_max_size - 1), 0) < 0) {
	debug(D_ALWAYS, "Could not seek into EMS mapfile, ");
	goto fail;
    }
    if (write(mapfile_fd, "", 1) < 0) {
	debug(D_ALWAYS, "Could not write to EMS mapfile, ");
	goto fail;
    }
    /* Unmap the entire page frame */
    if (munmap((caddr_t)ems_frame_addr, 64 * 1024) < 0) {
	debug(D_ALWAYS, "Could not unmap EMS page frame, ");
	goto fail;
    }
    /* DOS programs will access the page frame without allocating 
     * pages first. Microsoft diagnose MSD.EXE does this, for example
     * We need to have memory here to avoid segmentation violation
     */
    if (mmap((caddr_t)ems_frame_addr, 64 * 1024,
              PROT_EXEC | PROT_READ | PROT_WRITE,
              MAP_ANON | MAP_FIXED | MAP_INHERIT | MAP_SHARED,
	      -1, 0) < 0) {
	debug(D_ALWAYS, "Could not map EMS page frame, ");
	goto fail;
    }
    bzero((void *)&ems_mapping_context, sizeof(EMS_mapping_context));
    return (1);

fail:
    debug(D_ALWAYS, "EMS disabled\n");
    ems_max_size = 0;
    ems_frame_addr = 0;
    return (0);
}

/* Map/Unmap pages into one of four positions in the frame segment */

static void
map_page(u_long pagenum, u_char position, short handle, int unmaponly)
{
    caddr_t map_addr;
    size_t  len;
    off_t   file_offs;

    if (position > 3)
	fatal("EMS: Internal error: Mapping position\n");

    map_addr = (caddr_t)(ems_frame_addr + (1024 * 16 * (u_long)position));
    len = 1024 * 16;
    file_offs = (off_t)(pagenum * 16 * 1024);

    if (ems_mapping_context.pos_mapped[position]) {
        if (munmap(map_addr, len) < 0) {
             fatal("EMS unmapping error: %s\nCannot recover\n", 
		strerror(errno));
	}
	ems_page[ems_mapping_context.pos_pagenum[position]].status 
		&= ~EMS_MAPPED;
	ems_mapping_context.pos_mapped[position] = 0;
	ems_mapping_context.handle[position] = 0;
    }
    if (unmaponly) {
        /* DOS programs will access the page frame without allocating 
         * pages first. Microsoft diagnose MSD.EXE does this, for example
         * We need to have memory here to avoid segmentation violation
         */
    	if (mmap((caddr_t)ems_frame_addr, 64 * 1024,
              PROT_EXEC | PROT_READ | PROT_WRITE,
              MAP_ANON | MAP_FIXED | MAP_INHERIT | MAP_SHARED,
	      -1, 0) < 0)
	    fatal("Could not map EMS page frame during unmap only\n");
	return;
    }
    if (mmap(map_addr, len,
              PROT_EXEC | PROT_READ | PROT_WRITE,
              MAP_FILE | MAP_FIXED | MAP_INHERIT | MAP_SHARED,
              mapfile_fd, file_offs) < 0) {
        fatal("EMS mapping error: %s\nCannot recover\n", strerror(errno));
    }
    ems_mapping_context.pos_mapped[position] = 1;
    ems_mapping_context.pos_pagenum[position] = pagenum;
    ems_mapping_context.handle[position] = handle;
    ems_page[pagenum].status |= EMS_MAPPED;
}

/* Get a pointer from VM86 app, check it and return it. This returns NULL
 * if the pointer is not valid. We can check only for very limited
 * criteria: The pointer and the area defined by size may not point to
 * memory over 1MB and it may not may to addresses under 1kB, because there
 * is the VM86 interrupt table.
 */
static void 
*get_valid_pointer(u_short seg, u_short offs, u_long size)
{
    u_long addr;
    addr = MAKEPTR(seg, offs);
    /* Check bounds */
    if ((addr + size) >= (1024 * 1024) || addr < 1024)
	return NULL;
    else
	return (void *)addr;
}

/* Malloc a new handle */
static EMS_handle
*get_new_handle(long npages)
{
    EMS_handle *ehp;
    size_t dynsize = sizeof(EMS_handle) + sizeof(short) * npages;

    if ((ehp = calloc(1, dynsize)) == NULL)
	fatal("Cannot malloc EMS handle, cannot continue\n");
    return ehp;
}

/* Allocate a mapping context to a handle */
static void
context_to_handle(short handle)
{
    EMS_mapping_context *emc;

    if (ems_handle[handle] == NULL)
	fatal("EMS context_to_handle called with invalid handle\n");
    if ((emc = calloc(1, sizeof(EMS_mapping_context))) == NULL)
	fatal("EMS Cannot malloc mapping context, cannot continue\n");
    ems_handle[handle]->mcontext = emc;
    memmove((void *)emc, (void *)&ems_mapping_context, 
             sizeof(EMS_mapping_context));
}
   
/* Find the next free handle, returns -1 if there are no more handles */
static long
find_next_free_handle()
{
    int i;

    if (ems_alloc_handles >= 255)
	return (-1);
    /* handle 0 is OS handle */
    for (i = 1; i < EMS_NUM_HANDLES; i++) {
	if (ems_handle[i] == NULL)
	    return (i);
    }
    fatal("EMS handle count garbled, should not happen\n");
}

/* Look for a named handle, returns 0 if not found, else handle */
static short
lookup_handle(Hname *hp)
{
    int i;

    for (i = 1; i < EMS_NUM_HANDLES; i++) {
	if (ems_handle[i] != NULL) {
	    if (hp->ul_hn[0] == ems_handle[i]->hname.ul_hn[0] &&
	        hp->ul_hn[1] == ems_handle[i]->hname.ul_hn[1])
		return (i);
	}
    }
    return (0);
}    

/* Malloc a new handle struct and put into array at index handle */
static void
allocate_handle(short handle, long npages)
{
    if (ems_handle[handle] != NULL)
	fatal("EMS allocate_handle, handle was not free\n");
    ems_handle[handle] = get_new_handle(npages);
    ems_alloc_handles++;
}

/* Free a handle, return its memory. Call this *after* freeing the
 * allocated pages !
 */
static void
free_handle(short handle)
{
    if (ems_handle[handle] == NULL)
	fatal("EMS free_handle, handle was free\n");
    if (ems_handle[handle]->mcontext != NULL)
	free((void *)ems_handle[handle]->mcontext);
    free((void *)ems_handle[handle]);
    ems_handle[handle] = NULL;
    ems_alloc_handles--;
}


/* Allocates npages to handle. Call this routine only after you have
 * ensured there are enough free pages *and* the new handle is in place
 * in the handle array !
 */
static void
allocate_pages_to_handle(u_short handle, long npages)
{
    int syspagenum;
    int pages_to_alloc = npages;
    int allocpagenum = 0;

    /* sanity */
    if (handle > 255 || ems_handle[handle] == NULL)
	fatal("EMS allocate_pages_to_handle called with invalid handle\n");

    ems_handle[handle]->npages = npages;    
    for (syspagenum = 0; syspagenum < ems_total_pages; syspagenum++) {
	if (ems_page[syspagenum].status == EMS_FREE) {
	    ems_page[syspagenum].handle = handle;
	    ems_page[syspagenum].status = EMS_ALLOCED;
	    ems_handle[handle]->pagenum[allocpagenum] = syspagenum;
	    allocpagenum++;
	    pages_to_alloc--;
	    if (pages_to_alloc == 0)
		break;
	}
    }
    if (pages_to_alloc > 0)
	fatal("EMS allocate_pages_to_handle found not enough free pages\n");
    ems_alloc_pages += npages;
    ems_free_pages -= npages;
}

/* Reallocates npages to handle. Call this routine only after you have
 * ensured there are enough free pages *and* the new handle is in place
 * in the handle array !
 */
static void
reallocate_pages_to_handle(u_short handle, long npages)
{
    int syspagenum;
    int pages_to_alloc;
    int allocpagenum;
    long delta;
    size_t dynsize;
    EMS_handle *emp;

    /* sanity */
    if (handle > 255 || ems_handle[handle] == NULL)
	fatal("EMS allocate_pages_to_handle called with invalid handle\n");

    delta = npages - ems_handle[handle]->npages;
    if (delta > 0) {
	/* Grow array size and allocation */

	emp = ems_handle[handle];
	dynsize = sizeof(EMS_handle) + sizeof(short) * npages;

	/* First step: Make room in the handle pagenum array */
	if ((emp = (EMS_handle *)realloc((void *)emp, dynsize)) == NULL)
	    fatal("Cannot malloc EMS handle, cannot continue\n");
	ems_handle[handle] = emp;

	/* Second step: Add pages to the handle */ 
        pages_to_alloc = delta;
	allocpagenum = ems_handle[handle]->npages;
        ems_handle[handle]->npages = npages;    
        for (syspagenum = 0; syspagenum < ems_total_pages; syspagenum++) {
	    if (ems_page[syspagenum].status == EMS_FREE) {
	        ems_page[syspagenum].handle = handle;
	        ems_page[syspagenum].status = EMS_ALLOCED;
	        ems_handle[handle]->pagenum[allocpagenum] = syspagenum;
	        allocpagenum++;
	        pages_to_alloc--;
	        if (pages_to_alloc == 0)
		    break;
	    }
        }
    	if (pages_to_alloc > 0)
	    fatal("EMS allocate_pages_to_handle found not enough free pages\n");

    } else {
	/* Shrink array size and allocation */

	/* First step: Deallocate all pages from new size to old size */
	for (allocpagenum = npages; 
		allocpagenum < ems_handle[handle]->npages; 
		allocpagenum++) { 
	    syspagenum = ems_handle[handle]->pagenum[allocpagenum];

	    /* sanity */
            if (syspagenum > ems_total_pages)
                fatal("EMS free_pages_of_handle found invalid page number\n");
	    if (!(ems_page[syspagenum].status & EMS_ALLOCED))
	    	fatal("EMS free_pages_of_handle tried to free page already free\n");
	    ems_page[syspagenum].handle = 0;
	    ems_page[syspagenum].status = EMS_FREE;
	}

	/* Second step: Shrink the dynamic array of the handle */	
	dynsize = sizeof(EMS_handle) + sizeof(short) * npages;
	emp = ems_handle[handle];
	if ((emp = (EMS_handle *)realloc((void *)emp, dynsize)) == NULL)
	    fatal("Cannot realloc EMS handle, cannot continue\n");
	ems_handle[handle] = emp;
	ems_handle[handle]->npages = npages;
    }
    ems_alloc_pages += delta;
    ems_free_pages -= delta;
}

/* Free all pages belonging to a handle, handle must be valid */
static void
free_pages_of_handle(short handle)
{
    int allocpagenum;
    int syspagenum;
    int npages;

    /* sanity */

    if (handle > 255 || ems_handle[handle] == NULL)
	fatal("EMS free_pages_of_handle called with invalid handle\n");

    if ((npages = ems_handle[handle]->npages) == 0)
	return;

    for (allocpagenum = 0; allocpagenum < npages; allocpagenum++) {
	syspagenum = ems_handle[handle]->pagenum[allocpagenum];
	/* sanity */
	if (syspagenum > ems_total_pages)
	    fatal("EMS free_pages_of_handle found invalid page number\n");
	if (!(ems_page[syspagenum].status & EMS_ALLOCED))
	    fatal("EMS free_pages_of_handle tried to free page already free\n");
	ems_page[syspagenum].handle = 0;
	ems_page[syspagenum].status = EMS_FREE;
    }
    ems_alloc_pages -= npages;
    ems_free_pages += npages;
}

/* Restore a saved mapping context, overwrites current mapping context */
static void
restore_context(EMS_mapping_context *emc)
{
    int i;

    for (i = 0; i < 4; i++) {
	ems_mapping_context.handle[i] = emc->handle[i];
	if (emc->pos_mapped[i] != 0 &&
	    ems_mapping_context.pos_pagenum[i] != emc->pos_pagenum[i]) {
	    map_page(emc->pos_pagenum[i], (u_char) i, emc->handle[i], 0);
	} else {
	    ems_mapping_context.pos_mapped[i] = 0;
	}
    }
}

/* Prepare a special context save block for DOS and save it to
 * VM86 memory
 */
static void
save_context_to_dos(EMScontext *emp)
{
    int i, end;
    EMScontext context;
    u_short *sp;
    u_short sum;

    context.ems_saved_context = ems_mapping_context;
    context.magic = EMS_SAVEMAGIC;
    context.checksum = 0;
    sp = (u_short *)&context;
    end = sizeof(EMScontext) / sizeof(short);
    /* Generate checksum */
    for (i = 0, sum = 0; i < end; i++) {
	sum += *sp++;
	sum &= 0xffff;
    }
    context.checksum = 0x10000L - sum;
    /* Save it to VM86 memory */
    *emp = context;
}

/* Check a context returned from VM86 app for validity, return 0, if
 * not valid, else return 1
 */
static int
check_saved_context(EMScontext *emp)
{
    int i, end;
    u_short *sp;
    u_short sum;

    if (emp->magic != EMS_SAVEMAGIC)
	return 0;

    sp = (u_short *)emp;
    end = sizeof(EMScontext) / sizeof(short);
    /* Generate checksum */
    for (i = 0, sum = 0; i < end; i++) {
        sum += *sp++;
        sum &= 0xffff;
    }
    if (sum != 0)
	return 0;
    else
	return 1;
}

/* Helper routine for the move routines below: Check if length bytes
 * can be moved from/to handle pages (i.e are there enough pages)
 */
static int
check_alloc_pages(u_short handle, u_short firstpage, u_short offset, 
                  u_long length)
{
    u_long nbytes;

    if (firstpage > ems_handle[handle]->npages)
	return (0);
    nbytes = (ems_handle[handle]->npages - firstpage) * EMS_PAGESIZE - offset;
    return (ems_handle[handle]->npages >= nbytes);
}

/* Copy a block of memory up to the next 16kB boundary in the source
 * to the destination in upward direction (i.e. with ascending addresses)
 * XXX Could be an inline function.
 */
static void 
copy_block_up(struct copydesc *cdp)
{
    size_t size;
    void *srcp;
    void *dstp;

    /* If source or both memory types are EMS, source determines the
     * block lenght, else destination determines the block lenght
     */
    if (cdp->copytype & SRC_EMS)
	size = EMS_PAGESIZE - cdp->EMS_OFFS(src_addr);
    else
	size = EMS_PAGESIZE - cdp->EMS_OFFS(dst_addr);

    if (size > cdp->rest_len)
	size = cdp->rest_len;
 
    /* If src is EMS memory, it is mapped into position 0 */
    if (cdp->copytype & SRC_EMS)
	srcp = (void *)(ems_frame_addr + cdp->EMS_OFFS(src_addr));
    else
	srcp = (void *)(cdp->EMS_PTR(src_addr));

    /* If dest is EMS memory, it is mapped into position 1,2 */
    if (cdp->copytype & DST_EMS)
	dstp = (void *)(ems_frame_addr + EMS_PAGESIZE + 
					cdp->EMS_OFFS(dst_addr));
    else
	dstp = (void *)(cdp->EMS_PTR(dst_addr));

    /* Move this block */
    memmove(dstp, srcp, size);

    /* Update the copy descriptor: This updates the address of both 
     * conventional and EMS memory 
     */
    cdp->EMS_PTR(src_addr) += size;
    cdp->EMS_PTR(dst_addr) += size;

    cdp->rest_len -= size;
}


/* Move EMS memory starting with handle page src_seg and offset src_offset
 * to conventional memory dst_addr for length bytes
 * dst_addr is checked, handle is valid 
 */
static u_long 
move_ems_to_conv(short src_handle, u_short src_seg, 
			u_short src_offset, u_long dst_addr, u_long length)
{
    EMS_mapping_context ems_saved_context;
    EMS_handle *ehp;
    int pageindx = src_seg;
    struct copydesc cd;

    if (check_alloc_pages(src_handle, src_seg, src_offset, length) == 0)
	return EMS_MOVE_OVERFLOW;

    ehp = ems_handle[src_handle];

    /* Prepare the move: Save the mapping context */
    ems_saved_context = ems_mapping_context;

    /* Setup the copy descriptor struct */

    cd.copytype = SRC_EMS;
    cd.EMS_PAGE(src_addr) = ehp->pagenum[pageindx];
    cd.EMS_OFFS(src_addr) = src_offset;
    cd.EMS_PTR(dst_addr) = dst_addr;
    cd.rest_len = length;

    do {
	/* Map for the first block copy, source is mapped to position zero */
	map_page(cd.EMS_PAGE(src_addr), 0, src_handle, 0);
        copy_block_up(&cd);
    } while(cd.rest_len > 0);   

    /* Restore the original mapping */
    restore_context(&ems_saved_context);
    return EMS_SUCCESS;
}

/* Move conventional memory starting with src_addr
 * to EMS memory starting with handle page src_seg and offset src_offset
 * for length bytes
 * dst_addr is checked, handle is valid 
 */
static u_long
move_conv_to_ems(u_long src_addr, u_short dst_handle, u_short dst_seg,
                 u_short dst_offset, u_long length)
{
    EMS_mapping_context ems_saved_context;
    EMS_handle *ehp;
    int pageindx = dst_seg;
    struct copydesc cd;
    
    if (check_alloc_pages(dst_handle, dst_seg, dst_offset, length) == 0)
    	return EMS_MOVE_OVERFLOW;
    
    ehp = ems_handle[dst_handle];
    
    /* Prepare the move: Save the mapping context */
    ems_saved_context = ems_mapping_context;

    /* Setup the copy descriptor struct */

    cd.copytype = DST_EMS;
    cd.EMS_PAGE(dst_addr) = ehp->pagenum[pageindx];
    cd.EMS_OFFS(dst_addr) = dst_offset;
    cd.EMS_PTR(src_addr) = src_addr;
    cd.rest_len = length;

    do {
	map_page(cd.EMS_PAGE(dst_addr), 1, dst_handle, 0);
        copy_block_up(&cd);
    } while(cd.rest_len > 0);   

    /* Restore the original mapping */
    restore_context(&ems_saved_context);
    return EMS_SUCCESS;
}
    
static u_long
move_ems_to_ems(u_short src_handle, u_short src_seg, u_short src_offset,
                u_short dst_handle, u_short dst_seg, u_short dst_offset,
                u_long length)
{
    EMS_mapping_context ems_saved_context;
    EMS_handle *src_hp, *dst_hp;
    struct copydesc cd;
    
    if (check_alloc_pages(src_handle, src_seg, src_offset, length) == 0)
    	return EMS_MOVE_OVERFLOW;
    if (check_alloc_pages(dst_handle, dst_seg, dst_offset, length) == 0)
    	return EMS_MOVE_OVERFLOW;
    
    src_hp = ems_handle[src_handle];
    dst_hp = ems_handle[dst_handle];

    /* Prepare the move: Save the mapping context */
    ems_saved_context = ems_mapping_context;

    /* Setup the copy descriptor struct */

    cd.copytype = SRC_EMS | DST_EMS;
    cd.EMS_PAGE(src_addr) = src_hp->pagenum[src_seg];
    cd.EMS_OFFS(src_addr) = src_offset;
    cd.EMS_PAGE(dst_addr) = dst_hp->pagenum[dst_seg];
    cd.EMS_OFFS(dst_addr) = dst_offset;
    cd.rest_len = length;
    
    /* Copy */
    do {
        map_page(cd.EMS_PAGE(src_addr), 0, src_handle, 0);
	map_page(cd.EMS_PAGE(dst_addr), 1, dst_handle, 0);
        /* If there are more pages, map the next destination page to
         * position 2. This removes a compare between source and dest
         * offsets.
         */
        if (cd.EMS_PAGE(dst_addr) < dst_hp->npages)
	    map_page((cd.EMS_PAGE(dst_addr) + 1), 2, dst_handle, 0);        
        copy_block_up(&cd);
    } while(cd.rest_len > 0);   

    /* Restore the original mapping */
    restore_context(&ems_saved_context);
    return EMS_SUCCESS;
}