Implemented marshalling of pointers, simple and complex structures,
[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 <time.h>
34 #ifdef HAVE_SYS_TIME_H
35 # include <sys/time.h>
36 #endif
37
38 #include "winbase.h"
39 #include "wine/winbase16.h"
40
41 #include "global.h"
42 #include "selectors.h"
43 #include "miscemu.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(dosmem);
47 WINE_DECLARE_DEBUG_CHANNEL(selector);
48
49 WORD DOSMEM_0000H;        /* segment at 0:0 */
50 WORD DOSMEM_BiosDataSeg;  /* BIOS data segment at 0x40:0 */
51 WORD DOSMEM_BiosSysSeg;   /* BIOS ROM segment at 0xf000:0 */
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 /* Start of DOS conventional memory */
89 static char *DOSMEM_membase;
90
91 static void DOSMEM_InitMemory(void);
92
93 /***********************************************************************
94  *           DOSMEM_MemoryTop
95  *
96  * Gets the DOS memory top.
97  */
98 static char *DOSMEM_MemoryTop(void)
99 {
100     return DOSMEM_dosmem+0x9FFFC; /* 640K */
101 }
102
103 /***********************************************************************
104  *           DOSMEM_InfoBlock
105  *
106  * Gets the DOS memory info block.
107  */
108 static dosmem_info *DOSMEM_InfoBlock(void)
109 {
110     if (!DOSMEM_membase)
111     {
112         DWORD         reserve;
113
114         /*
115          * Reserve either:
116          * - lowest 64k for NULL pointer catching (Win16)
117          * - lowest 1k for interrupt handlers and 
118          *   another 0.5k for BIOS, DOS and intra-application
119          *   areas (DOS)
120          */
121         if (DOSMEM_dosmem != DOSMEM_sysmem)
122             reserve = 0x10000; /* 64k */
123         else
124             reserve = 0x600; /* 1.5k */
125
126         /*
127          * Round to paragraph boundary in order to make 
128          * sure the alignment is correct.
129          */
130         reserve = ((reserve + 15) >> 4) << 4;
131
132         /*
133          * Set DOS memory base and initialize conventional memory.
134          */
135         DOSMEM_membase = DOSMEM_dosmem + reserve;
136         DOSMEM_InitMemory();
137     }
138
139     return (dosmem_info*)DOSMEM_membase;
140 }
141
142 /***********************************************************************
143  *           DOSMEM_RootBlock
144  *
145  * Gets the DOS memory root block.
146  */
147 static dosmem_entry *DOSMEM_RootBlock(void)
148 {
149     /* first block has to be paragraph-aligned */
150     return (dosmem_entry*)(((char*)DOSMEM_InfoBlock()) +
151                            ((((sizeof(dosmem_info) + 0xf) & ~0xf) - sizeof(dosmem_entry))));
152 }
153
154 /***********************************************************************
155  *           DOSMEM_FillIsrTable
156  *
157  * Fill the interrupt table with fake BIOS calls to BIOSSEG (0xf000).
158  *
159  * NOTES:
160  * Linux normally only traps INTs performed from or destined to BIOSSEG
161  * for us to handle, if the int_revectored table is empty. Filling the
162  * interrupt table with calls to INT stubs in BIOSSEG allows DOS programs
163  * to hook interrupts, as well as use their familiar retf tricks to call
164  * them, AND let Wine handle any unhooked interrupts transparently.
165  */
166 static void DOSMEM_FillIsrTable(void)
167 {
168     SEGPTR *isr = (SEGPTR*)DOSMEM_sysmem;
169     int x;
170
171     for (x=0; x<256; x++) isr[x]=MAKESEGPTR(VM_STUB_SEGMENT,x*4);
172 }
173
174 static void DOSMEM_MakeIsrStubs(void)
175 {
176     DWORD *stub = (DWORD*)(DOSMEM_dosmem + (VM_STUB_SEGMENT << 4));
177     int x;
178
179     for (x=0; x<256; x++) stub[x]=VM_STUB(x);
180 }
181
182 static BIOSDATA * DOSMEM_BiosData(void)
183 {
184     return (BIOSDATA *)(DOSMEM_sysmem + 0x400);
185 }
186
187 /**********************************************************************
188  *          DOSMEM_GetTicksSinceMidnight
189  *
190  * Return number of clock ticks since midnight.
191  */
192 static DWORD DOSMEM_GetTicksSinceMidnight(void)
193 {
194     struct tm *bdtime;
195     struct timeval tvs;
196     time_t seconds;
197
198     /* This should give us the (approximately) correct
199      * 18.206 clock ticks per second since midnight.
200      */
201     gettimeofday( &tvs, NULL );
202     seconds = tvs.tv_sec;
203     bdtime = localtime( &seconds );
204     return (((bdtime->tm_hour * 3600 + bdtime->tm_min * 60 +
205               bdtime->tm_sec) * 18206) / 1000) +
206                   (tvs.tv_usec / 54927);
207 }
208
209 /***********************************************************************
210  *           DOSMEM_FillBiosSegments
211  *
212  * Fill the BIOS data segment with dummy values.
213  */
214 static void DOSMEM_FillBiosSegments(void)
215 {
216     BYTE *pBiosSys = DOSMEM_dosmem + 0xf0000;
217     BYTE *pBiosROMTable = pBiosSys+0xe6f5;
218     BIOS_EXTRA *extra = (BIOS_EXTRA *)(DOSMEM_dosmem + (int)BIOS_EXTRA_PTR);
219     BIOSDATA *pBiosData = DOSMEM_BiosData();
220
221     /* Supported VESA mode, see int10.c */
222     WORD ConstVesaModeList[]={0x00,0x01,0x02,0x03,0x07,0x0D,0x0E,0x10,0x12,0x13,
223                               0x100,0x101,0x102,0x103,0x104,0x105,0x106,0x107,0x10D,0x10E,
224                               0x10F,0x110,0x111,0x112,0x113,0x114,0x115,0x116,0x117,0x118,
225                               0x119,0x11A,0x11B,0xFFFF};
226     char * ConstVesaString = "WINE SVGA BOARD";
227     int i;
228
229     VIDEOFUNCTIONALITY *pVidFunc = &extra->vid_func;
230     VIDEOSTATE *pVidState = &extra->vid_state;
231     VESAINFO *pVesaInfo = &extra->vesa_info;
232     char * VesaString = extra->vesa_string;
233     WORD * VesaModeList = extra->vesa_modes;
234
235       /* Clear all unused values */
236     memset( pBiosData, 0, sizeof(*pBiosData) );
237     memset( pVidFunc,  0, sizeof(*pVidFunc ) );
238     memset( pVidState, 0, sizeof(*pVidState) );
239     memset( pVesaInfo, 0, sizeof(*pVesaInfo) );
240
241     /* FIXME: should check the number of configured drives and ports */
242     pBiosData->Com1Addr             = 0x3f8;
243     pBiosData->Com2Addr             = 0x2f8;
244     pBiosData->Lpt1Addr             = 0x378;
245     pBiosData->Lpt2Addr             = 0x278;
246     pBiosData->InstalledHardware    = 0x5463;
247     pBiosData->MemSize              = 640;
248     pBiosData->NextKbdCharPtr       = 0x1e;
249     pBiosData->FirstKbdCharPtr      = 0x1e;
250     pBiosData->VideoMode            = 3;
251     pBiosData->VideoColumns         = 80;
252     pBiosData->VideoPageSize        = 80 * 25 * 2;
253     pBiosData->VideoPageStartAddr   = 0xb800;
254     pBiosData->VideoCtrlAddr        = 0x3d4;
255     pBiosData->Ticks                = DOSMEM_GetTicksSinceMidnight();
256     pBiosData->NbHardDisks          = 2;
257     pBiosData->KbdBufferStart       = 0x1e;
258     pBiosData->KbdBufferEnd         = 0x3e;
259     pBiosData->RowsOnScreenMinus1   = 24;
260     pBiosData->BytesPerChar         = 0x10;
261     pBiosData->ModeOptions          = 0x64;
262     pBiosData->FeatureBitsSwitches  = 0xf9;
263     pBiosData->VGASettings          = 0x51;
264     pBiosData->DisplayCombination   = 0x08;
265     pBiosData->DiskDataRate         = 0;
266
267     /* fill ROM configuration table (values from Award) */
268     *(pBiosROMTable+0x0)        = 0x08; /* number of bytes following LO */
269     *(pBiosROMTable+0x1)        = 0x00; /* number of bytes following HI */
270     *(pBiosROMTable+0x2)        = 0xfc; /* model */
271     *(pBiosROMTable+0x3)        = 0x01; /* submodel */
272     *(pBiosROMTable+0x4)        = 0x00; /* BIOS revision */
273     *(pBiosROMTable+0x5)        = 0x74; /* feature byte 1 */
274     *(pBiosROMTable+0x6)        = 0x00; /* feature byte 2 */
275     *(pBiosROMTable+0x7)        = 0x00; /* feature byte 3 */
276     *(pBiosROMTable+0x8)        = 0x00; /* feature byte 4 */
277     *(pBiosROMTable+0x9)        = 0x00; /* feature byte 5 */
278
279
280     for (i = 0; i < 7; i++)
281         pVidFunc->ModeSupport[i] = 0xff;
282
283     pVidFunc->ScanlineSupport     = 7;
284     pVidFunc->NumberCharBlocks    = 0;
285     pVidFunc->ActiveCharBlocks    = 0;
286     pVidFunc->MiscFlags           = 0x8ff;
287     pVidFunc->SavePointerFlags    = 0x3f;
288
289                                     /* FIXME: always real mode ? */
290     pVidState->StaticFuncTable    = BIOS_EXTRA_SEGPTR + offsetof(BIOS_EXTRA,vid_func);
291     pVidState->VideoMode          = pBiosData->VideoMode; /* needs updates! */
292     pVidState->NumberColumns      = pBiosData->VideoColumns; /* needs updates! */
293     pVidState->RegenBufLen        = 0;
294     pVidState->RegenBufAddr       = 0;
295
296     for (i = 0; i < 8; i++)
297         pVidState->CursorPos[i] = 0;
298
299     pVidState->CursorType         = 0x0a0b;  /* start/end line */
300     pVidState->ActivePage         = 0;
301     pVidState->CRTCPort           = 0x3da;
302     pVidState->Port3x8            = 0;
303     pVidState->Port3x9            = 0;
304     pVidState->NumberRows         = 23;     /* number of rows - 1 */
305     pVidState->BytesPerChar       = 0x10;
306     pVidState->DCCActive          = pBiosData->DisplayCombination;
307     pVidState->DCCAlternate       = 0;
308     pVidState->NumberColors       = 16;
309     pVidState->NumberPages        = 1;
310     pVidState->NumberScanlines    = 3; /* (0,1,2,3) = (200,350,400,480) */
311     pVidState->CharBlockPrimary   = 0;
312     pVidState->CharBlockSecondary = 0;
313     pVidState->MiscFlags =
314                            (pBiosData->VGASettings & 0x0f)
315                          | ((pBiosData->ModeOptions & 1) << 4); /* cursor emulation */
316     pVidState->NonVGASupport      = 0;
317     pVidState->VideoMem           = (pBiosData->ModeOptions & 0x60 >> 5);
318     pVidState->SavePointerState   = 0;
319     pVidState->DisplayStatus      = 4;
320
321     /* SVGA structures */
322     pVesaInfo->Signature          = *(DWORD*)"VESA";
323     pVesaInfo->Major              = 2;
324     pVesaInfo->Minor              = 0;
325                                     /* FIXME: always real mode ? */
326     pVesaInfo->StaticVendorString = BIOS_EXTRA_SEGPTR + offsetof(BIOS_EXTRA,vesa_string);
327     pVesaInfo->CapabilitiesFlags  = 0xfffffffd; /* FIXME: not really supported */
328                                     /* FIXME: always real mode ? */
329     pVesaInfo->StaticModeList     = BIOS_EXTRA_SEGPTR + offsetof(BIOS_EXTRA,vesa_modes);
330
331     strcpy(VesaString,ConstVesaString);
332     memcpy(VesaModeList,ConstVesaModeList,sizeof(ConstVesaModeList));
333
334     /* BIOS date string */
335     strcpy((char *)pBiosSys+0xfff5, "13/01/99");
336
337     /* BIOS ID */
338     *(pBiosSys+0xfffe) = 0xfc;
339 }
340
341 /***********************************************************************
342  *           DOSMEM_InitMemory
343  *
344  * Initialises the DOS memory structures.
345  */
346 static void DOSMEM_InitMemory(void)
347 {
348     dosmem_info*        info_block = DOSMEM_InfoBlock();
349     dosmem_entry*       root_block = DOSMEM_RootBlock();
350     dosmem_entry*       dm;
351
352     root_block->size = DOSMEM_MemoryTop() - (((char*)root_block) + sizeof(dosmem_entry));
353
354     info_block->blocks = 0;
355     info_block->free = root_block->size;
356
357     dm = NEXT_BLOCK(root_block);
358     dm->size = DM_BLOCK_TERMINAL;
359     root_block->size |= DM_BLOCK_FREE
360 #ifdef __DOSMEM_DEBUG__
361                      | DM_BLOCK_DEBUG
362 #endif
363                      ;
364
365     TRACE( "DOS conventional memory initialized, %d bytes free.\n", 
366            DOSMEM_Available() );
367 }
368
369
370 /**********************************************************************
371  *              setup_dos_mem
372  *
373  * Setup the first megabyte for DOS memory access
374  */
375 static void setup_dos_mem( int dos_init )
376 {
377     int sys_offset = 0;
378     int page_size = getpagesize();
379     void *addr = wine_anon_mmap( (void *)page_size, 0x110000-page_size,
380                                  PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
381     if (addr == (void *)page_size)  /* we got what we wanted */
382     {
383         /* now map from address 0 */
384         addr = wine_anon_mmap( NULL, 0x110000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED );
385         if (addr)
386         {
387             ERR("MAP_FIXED failed at address 0 for DOS address space\n" );
388             ExitProcess(1);
389         }
390
391         /* inform the memory manager that there is a mapping here */
392         VirtualAlloc( addr, 0x110000, MEM_RESERVE | MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
393
394         /* protect the first 64K to catch NULL pointers */
395         if (!dos_init)
396         {
397             VirtualProtect( addr, 0x10000, PAGE_NOACCESS, NULL );
398             /* move the BIOS and ISR area from 0x00000 to 0xf0000 */
399             sys_offset += 0xf0000;
400         }
401     }
402     else
403     {
404         ERR("Cannot use first megabyte for DOS address space, please report\n" );
405         if (dos_init) ExitProcess(1);
406         /* allocate the DOS area somewhere else */
407         addr = VirtualAlloc( NULL, 0x110000, MEM_COMMIT, PAGE_EXECUTE_READWRITE );
408         if (!addr)
409         {
410             ERR( "Cannot allocate DOS memory\n" );
411             ExitProcess(1);
412         }
413     }
414     DOSMEM_dosmem = addr;
415     DOSMEM_sysmem = (char*)addr + sys_offset;
416 }
417
418
419 /***********************************************************************
420  *           DOSMEM_Init
421  *
422  * Create the dos memory segments, and store them into the KERNEL
423  * exported values.
424  */
425 BOOL DOSMEM_Init(BOOL dos_init)
426 {
427     static int already_done, already_mapped;
428
429     if (!already_done)
430     {
431         setup_dos_mem( dos_init );
432
433         DOSMEM_0000H = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem,
434                                            0x10000, 0, WINE_LDT_FLAGS_DATA );
435         DOSMEM_BiosDataSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_sysmem + 0x400,
436                                                 0x100, 0, WINE_LDT_FLAGS_DATA );
437         DOSMEM_BiosSysSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_dosmem+0xf0000,
438                                                0x10000, 0, WINE_LDT_FLAGS_DATA );
439         DOSMEM_FillBiosSegments();
440         DOSMEM_FillIsrTable();
441         already_done = 1;
442     }
443     else if (dos_init && !already_mapped)
444     {
445         if (DOSMEM_dosmem)
446         {
447             ERR( "Needs access to the first megabyte for DOS mode\n" );
448             ExitProcess(1);
449         }
450         MESSAGE( "Warning: unprotecting the first 64KB of memory to allow real-mode calls.\n"
451                  "         NULL pointer accesses will no longer be caught.\n" );
452         VirtualProtect( NULL, 0x10000, PAGE_EXECUTE_READWRITE, NULL );
453         /* copy the BIOS and ISR area down */
454         memcpy( DOSMEM_dosmem, DOSMEM_sysmem, 0x400 + 0x100 );
455         DOSMEM_sysmem = DOSMEM_dosmem;
456         SetSelectorBase( DOSMEM_0000H, 0 );
457         SetSelectorBase( DOSMEM_BiosDataSeg, 0x400 );
458         /* we may now need the actual interrupt stubs, and since we've just moved the
459          * interrupt vector table away, we can fill the area with stubs instead... */
460         DOSMEM_MakeIsrStubs();
461         already_mapped = 1;
462     }
463     return TRUE;
464 }
465
466
467 /***********************************************************************
468  *           DOSMEM_Tick
469  *
470  * Increment the BIOS tick counter. Called by timer signal handler.
471  */
472 void DOSMEM_Tick( WORD timer )
473 {
474     BIOSDATA *pBiosData = DOSMEM_BiosData();
475     if (pBiosData) pBiosData->Ticks++;
476 }
477
478 /***********************************************************************
479  *           DOSMEM_GetBlock
480  *
481  * Carve a chunk of the DOS memory block (without selector).
482  */
483 LPVOID DOSMEM_GetBlock(UINT size, UINT16* pseg)
484 {
485    UINT          blocksize;
486    char         *block = NULL;
487    dosmem_info  *info_block = DOSMEM_InfoBlock();
488    dosmem_entry *dm;
489 #ifdef __DOSMEM_DEBUG_
490    dosmem_entry *prev = NULL;
491 #endif
492
493    if( size > info_block->free ) return NULL;
494    dm = DOSMEM_RootBlock();
495
496    while (dm && dm->size != DM_BLOCK_TERMINAL)
497    {
498 #ifdef __DOSMEM_DEBUG__
499        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
500        {
501             WARN("MCB overrun! [prev = 0x%08x]\n", 4 + (UINT)prev);
502             return NULL;
503        }
504        prev = dm;
505 #endif
506        if( dm->size & DM_BLOCK_FREE )
507        {
508            dosmem_entry  *next = NEXT_BLOCK(dm);
509
510            while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
511            {
512                dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
513                next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
514                next = NEXT_BLOCK(dm);
515            }
516
517            blocksize = dm->size & DM_BLOCK_MASK;
518            if( blocksize >= size )
519            {
520                block = ((char*)dm) + sizeof(dosmem_entry);
521                if( blocksize - size > 0x20 )
522                {
523                    /* split dm so that the next one stays
524                     * paragraph-aligned (and dm loses free bit) */
525
526                    dm->size = (((size + 0xf + sizeof(dosmem_entry)) & ~0xf) -
527                                               sizeof(dosmem_entry));
528                    next = (dosmem_entry*)(((char*)dm) +
529                            sizeof(dosmem_entry) + dm->size);
530                    next->size = (blocksize - (dm->size +
531                            sizeof(dosmem_entry))) | DM_BLOCK_FREE
532 #ifdef __DOSMEM_DEBUG__
533                                                   | DM_BLOCK_DEBUG
534 #endif
535                                                   ;
536                } else dm->size &= DM_BLOCK_MASK;
537
538                info_block->blocks++;
539                info_block->free -= dm->size;
540                if( pseg ) *pseg = (block - DOSMEM_dosmem) >> 4;
541 #ifdef __DOSMEM_DEBUG__
542                dm->size |= DM_BLOCK_DEBUG;
543 #endif
544                break;
545            }
546            dm = next;
547        }
548        else dm = NEXT_BLOCK(dm);
549    }
550    return (LPVOID)block;
551 }
552
553 /***********************************************************************
554  *           DOSMEM_FreeBlock
555  */
556 BOOL DOSMEM_FreeBlock(void* ptr)
557 {
558    dosmem_info  *info_block = DOSMEM_InfoBlock();
559
560    if( ptr >= (void*)(((char*)DOSMEM_RootBlock()) + sizeof(dosmem_entry)) &&
561        ptr < (void*)DOSMEM_MemoryTop() && !((((char*)ptr)
562                   - DOSMEM_dosmem) & 0xf) )
563    {
564        dosmem_entry  *dm = (dosmem_entry*)(((char*)ptr) - sizeof(dosmem_entry));
565
566        if( !(dm->size & (DM_BLOCK_FREE | DM_BLOCK_TERMINAL))
567 #ifdef __DOSMEM_DEBUG__
568          && ((dm->size & DM_BLOCK_DEBUG) == DM_BLOCK_DEBUG )
569 #endif
570          )
571        {
572              info_block->blocks--;
573              info_block->free += dm->size;
574
575              dm->size |= DM_BLOCK_FREE;
576              return TRUE;
577        }
578    }
579    return FALSE;
580 }
581
582 /***********************************************************************
583  *           DOSMEM_ResizeBlock
584  */
585 LPVOID DOSMEM_ResizeBlock(void* ptr, UINT size, UINT16* pseg)
586 {
587    char         *block = NULL;
588    dosmem_info  *info_block = DOSMEM_InfoBlock();
589
590    if( ptr >= (void*)(((char*)DOSMEM_RootBlock()) + sizeof(dosmem_entry)) &&
591        ptr < (void*)DOSMEM_MemoryTop() && !((((char*)ptr)
592                   - DOSMEM_dosmem) & 0xf) )
593    {
594        dosmem_entry  *dm = (dosmem_entry*)(((char*)ptr) - sizeof(dosmem_entry));
595
596        if( pseg ) *pseg = ((char*)ptr - DOSMEM_dosmem) >> 4;
597
598        if( !(dm->size & (DM_BLOCK_FREE | DM_BLOCK_TERMINAL))
599          )
600        {
601              dosmem_entry  *next = NEXT_BLOCK(dm);
602              UINT blocksize, orgsize = dm->size & DM_BLOCK_MASK;
603
604              while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
605              {
606                  dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
607                  next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
608                  next = NEXT_BLOCK(dm);
609              }
610
611              blocksize = dm->size & DM_BLOCK_MASK;
612              if (blocksize >= size)
613              {
614                  block = ((char*)dm) + sizeof(dosmem_entry);
615                  if( blocksize - size > 0x20 )
616                  {
617                      /* split dm so that the next one stays
618                       * paragraph-aligned (and next gains free bit) */
619
620                      dm->size = (((size + 0xf + sizeof(dosmem_entry)) & ~0xf) -
621                                                 sizeof(dosmem_entry));
622                      next = (dosmem_entry*)(((char*)dm) +
623                              sizeof(dosmem_entry) + dm->size);
624                      next->size = (blocksize - (dm->size +
625                              sizeof(dosmem_entry))) | DM_BLOCK_FREE
626                                                     ;
627                  } else dm->size &= DM_BLOCK_MASK;
628
629                  info_block->free += orgsize - dm->size;
630              } else {
631                  /* the collapse didn't help, try getting a new block */
632                  block = DOSMEM_GetBlock(size, pseg);
633                  if (block) {
634                      /* we got one, copy the old data there (we do need to, right?) */
635                      memcpy(block, ((char*)dm) + sizeof(dosmem_entry),
636                                    (size<orgsize) ? size : orgsize);
637                      /* free old block */
638                      info_block->blocks--;
639                      info_block->free += dm->size;
640
641                      dm->size |= DM_BLOCK_FREE;
642                  } else {
643                      /* and Bill Gates said 640K should be enough for everyone... */
644
645                      /* need to split original and collapsed blocks apart again,
646                       * and free the collapsed blocks again, before exiting */
647                      if( blocksize - orgsize > 0x20 )
648                      {
649                          /* split dm so that the next one stays
650                           * paragraph-aligned (and next gains free bit) */
651
652                          dm->size = (((orgsize + 0xf + sizeof(dosmem_entry)) & ~0xf) -
653                                                        sizeof(dosmem_entry));
654                          next = (dosmem_entry*)(((char*)dm) +
655                                  sizeof(dosmem_entry) + dm->size);
656                          next->size = (blocksize - (dm->size +
657                                  sizeof(dosmem_entry))) | DM_BLOCK_FREE
658                                                         ;
659                      } else dm->size &= DM_BLOCK_MASK;
660                  }
661              }
662        }
663    }
664    return (LPVOID)block;
665 }
666
667
668 /***********************************************************************
669  *           DOSMEM_Available
670  */
671 UINT DOSMEM_Available(void)
672 {
673    UINT          blocksize, available = 0;
674    dosmem_entry *dm;
675
676    dm = DOSMEM_RootBlock();
677
678    while (dm && dm->size != DM_BLOCK_TERMINAL)
679    {
680 #ifdef __DOSMEM_DEBUG__
681        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
682        {
683             WARN("MCB overrun! [prev = 0x%08x]\n", 4 + (UINT)prev);
684             return NULL;
685        }
686        prev = dm;
687 #endif
688        if( dm->size & DM_BLOCK_FREE )
689        {
690            dosmem_entry  *next = NEXT_BLOCK(dm);
691
692            while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
693            {
694                dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
695                next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
696                next = NEXT_BLOCK(dm);
697            }
698
699            blocksize = dm->size & DM_BLOCK_MASK;
700            if ( blocksize > available ) available = blocksize;
701            dm = next;
702        }
703        else dm = NEXT_BLOCK(dm);
704    }
705    return available;
706 }
707
708
709 /***********************************************************************
710  *           DOSMEM_MapLinearToDos
711  *
712  * Linear address to the DOS address space.
713  */
714 UINT DOSMEM_MapLinearToDos(LPVOID ptr)
715 {
716     if (((char*)ptr >= DOSMEM_dosmem) &&
717         ((char*)ptr < DOSMEM_dosmem + 0x100000))
718           return (UINT)ptr - (UINT)DOSMEM_dosmem;
719     return (UINT)ptr;
720 }
721
722
723 /***********************************************************************
724  *           DOSMEM_MapDosToLinear
725  *
726  * DOS linear address to the linear address space.
727  */
728 LPVOID DOSMEM_MapDosToLinear(UINT ptr)
729 {
730     if (ptr < 0x100000) return (LPVOID)(ptr + (UINT)DOSMEM_dosmem);
731     return (LPVOID)ptr;
732 }
733
734
735 /***********************************************************************
736  *           DOSMEM_MapRealToLinear
737  *
738  * Real mode DOS address into a linear pointer
739  */
740 LPVOID DOSMEM_MapRealToLinear(DWORD x)
741 {
742    LPVOID       lin;
743
744    lin=DOSMEM_dosmem+(x&0xffff)+(((x&0xffff0000)>>16)*16);
745    TRACE_(selector)("(0x%08lx) returns %p.\n", x, lin );
746    return lin;
747 }
748
749 /***********************************************************************
750  *           DOSMEM_AllocSelector
751  *
752  * Allocates a protected mode selector for a realmode segment.
753  */
754 WORD DOSMEM_AllocSelector(WORD realsel)
755 {
756         HMODULE16 hModule = GetModuleHandle16("KERNEL");
757         WORD    sel;
758
759         sel=GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_dosmem+realsel*16, 0x10000,
760                                 hModule, WINE_LDT_FLAGS_DATA );
761         TRACE_(selector)("(0x%04x) returns 0x%04x.\n", realsel,sel);
762         return sel;
763 }