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