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