Rename old DOS3Call as INT_Int21Handler and make new DOS3Call call
[wine] / msdos / dosmem.c
1 /*
2  * DOS memory emulation
3  *
4  * Copyright 1995 Alexandre Julliard
5  * Copyright 1996 Marcus Meissner
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <signal.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_MMAN_H
30 # include <sys/mman.h>
31 #endif
32
33 #include <time.h>
34 #ifdef HAVE_SYS_TIME_H
35 # include <sys/time.h>
36 #endif
37
38 #include "winbase.h"
39 #include "wine/winbase16.h"
40
41 #include "global.h"
42 #include "selectors.h"
43 #include "miscemu.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(dosmem);
47 WINE_DECLARE_DEBUG_CHANNEL(selector);
48
49 WORD DOSMEM_0000H;        /* segment at 0:0 */
50 WORD DOSMEM_BiosDataSeg;  /* BIOS data segment at 0x40:0 */
51 WORD DOSMEM_BiosSysSeg;   /* BIOS ROM segment at 0xf000:0 */
52
53 DWORD DOSMEM_CollateTable;
54
55 /* use 2 low bits of 'size' for the housekeeping */
56
57 #define DM_BLOCK_DEBUG          0xABE00000
58 #define DM_BLOCK_TERMINAL       0x00000001
59 #define DM_BLOCK_FREE           0x00000002
60 #define DM_BLOCK_MASK           0x001FFFFC
61
62 /*
63 #define __DOSMEM_DEBUG__
64  */
65
66 typedef struct {
67    unsigned     size;
68 } dosmem_entry;
69
70 typedef struct {
71   unsigned      blocks;
72   unsigned      free;
73 } dosmem_info;
74
75 #define NEXT_BLOCK(block) \
76         (dosmem_entry*)(((char*)(block)) + \
77          sizeof(dosmem_entry) + ((block)->size & DM_BLOCK_MASK))
78
79 #define VM_STUB(x) (0x90CF00CD|(x<<8)) /* INT x; IRET; NOP */
80 #define VM_STUB_SEGMENT 0xf000         /* BIOS segment */
81
82 /* DOS memory base */
83 static char *DOSMEM_dosmem;
84 /* DOS system base (for interrupt vector table and BIOS data area)
85  * ...should in theory (i.e. Windows) be equal to DOSMEM_dosmem (NULL),
86  * but is normally set to 0xf0000 in Wine to allow trapping of NULL pointers,
87  * and only relocated to NULL when absolutely necessary */
88 static char *DOSMEM_sysmem;
89
90 /* various real-mode code stubs */
91 struct DPMI_segments DOSMEM_dpmi_segments;
92
93 /***********************************************************************
94  *           DOSMEM_GetDPMISegments
95  */
96 const struct DPMI_segments *DOSMEM_GetDPMISegments(void)
97 {
98     return &DOSMEM_dpmi_segments;
99 }
100
101 /***********************************************************************
102  *           DOSMEM_MemoryTop
103  *
104  * Gets the DOS memory top.
105  */
106 static char *DOSMEM_MemoryTop(void)
107 {
108     return DOSMEM_dosmem+0x9FFFC; /* 640K */
109 }
110
111 /***********************************************************************
112  *           DOSMEM_InfoBlock
113  *
114  * Gets the DOS memory info block.
115  */
116 static dosmem_info *DOSMEM_InfoBlock(void)
117 {
118     return (dosmem_info*)(DOSMEM_dosmem+0x10000); /* 64K */
119 }
120
121 /***********************************************************************
122  *           DOSMEM_RootBlock
123  *
124  * Gets the DOS memory root block.
125  */
126 static dosmem_entry *DOSMEM_RootBlock(void)
127 {
128     /* first block has to be paragraph-aligned */
129     return (dosmem_entry*)(((char*)DOSMEM_InfoBlock()) +
130                            ((((sizeof(dosmem_info) + 0xf) & ~0xf) - sizeof(dosmem_entry))));
131 }
132
133 /***********************************************************************
134  *           DOSMEM_FillIsrTable
135  *
136  * Fill the interrupt table with fake BIOS calls to BIOSSEG (0xf000).
137  *
138  * NOTES:
139  * Linux normally only traps INTs performed from or destined to BIOSSEG
140  * for us to handle, if the int_revectored table is empty. Filling the
141  * interrupt table with calls to INT stubs in BIOSSEG allows DOS programs
142  * to hook interrupts, as well as use their familiar retf tricks to call
143  * them, AND let Wine handle any unhooked interrupts transparently.
144  */
145 static void DOSMEM_FillIsrTable(void)
146 {
147     SEGPTR *isr = (SEGPTR*)DOSMEM_sysmem;
148     int x;
149
150     for (x=0; x<256; x++) isr[x]=MAKESEGPTR(VM_STUB_SEGMENT,x*4);
151 }
152
153 static void DOSMEM_MakeIsrStubs(void)
154 {
155     DWORD *stub = (DWORD*)(DOSMEM_dosmem + (VM_STUB_SEGMENT << 4));
156     int x;
157
158     for (x=0; x<256; x++) stub[x]=VM_STUB(x);
159 }
160
161 /***********************************************************************
162  *           DOSMEM_InitDPMI
163  *
164  * Allocate the global DPMI RMCB wrapper.
165  */
166 static void DOSMEM_InitDPMI(void)
167 {
168     LPSTR ptr;
169     int   i;
170
171     static const char wrap_code[]={
172      0xCD,0x31, /* int $0x31 */
173      0xCB       /* lret */
174     };
175
176     static const char enter_xms[]=
177     {
178         /* XMS hookable entry point */
179         0xEB,0x03,           /* jmp entry */
180         0x90,0x90,0x90,      /* nop;nop;nop */
181                              /* entry: */
182         /* real entry point */
183         /* for simplicity, we'll just use the same hook as DPMI below */
184         0xCD,0x31,           /* int $0x31 */
185         0xCB                 /* lret */
186     };
187
188     static const char enter_pm[]=
189     {
190         0x50,                /* pushw %ax */
191         0x52,                /* pushw %dx */
192         0x55,                /* pushw %bp */
193         0x89,0xE5,           /* movw %sp,%bp */
194         /* get return CS */
195         0x8B,0x56,0x08,      /* movw 8(%bp),%dx */
196         /* just call int 31 here to get into protected mode... */
197         /* it'll check whether it was called from dpmi_seg... */
198         0xCD,0x31,           /* int $0x31 */
199         /* we are now in the context of a 16-bit relay call */
200         /* need to fixup our stack;
201          * 16-bit relay return address will be lost, but we won't worry quite yet */
202         0x8E,0xD0,           /* movw %ax,%ss */
203         0x66,0x0F,0xB7,0xE5, /* movzwl %bp,%esp */
204         /* set return CS */
205         0x89,0x56,0x08,      /* movw %dx,8(%bp) */
206         0x5D,                /* popw %bp */
207         0x5A,                /* popw %dx */
208         0x58,                /* popw %ax */
209         0xCB                 /* lret */
210     };
211
212     ptr = DOSMEM_GetBlock( sizeof(wrap_code), &DOSMEM_dpmi_segments.wrap_seg );
213     memcpy( ptr, wrap_code, sizeof(wrap_code) );
214     ptr = DOSMEM_GetBlock( sizeof(enter_xms), &DOSMEM_dpmi_segments.xms_seg );
215     memcpy( ptr, enter_xms, sizeof(enter_xms) );
216     ptr = DOSMEM_GetBlock( sizeof(enter_pm), &DOSMEM_dpmi_segments.dpmi_seg );
217     memcpy( ptr, enter_pm, sizeof(enter_pm) );
218     DOSMEM_dpmi_segments.dpmi_sel = SELECTOR_AllocBlock( ptr, sizeof(enter_pm), WINE_LDT_FLAGS_CODE );
219
220     ptr = DOSMEM_GetBlock( 6 * 256, &DOSMEM_dpmi_segments.int48_seg );
221     for(i=0; i<256; i++) {
222         /*
223          * Each 32-bit interrupt handler is 6 bytes:
224          * 0xCD,<i>            = int <i> (nested 16-bit interrupt)
225          * 0x66,0xCA,0x04,0x00 = ret 4   (32-bit far return and pop 4 bytes)
226          */
227         ptr[i * 6 + 0] = 0xCD;
228         ptr[i * 6 + 1] = i;
229         ptr[i * 6 + 2] = 0x66;
230         ptr[i * 6 + 3] = 0xCA;
231         ptr[i * 6 + 4] = 0x04;
232         ptr[i * 6 + 5] = 0x00;
233     }
234     DOSMEM_dpmi_segments.int48_sel = SELECTOR_AllocBlock( ptr, 6 * 256, WINE_LDT_FLAGS_CODE );
235 }
236
237 static BIOSDATA * DOSMEM_BiosData(void)
238 {
239     return (BIOSDATA *)(DOSMEM_sysmem + 0x400);
240 }
241
242 /**********************************************************************
243  *          DOSMEM_GetTicksSinceMidnight
244  *
245  * Return number of clock ticks since midnight.
246  */
247 static DWORD DOSMEM_GetTicksSinceMidnight(void)
248 {
249     struct tm *bdtime;
250     struct timeval tvs;
251     time_t seconds;
252
253     /* This should give us the (approximately) correct
254      * 18.206 clock ticks per second since midnight.
255      */
256     gettimeofday( &tvs, NULL );
257     seconds = tvs.tv_sec;
258     bdtime = localtime( &seconds );
259     return (((bdtime->tm_hour * 3600 + bdtime->tm_min * 60 +
260               bdtime->tm_sec) * 18206) / 1000) +
261                   (tvs.tv_usec / 54927);
262 }
263
264 /***********************************************************************
265  *           DOSMEM_FillBiosSegments
266  *
267  * Fill the BIOS data segment with dummy values.
268  */
269 static void DOSMEM_FillBiosSegments(void)
270 {
271     BYTE *pBiosSys = DOSMEM_dosmem + 0xf0000;
272     BYTE *pBiosROMTable = pBiosSys+0xe6f5;
273     BIOS_EXTRA *extra = (BIOS_EXTRA *)(DOSMEM_dosmem + (int)BIOS_EXTRA_PTR);
274     BIOSDATA *pBiosData = DOSMEM_BiosData();
275
276     /* Supported VESA mode, see int10.c */
277     WORD ConstVesaModeList[]={0x00,0x01,0x02,0x03,0x07,0x0D,0x0E,0x10,0x12,0x13,
278                               0x100,0x101,0x102,0x103,0x104,0x105,0x106,0x107,0x10D,0x10E,
279                               0x10F,0x110,0x111,0x112,0x113,0x114,0x115,0x116,0x117,0x118,
280                               0x119,0x11A,0x11B,0xFFFF};
281     char * ConstVesaString = "WINE SVGA BOARD";
282     int i;
283
284     VIDEOFUNCTIONALITY *pVidFunc = &extra->vid_func;
285     VIDEOSTATE *pVidState = &extra->vid_state;
286     VESAINFO *pVesaInfo = &extra->vesa_info;
287     char * VesaString = extra->vesa_string;
288     WORD * VesaModeList = extra->vesa_modes;
289
290       /* Clear all unused values */
291     memset( pBiosData, 0, sizeof(*pBiosData) );
292     memset( pVidFunc,  0, sizeof(*pVidFunc ) );
293     memset( pVidState, 0, sizeof(*pVidState) );
294     memset( pVesaInfo, 0, sizeof(*pVesaInfo) );
295
296     /* FIXME: should check the number of configured drives and ports */
297     pBiosData->Com1Addr             = 0x3f8;
298     pBiosData->Com2Addr             = 0x2f8;
299     pBiosData->Lpt1Addr             = 0x378;
300     pBiosData->Lpt2Addr             = 0x278;
301     pBiosData->InstalledHardware    = 0x5463;
302     pBiosData->MemSize              = 640;
303     pBiosData->NextKbdCharPtr       = 0x1e;
304     pBiosData->FirstKbdCharPtr      = 0x1e;
305     pBiosData->VideoMode            = 3;
306     pBiosData->VideoColumns         = 80;
307     pBiosData->VideoPageSize        = 80 * 25 * 2;
308     pBiosData->VideoPageStartAddr   = 0xb800;
309     pBiosData->VideoCtrlAddr        = 0x3d4;
310     pBiosData->Ticks                = DOSMEM_GetTicksSinceMidnight();
311     pBiosData->NbHardDisks          = 2;
312     pBiosData->KbdBufferStart       = 0x1e;
313     pBiosData->KbdBufferEnd         = 0x3e;
314     pBiosData->RowsOnScreenMinus1   = 24;
315     pBiosData->BytesPerChar         = 0x10;
316     pBiosData->ModeOptions          = 0x64;
317     pBiosData->FeatureBitsSwitches  = 0xf9;
318     pBiosData->VGASettings          = 0x51;
319     pBiosData->DisplayCombination   = 0x08;
320     pBiosData->DiskDataRate         = 0;
321
322     /* fill ROM configuration table (values from Award) */
323     *(pBiosROMTable+0x0)        = 0x08; /* number of bytes following LO */
324     *(pBiosROMTable+0x1)        = 0x00; /* number of bytes following HI */
325     *(pBiosROMTable+0x2)        = 0xfc; /* model */
326     *(pBiosROMTable+0x3)        = 0x01; /* submodel */
327     *(pBiosROMTable+0x4)        = 0x00; /* BIOS revision */
328     *(pBiosROMTable+0x5)        = 0x74; /* feature byte 1 */
329     *(pBiosROMTable+0x6)        = 0x00; /* feature byte 2 */
330     *(pBiosROMTable+0x7)        = 0x00; /* feature byte 3 */
331     *(pBiosROMTable+0x8)        = 0x00; /* feature byte 4 */
332     *(pBiosROMTable+0x9)        = 0x00; /* feature byte 5 */
333
334
335     for (i = 0; i < 7; i++)
336         pVidFunc->ModeSupport[i] = 0xff;
337
338     pVidFunc->ScanlineSupport     = 7;
339     pVidFunc->NumberCharBlocks    = 0;
340     pVidFunc->ActiveCharBlocks    = 0;
341     pVidFunc->MiscFlags           = 0x8ff;
342     pVidFunc->SavePointerFlags    = 0x3f;
343
344                                     /* FIXME: always real mode ? */
345     pVidState->StaticFuncTable    = BIOS_EXTRA_SEGPTR + offsetof(BIOS_EXTRA,vid_func);
346     pVidState->VideoMode          = pBiosData->VideoMode; /* needs updates! */
347     pVidState->NumberColumns      = pBiosData->VideoColumns; /* needs updates! */
348     pVidState->RegenBufLen        = 0;
349     pVidState->RegenBufAddr       = 0;
350
351     for (i = 0; i < 8; i++)
352         pVidState->CursorPos[i] = 0;
353
354     pVidState->CursorType         = 0x0a0b;  /* start/end line */
355     pVidState->ActivePage         = 0;
356     pVidState->CRTCPort           = 0x3da;
357     pVidState->Port3x8            = 0;
358     pVidState->Port3x9            = 0;
359     pVidState->NumberRows         = 23;     /* number of rows - 1 */
360     pVidState->BytesPerChar       = 0x10;
361     pVidState->DCCActive          = pBiosData->DisplayCombination;
362     pVidState->DCCAlternate       = 0;
363     pVidState->NumberColors       = 16;
364     pVidState->NumberPages        = 1;
365     pVidState->NumberScanlines    = 3; /* (0,1,2,3) = (200,350,400,480) */
366     pVidState->CharBlockPrimary   = 0;
367     pVidState->CharBlockSecondary = 0;
368     pVidState->MiscFlags =
369                            (pBiosData->VGASettings & 0x0f)
370                          | ((pBiosData->ModeOptions & 1) << 4); /* cursor emulation */
371     pVidState->NonVGASupport      = 0;
372     pVidState->VideoMem           = (pBiosData->ModeOptions & 0x60 >> 5);
373     pVidState->SavePointerState   = 0;
374     pVidState->DisplayStatus      = 4;
375
376     /* SVGA structures */
377     pVesaInfo->Signature          = *(DWORD*)"VESA";
378     pVesaInfo->Major              = 2;
379     pVesaInfo->Minor              = 0;
380                                     /* FIXME: always real mode ? */
381     pVesaInfo->StaticVendorString = BIOS_EXTRA_SEGPTR + offsetof(BIOS_EXTRA,vesa_string);
382     pVesaInfo->CapabilitiesFlags  = 0xfffffffd; /* FIXME: not really supported */
383                                     /* FIXME: always real mode ? */
384     pVesaInfo->StaticModeList     = BIOS_EXTRA_SEGPTR + offsetof(BIOS_EXTRA,vesa_modes);
385
386     strcpy(VesaString,ConstVesaString);
387     memcpy(VesaModeList,ConstVesaModeList,sizeof(ConstVesaModeList));
388
389     /* BIOS date string */
390     strcpy((char *)pBiosSys+0xfff5, "13/01/99");
391
392     /* BIOS ID */
393     *(pBiosSys+0xfffe) = 0xfc;
394 }
395
396 /***********************************************************************
397  *           DOSMEM_InitCollateTable
398  *
399  * Initialises the collate table (character sorting, language dependent)
400  */
401 static void DOSMEM_InitCollateTable()
402 {
403         DWORD           x;
404         unsigned char   *tbl;
405         int             i;
406
407         x = GlobalDOSAlloc16(258);
408         DOSMEM_CollateTable = MAKELONG(0,(x>>16));
409         tbl = DOSMEM_MapRealToLinear(DOSMEM_CollateTable);
410         *(WORD*)tbl     = 0x100;
411         tbl += 2;
412         for ( i = 0; i < 0x100; i++) *tbl++ = i;
413 }
414
415 /***********************************************************************
416  *           DOSMEM_InitErrorTable
417  *
418  * Initialises the error tables (DOS 5+)
419  */
420 static void DOSMEM_InitErrorTable()
421 {
422 #if 0  /* no longer used */
423         DWORD           x;
424         char            *call;
425
426         /* We will use a snippet of real mode code that calls */
427         /* a WINE-only interrupt to handle moving the requested */
428         /* message into the buffer... */
429
430         /* FIXME - There is still something wrong... */
431
432         /* FIXME - Find hex values for opcodes...
433
434            (On call, AX contains message number
435                      DI contains 'offset' (??)
436             Resturn, ES:DI points to counted string )
437
438            PUSH BX
439            MOV BX, AX
440            MOV AX, (arbitrary subfunction number)
441            INT (WINE-only interrupt)
442            POP BX
443            RET
444
445         */
446
447         const int       code = 4;
448         const int       buffer = 80;
449         const int       SIZE_TO_ALLOCATE = code + buffer;
450
451         /* FIXME - Complete rewrite of the table system to save */
452         /* precious DOS space. Now, we return the 0001:???? as */
453         /* DOS 4+ (??, it seems to be the case in MS 7.10) treats that */
454         /* as a special case and programs will use the alternate */
455         /* interface (a farcall returned with INT 24 (AX = 0x122e, DL = */
456         /* 0x08) which lets us have a smaller memory footprint anyway. */
457
458         x = GlobalDOSAlloc16(SIZE_TO_ALLOCATE);
459
460         DOSMEM_ErrorCall = MAKELONG(0,(x>>16));
461         DOSMEM_ErrorBuffer = DOSMEM_ErrorCall + code;
462
463         call = DOSMEM_MapRealToLinear(DOSMEM_ErrorCall);
464
465         memset(call, 0, SIZE_TO_ALLOCATE);
466 #endif
467         /* FIXME - Copy assembly into buffer here */
468 }
469
470 /***********************************************************************
471  *           DOSMEM_InitMemory
472  *
473  * Initialises the DOS memory structures.
474  */
475 static void DOSMEM_InitMemory(void)
476 {
477    /* Low 64Kb are reserved for DOS/BIOS so the useable area starts at
478     * 1000:0000 and ends at 9FFF:FFEF. */
479
480     dosmem_info*        info_block = DOSMEM_InfoBlock();
481     dosmem_entry*       root_block = DOSMEM_RootBlock();
482     dosmem_entry*       dm;
483
484     root_block->size = DOSMEM_MemoryTop() - (((char*)root_block) + sizeof(dosmem_entry));
485
486     info_block->blocks = 0;
487     info_block->free = root_block->size;
488
489     dm = NEXT_BLOCK(root_block);
490     dm->size = DM_BLOCK_TERMINAL;
491     root_block->size |= DM_BLOCK_FREE
492 #ifdef __DOSMEM_DEBUG__
493                      | DM_BLOCK_DEBUG
494 #endif
495                      ;
496 }
497
498 /**********************************************************************
499  *              setup_dos_mem
500  *
501  * Setup the first megabyte for DOS memory access
502  */
503 static void setup_dos_mem( int dos_init )
504 {
505     int sys_offset = 0;
506     int page_size = getpagesize();
507     void *addr = wine_anon_mmap( (void *)page_size, 0x110000-page_size,
508                                  PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
509     if (addr == (void *)page_size)  /* we got what we wanted */
510     {
511         /* now map from address 0 */
512         addr = wine_anon_mmap( NULL, 0x110000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED );
513         if (addr)
514         {
515             ERR("MAP_FIXED failed at address 0 for DOS address space\n" );
516             ExitProcess(1);
517         }
518
519         /* inform the memory manager that there is a mapping here */
520         VirtualAlloc( addr, 0x110000, MEM_RESERVE | MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
521
522         /* protect the first 64K to catch NULL pointers */
523         if (!dos_init)
524         {
525             VirtualProtect( addr, 0x10000, PAGE_NOACCESS, NULL );
526             /* move the BIOS and ISR area from 0x00000 to 0xf0000 */
527             sys_offset += 0xf0000;
528         }
529     }
530     else
531     {
532         ERR("Cannot use first megabyte for DOS address space, please report\n" );
533         if (dos_init) ExitProcess(1);
534         /* allocate the DOS area somewhere else */
535         addr = VirtualAlloc( NULL, 0x110000, MEM_COMMIT, PAGE_EXECUTE_READWRITE );
536         if (!addr)
537         {
538             ERR( "Cannot allocate DOS memory\n" );
539             ExitProcess(1);
540         }
541     }
542     DOSMEM_dosmem = addr;
543     DOSMEM_sysmem = (char*)addr + sys_offset;
544 }
545
546
547 /***********************************************************************
548  *           DOSMEM_Init
549  *
550  * Create the dos memory segments, and store them into the KERNEL
551  * exported values.
552  */
553 BOOL DOSMEM_Init(BOOL dos_init)
554 {
555     static int already_done, already_mapped;
556
557     if (!already_done)
558     {
559         setup_dos_mem( dos_init );
560
561         DOSMEM_0000H = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem,
562                                            0x10000, 0, WINE_LDT_FLAGS_DATA );
563         DOSMEM_BiosDataSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_sysmem + 0x400,
564                                                 0x100, 0, WINE_LDT_FLAGS_DATA );
565         DOSMEM_BiosSysSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_dosmem+0xf0000,
566                                                0x10000, 0, WINE_LDT_FLAGS_DATA );
567         DOSMEM_FillBiosSegments();
568         DOSMEM_FillIsrTable();
569         DOSMEM_InitMemory();
570         DOSMEM_InitCollateTable();
571         DOSMEM_InitErrorTable();
572         DOSMEM_InitDPMI();
573         already_done = 1;
574     }
575     else if (dos_init && !already_mapped)
576     {
577         if (DOSMEM_dosmem)
578         {
579             ERR( "Needs access to the first megabyte for DOS mode\n" );
580             ExitProcess(1);
581         }
582         MESSAGE( "Warning: unprotecting the first 64KB of memory to allow real-mode calls.\n"
583                  "         NULL pointer accesses will no longer be caught.\n" );
584         VirtualProtect( NULL, 0x10000, PAGE_EXECUTE_READWRITE, NULL );
585         /* copy the BIOS and ISR area down */
586         memcpy( DOSMEM_dosmem, DOSMEM_sysmem, 0x400 + 0x100 );
587         DOSMEM_sysmem = DOSMEM_dosmem;
588         SetSelectorBase( DOSMEM_0000H, 0 );
589         SetSelectorBase( DOSMEM_BiosDataSeg, 0x400 );
590         /* we may now need the actual interrupt stubs, and since we've just moved the
591          * interrupt vector table away, we can fill the area with stubs instead... */
592         DOSMEM_MakeIsrStubs();
593         already_mapped = 1;
594     }
595     return TRUE;
596 }
597
598
599 /***********************************************************************
600  *           DOSMEM_Tick
601  *
602  * Increment the BIOS tick counter. Called by timer signal handler.
603  */
604 void DOSMEM_Tick( WORD timer )
605 {
606     BIOSDATA *pBiosData = DOSMEM_BiosData();
607     if (pBiosData) pBiosData->Ticks++;
608 }
609
610 /***********************************************************************
611  *           DOSMEM_GetBlock
612  *
613  * Carve a chunk of the DOS memory block (without selector).
614  */
615 LPVOID DOSMEM_GetBlock(UINT size, UINT16* pseg)
616 {
617    UINT          blocksize;
618    char         *block = NULL;
619    dosmem_info  *info_block = DOSMEM_InfoBlock();
620    dosmem_entry *dm;
621 #ifdef __DOSMEM_DEBUG_
622    dosmem_entry *prev = NULL;
623 #endif
624
625    if( size > info_block->free ) return NULL;
626    dm = DOSMEM_RootBlock();
627
628    while (dm && dm->size != DM_BLOCK_TERMINAL)
629    {
630 #ifdef __DOSMEM_DEBUG__
631        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
632        {
633             WARN("MCB overrun! [prev = 0x%08x]\n", 4 + (UINT)prev);
634             return NULL;
635        }
636        prev = dm;
637 #endif
638        if( dm->size & DM_BLOCK_FREE )
639        {
640            dosmem_entry  *next = NEXT_BLOCK(dm);
641
642            while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
643            {
644                dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
645                next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
646                next = NEXT_BLOCK(dm);
647            }
648
649            blocksize = dm->size & DM_BLOCK_MASK;
650            if( blocksize >= size )
651            {
652                block = ((char*)dm) + sizeof(dosmem_entry);
653                if( blocksize - size > 0x20 )
654                {
655                    /* split dm so that the next one stays
656                     * paragraph-aligned (and dm loses free bit) */
657
658                    dm->size = (((size + 0xf + sizeof(dosmem_entry)) & ~0xf) -
659                                               sizeof(dosmem_entry));
660                    next = (dosmem_entry*)(((char*)dm) +
661                            sizeof(dosmem_entry) + dm->size);
662                    next->size = (blocksize - (dm->size +
663                            sizeof(dosmem_entry))) | DM_BLOCK_FREE
664 #ifdef __DOSMEM_DEBUG__
665                                                   | DM_BLOCK_DEBUG
666 #endif
667                                                   ;
668                } else dm->size &= DM_BLOCK_MASK;
669
670                info_block->blocks++;
671                info_block->free -= dm->size;
672                if( pseg ) *pseg = (block - DOSMEM_dosmem) >> 4;
673 #ifdef __DOSMEM_DEBUG__
674                dm->size |= DM_BLOCK_DEBUG;
675 #endif
676                break;
677            }
678            dm = next;
679        }
680        else dm = NEXT_BLOCK(dm);
681    }
682    return (LPVOID)block;
683 }
684
685 /***********************************************************************
686  *           DOSMEM_FreeBlock
687  */
688 BOOL DOSMEM_FreeBlock(void* ptr)
689 {
690    dosmem_info  *info_block = DOSMEM_InfoBlock();
691
692    if( ptr >= (void*)(((char*)DOSMEM_RootBlock()) + sizeof(dosmem_entry)) &&
693        ptr < (void*)DOSMEM_MemoryTop() && !((((char*)ptr)
694                   - DOSMEM_dosmem) & 0xf) )
695    {
696        dosmem_entry  *dm = (dosmem_entry*)(((char*)ptr) - sizeof(dosmem_entry));
697
698        if( !(dm->size & (DM_BLOCK_FREE | DM_BLOCK_TERMINAL))
699 #ifdef __DOSMEM_DEBUG__
700          && ((dm->size & DM_BLOCK_DEBUG) == DM_BLOCK_DEBUG )
701 #endif
702          )
703        {
704              info_block->blocks--;
705              info_block->free += dm->size;
706
707              dm->size |= DM_BLOCK_FREE;
708              return TRUE;
709        }
710    }
711    return FALSE;
712 }
713
714 /***********************************************************************
715  *           DOSMEM_ResizeBlock
716  */
717 LPVOID DOSMEM_ResizeBlock(void* ptr, UINT size, UINT16* pseg)
718 {
719    char         *block = NULL;
720    dosmem_info  *info_block = DOSMEM_InfoBlock();
721
722    if( ptr >= (void*)(((char*)DOSMEM_RootBlock()) + sizeof(dosmem_entry)) &&
723        ptr < (void*)DOSMEM_MemoryTop() && !((((char*)ptr)
724                   - DOSMEM_dosmem) & 0xf) )
725    {
726        dosmem_entry  *dm = (dosmem_entry*)(((char*)ptr) - sizeof(dosmem_entry));
727
728        if( pseg ) *pseg = ((char*)ptr - DOSMEM_dosmem) >> 4;
729
730        if( !(dm->size & (DM_BLOCK_FREE | DM_BLOCK_TERMINAL))
731          )
732        {
733              dosmem_entry  *next = NEXT_BLOCK(dm);
734              UINT blocksize, orgsize = dm->size & DM_BLOCK_MASK;
735
736              while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
737              {
738                  dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
739                  next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
740                  next = NEXT_BLOCK(dm);
741              }
742
743              blocksize = dm->size & DM_BLOCK_MASK;
744              if (blocksize >= size)
745              {
746                  block = ((char*)dm) + sizeof(dosmem_entry);
747                  if( blocksize - size > 0x20 )
748                  {
749                      /* split dm so that the next one stays
750                       * paragraph-aligned (and next gains free bit) */
751
752                      dm->size = (((size + 0xf + sizeof(dosmem_entry)) & ~0xf) -
753                                                 sizeof(dosmem_entry));
754                      next = (dosmem_entry*)(((char*)dm) +
755                              sizeof(dosmem_entry) + dm->size);
756                      next->size = (blocksize - (dm->size +
757                              sizeof(dosmem_entry))) | DM_BLOCK_FREE
758                                                     ;
759                  } else dm->size &= DM_BLOCK_MASK;
760
761                  info_block->free += orgsize - dm->size;
762              } else {
763                  /* the collapse didn't help, try getting a new block */
764                  block = DOSMEM_GetBlock(size, pseg);
765                  if (block) {
766                      /* we got one, copy the old data there (we do need to, right?) */
767                      memcpy(block, ((char*)dm) + sizeof(dosmem_entry),
768                                    (size<orgsize) ? size : orgsize);
769                      /* free old block */
770                      info_block->blocks--;
771                      info_block->free += dm->size;
772
773                      dm->size |= DM_BLOCK_FREE;
774                  } else {
775                      /* and Bill Gates said 640K should be enough for everyone... */
776
777                      /* need to split original and collapsed blocks apart again,
778                       * and free the collapsed blocks again, before exiting */
779                      if( blocksize - orgsize > 0x20 )
780                      {
781                          /* split dm so that the next one stays
782                           * paragraph-aligned (and next gains free bit) */
783
784                          dm->size = (((orgsize + 0xf + sizeof(dosmem_entry)) & ~0xf) -
785                                                        sizeof(dosmem_entry));
786                          next = (dosmem_entry*)(((char*)dm) +
787                                  sizeof(dosmem_entry) + dm->size);
788                          next->size = (blocksize - (dm->size +
789                                  sizeof(dosmem_entry))) | DM_BLOCK_FREE
790                                                         ;
791                      } else dm->size &= DM_BLOCK_MASK;
792                  }
793              }
794        }
795    }
796    return (LPVOID)block;
797 }
798
799
800 /***********************************************************************
801  *           DOSMEM_Available
802  */
803 UINT DOSMEM_Available(void)
804 {
805    UINT          blocksize, available = 0;
806    dosmem_entry *dm;
807
808    dm = DOSMEM_RootBlock();
809
810    while (dm && dm->size != DM_BLOCK_TERMINAL)
811    {
812 #ifdef __DOSMEM_DEBUG__
813        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
814        {
815             WARN("MCB overrun! [prev = 0x%08x]\n", 4 + (UINT)prev);
816             return NULL;
817        }
818        prev = dm;
819 #endif
820        if( dm->size & DM_BLOCK_FREE )
821        {
822            dosmem_entry  *next = NEXT_BLOCK(dm);
823
824            while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
825            {
826                dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
827                next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
828                next = NEXT_BLOCK(dm);
829            }
830
831            blocksize = dm->size & DM_BLOCK_MASK;
832            if ( blocksize > available ) available = blocksize;
833            dm = next;
834        }
835        else dm = NEXT_BLOCK(dm);
836    }
837    return available;
838 }
839
840
841 /***********************************************************************
842  *           DOSMEM_MapLinearToDos
843  *
844  * Linear address to the DOS address space.
845  */
846 UINT DOSMEM_MapLinearToDos(LPVOID ptr)
847 {
848     if (((char*)ptr >= DOSMEM_dosmem) &&
849         ((char*)ptr < DOSMEM_dosmem + 0x100000))
850           return (UINT)ptr - (UINT)DOSMEM_dosmem;
851     return (UINT)ptr;
852 }
853
854
855 /***********************************************************************
856  *           DOSMEM_MapDosToLinear
857  *
858  * DOS linear address to the linear address space.
859  */
860 LPVOID DOSMEM_MapDosToLinear(UINT ptr)
861 {
862     if (ptr < 0x100000) return (LPVOID)(ptr + (UINT)DOSMEM_dosmem);
863     return (LPVOID)ptr;
864 }
865
866
867 /***********************************************************************
868  *           DOSMEM_MapRealToLinear
869  *
870  * Real mode DOS address into a linear pointer
871  */
872 LPVOID DOSMEM_MapRealToLinear(DWORD x)
873 {
874    LPVOID       lin;
875
876    lin=DOSMEM_dosmem+(x&0xffff)+(((x&0xffff0000)>>16)*16);
877    TRACE_(selector)("(0x%08lx) returns %p.\n", x, lin );
878    return lin;
879 }
880
881 /***********************************************************************
882  *           DOSMEM_AllocSelector
883  *
884  * Allocates a protected mode selector for a realmode segment.
885  */
886 WORD DOSMEM_AllocSelector(WORD realsel)
887 {
888         HMODULE16 hModule = GetModuleHandle16("KERNEL");
889         WORD    sel;
890
891         sel=GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_dosmem+realsel*16, 0x10000,
892                                 hModule, WINE_LDT_FLAGS_DATA );
893         TRACE_(selector)("(0x%04x) returns 0x%04x.\n", realsel,sel);
894         return sel;
895 }