Various ANSI C compability fixes.
[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 DECLARE_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     BYTE *pVideoStaticFuncTable = pBiosSys+0xe000;
178     BYTE *pVideoStateInfo = pBiosSys+0xe010;
179     BYTE *p;
180     int i;
181
182       /* Clear all unused values */
183     memset( pBiosData, 0, sizeof(*pBiosData) );
184
185     /* FIXME: should check the number of configured drives and ports */
186
187     pBiosData->Com1Addr             = 0x3f8;
188     pBiosData->Com2Addr             = 0x2f8;
189     pBiosData->Lpt1Addr             = 0x378;
190     pBiosData->Lpt2Addr             = 0x278;
191     pBiosData->InstalledHardware    = 0x5463;
192     pBiosData->MemSize              = 640;
193     pBiosData->NextKbdCharPtr       = 0x1e;
194     pBiosData->FirstKbdCharPtr      = 0x1e;
195     pBiosData->VideoMode            = 3;
196     pBiosData->VideoColumns         = 80;
197     pBiosData->VideoPageSize        = 80 * 25 * 2;
198     pBiosData->VideoPageStartAddr   = 0xb800;
199     pBiosData->VideoCtrlAddr        = 0x3d4;
200     pBiosData->Ticks                = INT1A_GetTicksSinceMidnight();
201     pBiosData->NbHardDisks          = 2;
202     pBiosData->KbdBufferStart       = 0x1e;
203     pBiosData->KbdBufferEnd         = 0x3e;
204     pBiosData->RowsOnScreenMinus1   = 23;
205     pBiosData->BytesPerChar         = 0x10;
206     pBiosData->ModeOptions          = 0x64;
207     pBiosData->FeatureBitsSwitches  = 0xf9;
208     pBiosData->VGASettings          = 0x51;
209     pBiosData->DisplayCombination   = 0x08;
210     pBiosData->DiskDataRate         = 0;
211
212     /* fill ROM configuration table (values from Award) */
213     *(WORD *)(pBiosROMTable)= 0x08; /* number of bytes following */
214     *(pBiosROMTable+0x2)        = 0xfc; /* model */
215     *(pBiosROMTable+0x3)        = 0x01; /* submodel */
216     *(pBiosROMTable+0x4)        = 0x00; /* BIOS revision */
217     *(pBiosROMTable+0x5)        = 0x74; /* feature byte 1 */
218     *(pBiosROMTable+0x6)        = 0x00; /* feature byte 2 */
219     *(pBiosROMTable+0x7)        = 0x00; /* feature byte 3 */
220     *(pBiosROMTable+0x8)        = 0x00; /* feature byte 4 */
221     *(pBiosROMTable+0x9)        = 0x00; /* feature byte 5 */
222
223     p = pVideoStaticFuncTable;
224     for (i=0; i < 7; i++)
225       *(p+i)  = 0xff; /* modes supported 1 to 7 */
226     
227     *(p+0x7)  = 7;                  /* scan lines supported */
228     *(p+0x8)  = 0;                  /* tot nr of char blocks in text mode */
229     *(p+0x9)  = 0;                  /* max nr of active char blocks in text */
230     *(WORD *)(p+0xa) = 0x8ff;       /* misc support flags */
231     *(WORD *)(p+0xc) = 0;           /* reserved */
232     *(p+0xe)  = 0x3f;               /* save pointer function flags */  
233     *(p+0xf)  = 0;                  /* reserved */
234
235     p = pVideoStateInfo;
236     *(DWORD *)p = 0xf000e000;       /* address of pVideoStaticFuncTable, FIXME: always real mode ? */
237     *(p+0x04) =                     /* current video mode, needs updates ! */
238       pBiosData->VideoMode;
239     *(WORD *)(p+0x05) =             /* number of columns, needs updates ! */
240       pBiosData->VideoColumns;
241     *(WORD *)(p+0x07) = 0;          /* length of regen (???) buffer in bytes */
242     *(WORD *)(p+0x09) = 0;          /* starting address of regen (?) buffer */
243     *(WORD *)(p+0x0b) = 0;          /* cursorpos page 0 */
244     *(WORD *)(p+0x0d) = 0;          /* cursorpos page 1 */
245     *(WORD *)(p+0x0f) = 0;          /* page 2 */
246     *(WORD *)(p+0x11) = 0;          /* page 3 */
247     *(WORD *)(p+0x13) = 0;          /* page 4 */
248     *(WORD *)(p+0x15) = 0;          /* page 5 */
249     *(WORD *)(p+0x17) = 0;          /* page 6 */
250     *(WORD *)(p+0x19) = 0;          /* page 7 */
251     *(WORD *)(p+0x1b) = 0x0a0b;     /* cursor size (start/end line) */
252     *(p+0x1d) = 0;                  /* active display page */
253     *(WORD *)(p+0x1e) = 0x3da;      /* CRTC port address */
254     *(p+0x20) = 0x0;                /* current setting of port 0x3x8 */
255     *(p+0x21) = 0x0;                /* current setting of port 0x3x9 */
256     *(p+0x22) = 23;                 /* number of rows - 1 */
257     *(WORD *)(p+0x23) = 0x10;       /* bytes/character */
258     *(p+0x25) =                     /* comb. of active display */
259       pBiosData->DisplayCombination;
260     *(p+0x26) = 0;                  /* DCC (???) of alternate display */
261     *(WORD *)(p+0x27) = 16;         /* number of colors in current mode */
262     *(p+0x29) = 1;                  /* number of pages in current mode */
263     *(p+0x2a) = 3;                  /* number of scan lines active */
264                                     /* (0,1,2,3) =  (200,350,400,480) */
265     *(p+0x2b) = 0;                  /* primary character block (?) */
266     *(p+0x2c) = 0;                  /* secondary character block (?) */
267     *(p+0x2d) =                     /* miscellaneous flags */
268         (pBiosData->VGASettings & 0x0f)
269       | ((pBiosData->ModeOptions & 1) << 4); /* cursor emulation */
270     *(p+0x2e) = 0;                  /* non-VGA mode support */
271     *(WORD *)(p+0x2f) = 0;          /* reserved */
272     *(p+0x31) =                     /* video memory available */
273       (pBiosData->ModeOptions & 0x60 >> 5);
274     *(p+0x32) = 0;                  /* save pointer state flags */
275     *(p+0x33) = 4;                  /* display info and status */
276
277     /* BIOS date string */
278     strcpy((char *)pBiosSys+0xfff5, "13/01/99");
279
280     /* BIOS ID */
281     *(pBiosSys+0xfffe) = 0xfc;
282 }
283
284 /***********************************************************************
285  *           DOSMEM_InitCollateTable
286  *
287  * Initialises the collate table (character sorting, language dependent)
288  */
289 static void DOSMEM_InitCollateTable()
290 {
291         DWORD           x;
292         unsigned char   *tbl;
293         int             i;
294
295         x = GlobalDOSAlloc16(258);
296         DOSMEM_CollateTable = MAKELONG(0,(x>>16));
297         tbl = DOSMEM_MapRealToLinear(DOSMEM_CollateTable);
298         *(WORD*)tbl     = 0x100;
299         tbl += 2;
300         for ( i = 0; i < 0x100; i++) *tbl++ = i;
301 }
302
303 /***********************************************************************
304  *           DOSMEM_InitErrorTable
305  *
306  * Initialises the error tables (DOS 5+)
307  */
308 static void DOSMEM_InitErrorTable()
309 {
310         DWORD           x;
311         char            *call;
312
313         /* We will use a snippet of real mode code that calls */
314         /* a WINE-only interrupt to handle moving the requested */
315         /* message into the buffer... */
316
317         /* FIXME - There is still something wrong... */
318
319         /* FIXME - Find hex values for opcodes...
320            
321            (On call, AX contains message number
322                      DI contains 'offset' (??)
323             Resturn, ES:DI points to counted string )
324
325            PUSH BX
326            MOV BX, AX
327            MOV AX, (arbitrary subfunction number)
328            INT (WINE-only interrupt)
329            POP BX
330            RET
331
332         */
333            
334         const int       code = 4;       
335         const int       buffer = 80; 
336         const int       SIZE_TO_ALLOCATE = code + buffer;
337
338         /* FIXME - Complete rewrite of the table system to save */
339         /* precious DOS space. Now, we return the 0001:???? as */
340         /* DOS 4+ (??, it seems to be the case in MS 7.10) treats that */
341         /* as a special case and programs will use the alternate */
342         /* interface (a farcall returned with INT 24 (AX = 0x122e, DL = */
343         /* 0x08) which lets us have a smaller memory footprint anyway. */
344  
345         x = GlobalDOSAlloc16(SIZE_TO_ALLOCATE);  
346
347         DOSMEM_ErrorCall = MAKELONG(0,(x>>16));
348         DOSMEM_ErrorBuffer = DOSMEM_ErrorCall + code;
349
350         call = DOSMEM_MapRealToLinear(DOSMEM_ErrorCall);
351
352         memset(call, 0, SIZE_TO_ALLOCATE);
353
354         /* Fixme - Copy assembly into buffer here */        
355 }
356
357 /***********************************************************************
358  *           DOSMEM_InitMemory
359  *
360  * Initialises the DOS memory structures.
361  */
362 static void DOSMEM_InitMemory(HMODULE16 hModule)
363 {
364    /* Low 64Kb are reserved for DOS/BIOS so the useable area starts at
365     * 1000:0000 and ends at 9FFF:FFEF. */
366
367     dosmem_info*        info_block = DOSMEM_InfoBlock(hModule);
368     dosmem_entry*       root_block = DOSMEM_RootBlock(hModule);
369     dosmem_entry*       dm;
370
371     root_block->size = DOSMEM_MemoryTop(hModule) - (((char*)root_block) + sizeof(dosmem_entry));
372
373     info_block->blocks = 0;
374     info_block->free = root_block->size;
375
376     dm = NEXT_BLOCK(root_block);
377     dm->size = DM_BLOCK_TERMINAL;
378     root_block->size |= DM_BLOCK_FREE 
379 #ifdef __DOSMEM_DEBUG__
380                      | DM_BLOCK_DEBUG;
381 #endif
382                      ;
383 }
384
385 /***********************************************************************
386  *           DOSMEM_MovePointers
387  *
388  * Relocates any pointers into DOS memory to a new address space.
389  */
390 static void DOSMEM_MovePointers(LPVOID dest, LPVOID src, DWORD size)
391 {
392   unsigned long delta = (char *) dest - (char *) src;
393   unsigned cnt;
394   ldt_entry ent;
395
396   /* relocate base addresses of any selectors pointing into memory */
397   for (cnt=FIRST_LDT_ENTRY_TO_ALLOC; cnt<LDT_SIZE; cnt++) {
398     LDT_GetEntry(cnt, &ent);
399     if ((ent.base >= (unsigned long)src) && \
400         (ent.base < ((unsigned long)src + size))) {
401       ent.base += delta;
402       LDT_SetEntry(cnt, &ent);
403     }
404   }
405 }
406
407 /***********************************************************************
408  *           DOSMEM_Init
409  *
410  * Create the dos memory segments, and store them into the KERNEL
411  * exported values.
412  */
413 BOOL DOSMEM_Init(HMODULE16 hModule)
414 {
415     if (!hModule)
416     {
417         /* Allocate 1 MB dosmemory 
418          * - it is mostly wasted but we can use some of it to 
419          *   store internal translation tables, etc...
420          */
421         DOSMEM_dosmem = VirtualAlloc( NULL, 0x100000, MEM_COMMIT,
422                                       PAGE_EXECUTE_READWRITE );
423         if (!DOSMEM_dosmem)
424         {
425             WARN_(dosmem)("Could not allocate DOS memory.\n" );
426             return FALSE;
427         }
428         DOSMEM_BiosDataSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_dosmem+0x400,
429                                      0x100, 0, FALSE, FALSE, FALSE, NULL );
430         DOSMEM_BiosSysSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_dosmem+0xf0000,
431                                      0x10000, 0, FALSE, FALSE, FALSE, NULL );
432         DOSMEM_FillIsrTable(0);
433         DOSMEM_FillBiosSegments();
434         DOSMEM_InitMemory(0);
435         DOSMEM_InitCollateTable();
436         DOSMEM_InitErrorTable();
437         DOSMEM_InitDPMI();
438         DOSDEV_InstallDOSDevices();
439     }
440     else
441     {
442 #if 0
443         DOSMEM_FillIsrTable(hModule);
444         DOSMEM_InitMemory(hModule);
445 #else
446         LPVOID base = DOSMEM_MemoryBase(hModule);
447
448         /* bootstrap the new V86 task with a copy of the "system" memory */
449         memcpy(base, DOSMEM_dosmem, 0x100000);
450         /* then move existing selectors to it */
451         DOSMEM_MovePointers(base, DOSMEM_dosmem, 0x100000);
452 #endif
453     }
454     return TRUE;
455 }
456
457
458 /***********************************************************************
459  *           DOSMEM_Tick
460  *
461  * Increment the BIOS tick counter. Called by timer signal handler.
462  */
463 void DOSMEM_Tick( WORD timer )
464 {
465     BIOSDATA *pBiosData = DOSMEM_BiosData();
466     if (pBiosData) pBiosData->Ticks++;
467 }
468
469 /***********************************************************************
470  *           DOSMEM_GetBlock
471  *
472  * Carve a chunk of the DOS memory block (without selector).
473  */
474 LPVOID DOSMEM_GetBlock(HMODULE16 hModule, UINT size, UINT16* pseg)
475 {
476    UINT          blocksize;
477    char         *block = NULL;
478    dosmem_info  *info_block = DOSMEM_InfoBlock(hModule);
479    dosmem_entry *dm;
480 #ifdef __DOSMEM_DEBUG_
481    dosmem_entry *prev = NULL;
482 #endif
483  
484    if( size > info_block->free ) return NULL;
485    dm = DOSMEM_RootBlock(hModule);
486
487    while (dm && dm->size != DM_BLOCK_TERMINAL)
488    {
489 #ifdef __DOSMEM_DEBUG__
490        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
491        {
492             WARN_(dosmem)("MCB overrun! [prev = 0x%08x]\n", 4 + (UINT)prev);
493             return NULL;
494        }
495        prev = dm;
496 #endif
497        if( dm->size & DM_BLOCK_FREE )
498        {
499            dosmem_entry  *next = NEXT_BLOCK(dm);
500
501            while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
502            {
503                dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
504                next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
505                next = NEXT_BLOCK(dm);
506            }
507
508            blocksize = dm->size & DM_BLOCK_MASK;
509            if( blocksize >= size )
510            {
511                block = ((char*)dm) + sizeof(dosmem_entry);
512                if( blocksize - size > 0x20 )
513                {
514                    /* split dm so that the next one stays
515                     * paragraph-aligned (and dm loses free bit) */
516
517                    dm->size = (((size + 0xf + sizeof(dosmem_entry)) & ~0xf) -
518                                               sizeof(dosmem_entry));
519                    next = (dosmem_entry*)(((char*)dm) + 
520                            sizeof(dosmem_entry) + dm->size);
521                    next->size = (blocksize - (dm->size + 
522                            sizeof(dosmem_entry))) | DM_BLOCK_FREE 
523 #ifdef __DOSMEM_DEBUG__
524                                                   | DM_BLOCK_DEBUG
525 #endif
526                                                   ;
527                } else dm->size &= DM_BLOCK_MASK;
528
529                info_block->blocks++;
530                info_block->free -= dm->size;
531                if( pseg ) *pseg = (block - DOSMEM_MemoryBase(hModule)) >> 4;
532 #ifdef __DOSMEM_DEBUG__
533                dm->size |= DM_BLOCK_DEBUG;
534 #endif
535                break;
536            }
537            dm = next;
538        }
539        else dm = NEXT_BLOCK(dm);
540    }
541    return (LPVOID)block;
542 }
543
544 /***********************************************************************
545  *           DOSMEM_FreeBlock
546  */
547 BOOL DOSMEM_FreeBlock(HMODULE16 hModule, void* ptr)
548 {
549    dosmem_info  *info_block = DOSMEM_InfoBlock(hModule);
550
551    if( ptr >= (void*)(((char*)DOSMEM_RootBlock(hModule)) + sizeof(dosmem_entry)) &&
552        ptr < (void*)DOSMEM_MemoryTop(hModule) && !((((char*)ptr)
553                   - DOSMEM_MemoryBase(hModule)) & 0xf) )
554    {
555        dosmem_entry  *dm = (dosmem_entry*)(((char*)ptr) - sizeof(dosmem_entry));
556
557        if( !(dm->size & (DM_BLOCK_FREE | DM_BLOCK_TERMINAL))
558 #ifdef __DOSMEM_DEBUG__
559          && ((dm->size & DM_BLOCK_DEBUG) == DM_BLOCK_DEBUG )
560 #endif
561          )
562        {
563              info_block->blocks--;
564              info_block->free += dm->size;
565
566              dm->size |= DM_BLOCK_FREE;
567              return TRUE;
568        }
569    }
570    return FALSE;
571 }
572
573 /***********************************************************************
574  *           DOSMEM_ResizeBlock
575  */
576 LPVOID DOSMEM_ResizeBlock(HMODULE16 hModule, void* ptr, UINT size, UINT16* pseg)
577 {
578    char         *block = NULL;
579    dosmem_info  *info_block = DOSMEM_InfoBlock(hModule);
580
581    if( ptr >= (void*)(((char*)DOSMEM_RootBlock(hModule)) + sizeof(dosmem_entry)) &&
582        ptr < (void*)DOSMEM_MemoryTop(hModule) && !((((char*)ptr)
583                   - DOSMEM_MemoryBase(hModule)) & 0xf) )
584    {
585        dosmem_entry  *dm = (dosmem_entry*)(((char*)ptr) - sizeof(dosmem_entry));
586
587        if( pseg ) *pseg = ((char*)ptr - DOSMEM_MemoryBase(hModule)) >> 4;
588
589        if( !(dm->size & (DM_BLOCK_FREE | DM_BLOCK_TERMINAL))
590          )
591        {
592              dosmem_entry  *next = NEXT_BLOCK(dm);
593              UINT blocksize, orgsize = dm->size & DM_BLOCK_MASK;
594
595              while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
596              {
597                  dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
598                  next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
599                  next = NEXT_BLOCK(dm);
600              }
601
602              blocksize = dm->size & DM_BLOCK_MASK;
603              if (blocksize >= size)
604              {
605                  block = ((char*)dm) + sizeof(dosmem_entry);
606                  if( blocksize - size > 0x20 )
607                  {
608                      /* split dm so that the next one stays
609                       * paragraph-aligned (and next gains free bit) */
610
611                      dm->size = (((size + 0xf + sizeof(dosmem_entry)) & ~0xf) -
612                                                 sizeof(dosmem_entry));
613                      next = (dosmem_entry*)(((char*)dm) + 
614                              sizeof(dosmem_entry) + dm->size);
615                      next->size = (blocksize - (dm->size + 
616                              sizeof(dosmem_entry))) | DM_BLOCK_FREE 
617                                                     ;
618                  } else dm->size &= DM_BLOCK_MASK;
619
620                  info_block->free += orgsize - dm->size;
621              } else {
622                  /* the collapse didn't help, try getting a new block */
623                  block = DOSMEM_GetBlock(hModule, size, pseg);
624                  if (block) {
625                      /* we got one, copy the old data there (we do need to, right?) */
626                      memcpy(block, ((char*)dm) + sizeof(dosmem_entry),
627                                    (size<orgsize) ? size : orgsize);
628                      /* free old block */
629                      info_block->blocks--;
630                      info_block->free += dm->size;
631
632                      dm->size |= DM_BLOCK_FREE;
633                  } else {
634                      /* and Bill Gates said 640K should be enough for everyone... */
635
636                      /* need to split original and collapsed blocks apart again,
637                       * and free the collapsed blocks again, before exiting */
638                      if( blocksize - orgsize > 0x20 )
639                      {
640                          /* split dm so that the next one stays
641                           * paragraph-aligned (and next gains free bit) */
642
643                          dm->size = (((orgsize + 0xf + sizeof(dosmem_entry)) & ~0xf) -
644                                                        sizeof(dosmem_entry));
645                          next = (dosmem_entry*)(((char*)dm) + 
646                                  sizeof(dosmem_entry) + dm->size);
647                          next->size = (blocksize - (dm->size + 
648                                  sizeof(dosmem_entry))) | DM_BLOCK_FREE 
649                                                         ;
650                      } else dm->size &= DM_BLOCK_MASK;
651                  }
652              }
653        }
654    }
655    return (LPVOID)block;
656 }
657
658
659 /***********************************************************************
660  *           DOSMEM_Available
661  */
662 UINT DOSMEM_Available(HMODULE16 hModule)
663 {
664    UINT          blocksize, available = 0;
665    dosmem_entry *dm;
666    
667    dm = DOSMEM_RootBlock(hModule);
668
669    while (dm && dm->size != DM_BLOCK_TERMINAL)
670    {
671 #ifdef __DOSMEM_DEBUG__
672        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
673        {
674             WARN_(dosmem)("MCB overrun! [prev = 0x%08x]\n", 4 + (UINT)prev);
675             return NULL;
676        }
677        prev = dm;
678 #endif
679        if( dm->size & DM_BLOCK_FREE )
680        {
681            dosmem_entry  *next = NEXT_BLOCK(dm);
682
683            while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
684            {
685                dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
686                next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
687                next = NEXT_BLOCK(dm);
688            }
689
690            blocksize = dm->size & DM_BLOCK_MASK;
691            if ( blocksize > available ) available = blocksize;
692            dm = next;
693        }
694        else dm = NEXT_BLOCK(dm);
695    }
696    return available;
697 }
698
699
700 /***********************************************************************
701  *           DOSMEM_MapLinearToDos
702  *
703  * Linear address to the DOS address space.
704  */
705 UINT DOSMEM_MapLinearToDos(LPVOID ptr)
706 {
707     if (((char*)ptr >= DOSMEM_MemoryBase(0)) &&
708         ((char*)ptr < DOSMEM_MemoryBase(0) + 0x100000))
709           return (UINT)ptr - (UINT)DOSMEM_MemoryBase(0);
710     return (UINT)ptr;
711 }
712
713
714 /***********************************************************************
715  *           DOSMEM_MapDosToLinear
716  *
717  * DOS linear address to the linear address space.
718  */
719 LPVOID DOSMEM_MapDosToLinear(UINT ptr)
720 {
721     if (ptr < 0x100000) return (LPVOID)(ptr + (UINT)DOSMEM_MemoryBase(0));
722     return (LPVOID)ptr;
723 }
724
725
726 /***********************************************************************
727  *           DOSMEM_MapRealToLinear
728  *
729  * Real mode DOS address into a linear pointer
730  */
731 LPVOID DOSMEM_MapRealToLinear(DWORD x)
732 {
733    LPVOID       lin;
734
735    lin=DOSMEM_MemoryBase(0)+(x&0xffff)+(((x&0xffff0000)>>16)*16);
736    TRACE_(selector)("(0x%08lx) returns 0x%p.\n",
737                     x,lin );
738    return lin;
739 }
740
741 /***********************************************************************
742  *           DOSMEM_AllocSelector
743  *
744  * Allocates a protected mode selector for a realmode segment.
745  */
746 WORD DOSMEM_AllocSelector(WORD realsel)
747 {
748         HMODULE16 hModule = GetModuleHandle16("KERNEL");
749         WORD    sel;
750
751         sel=GLOBAL_CreateBlock(
752                 GMEM_FIXED,DOSMEM_dosmem+realsel*16,0x10000,
753                 hModule,FALSE,FALSE,FALSE,NULL
754         );
755         TRACE_(selector)("(0x%04x) returns 0x%04x.\n",
756                 realsel,sel
757         );
758         return sel;
759 }
760