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