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