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