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