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