]> 4ch.mooo.com Git - 16.git/blob - 16/16/16_mm.c
16_ca needs huge amounts of work and I should remember what needs to be done soon...
[16.git] / 16 / 16 / 16_mm.c
1 /* Catacomb Apocalypse Source Code
2  * Copyright (C) 1993-2014 Flat Rock Software
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 // NEWMM.C
20
21 /*
22 =============================================================================
23
24                         ID software memory manager
25                         --------------------------
26
27 Primary coder: John Carmack
28
29 RELIES ON
30 ---------
31 Quit (char *error) function
32
33
34 WORK TO DO
35 ----------
36 MM_SizePtr to change the size of a given pointer
37
38 Multiple purge levels utilized
39
40 EMS / XMS unmanaged routines
41
42 =============================================================================
43 */
44 /*
45
46 Open Watcom port by sparky4
47
48 */
49 #include "src/lib/16_mm.h"
50 #pragma hdrstop
51
52 #pragma warn -pro
53 #pragma warn -use
54
55 /*
56 =============================================================================
57
58                                                  GLOBAL VARIABLES
59
60 =============================================================================
61 */
62
63 void            (* beforesort) (void);
64 void            (* aftersort) (void);
65 void            (* XMSaddr) (void);             // far pointer to XMS driver
66
67 /*
68 =============================================================================
69
70                                                  LOCAL VARIABLES
71
72 =============================================================================
73 */
74
75 static  char *ParmStringsexmm[] = {"noems","noxms",""};
76
77 /*
78 ======================
79 =
80 = MML_CheckForEMS
81 =
82 = Routine from p36 of Extending DOS
83 =
84 =======================
85 */
86
87 boolean MML_CheckForEMS(void)
88 {
89         boolean emmcfems;
90         static char     emmname[] = "EMMXXXX0"; //fix by andrius4669
91 //              mov     dx,OFFSET emmname
92         __asm {
93                 //LEA   DX, emmname     //fix by andrius4669
94                 mov     dx,OFFSET emmname       //fix by andrius4669
95                 mov     ax,0x3d00
96                 int     0x21            // try to open EMMXXXX0 device
97                 jc      error
98
99                 mov     bx,ax
100                 mov     ax,0x4400
101
102                 int     0x21            // get device info
103                 jc      error
104
105                 and     dx,0x80
106                 jz      error
107
108                 mov     ax,0x4407
109
110                 int     0x21            // get status
111                 jc      error
112                 or      al,al
113                 jz      error
114
115                 mov     ah,0x3e
116                 int     0x21            // close handle
117                 jc      error
118                 //
119                 // EMS is good
120                 //
121                 mov     emmcfems,1
122                 jmp End
123                 error:
124                 //
125                 // EMS is bad
126                 //
127                 mov     emmcfems,0
128                 End:
129         }
130         return(emmcfems);
131 }
132
133
134 /*
135 ======================
136 =
137 = MML_SetupEMS
138 =
139 =======================
140 */
141
142 byte MML_SetupEMS(mminfo_t *mm)
143 {
144         byte    str[160];
145         byte    err;
146         boolean errorflag=false;
147
148         unsigned int EMSVer = 0;
149         //byte  EMS_status;
150         unsigned        totalEMSpages,freeEMSpages,EMSpageframe,EMSpagesmapped,EMShandle;
151         totalEMSpages = freeEMSpages = EMSpageframe = EMSpagesmapped = 0;
152
153         __asm
154                 {
155                 mov     ah,EMS_STATUS
156                 int     EMS_INT                                         // make sure EMS hardware is present
157                 or      ah,ah
158                 //mov   [EMS_status],ah
159                 jnz     error
160
161                 mov     ah,EMS_VERSION
162                 int     EMS_INT
163                 or      ah,ah
164                 jnz     error
165                 mov     [EMSVer],ax                             //      set EMSVer
166                 cmp     al,0x32                                         // only work on ems 3.2 or greater
167                 jb      error
168
169                 mov     ah,EMS_GETFRAME
170                 int     EMS_INT                                         // find the page frame address
171                 or      ah,ah
172                 jnz     error
173                 mov     [EMSpageframe],bx
174
175                 mov     ah,EMS_GETPAGES
176                 int     EMS_INT                                         // find out how much EMS is there
177                 or      ah,ah
178                 jnz     error
179                 mov     [totalEMSpages],dx
180                 mov     [freeEMSpages],bx
181                 or      bx,bx
182                 jz      noEMS                                           // no EMS at all to allocate
183                                                                                         //EXPAND DONG!!!!
184                 cmp     [EMSVer],0x40
185                 jb      low
186                 cmp     bx,[freeEMSpages]
187                 jle     getpages
188                 mov     bx,[freeEMSpages]
189                 jmp     getpages
190
191 low:
192                 cmp     bx,4
193                 jle     getpages                                        // there is only 1,2,3,or 4 pages
194                 mov     bx,4                                            // we can't use more than 4 pages
195
196 getpages:
197                 mov     [EMSpagesmapped],bx
198                 mov     ah,EMS_ALLOCPAGES                       // allocate up to 64k of EMS
199                 int     EMS_INT
200                 or      ah,ah
201                 jnz     error
202                 mov     [EMShandle],dx
203                 jmp End
204 error:
205                 mov     err,ah
206                 mov     errorflag,1
207                 jmp End
208 noEMS:
209 End:
210         }
211         if(errorflag==true)
212         {
213                 //err = CPURegs.h.ah;
214                 strcpy(str,"MM_SetupEMS: EMS error ");
215                 //itoa(err,str2,16);
216                 MM_EMSerr(&str, err);
217                 printf("%s\n",str);
218                 return err;
219         }
220         mm->totalEMSpages=totalEMSpages;
221         mm->freeEMSpages=freeEMSpages;
222         mm->EMSpageframe=EMSpageframe;
223         mm->EMSpagesmapped=EMSpagesmapped;
224         mm->EMShandle=EMShandle;
225         mm->EMSVer=EMSVer;
226         return 0;
227 }
228
229
230 /*
231 ======================
232 =
233 = MML_ShutdownEMS
234 =
235 =======================
236 */
237
238 void MML_ShutdownEMS(mminfo_t *mm)
239 {
240         boolean errorflag=false;
241         unsigned EMShandle=mm->EMShandle;
242
243         if(!EMShandle)
244                 return;
245         __asm
246         {
247                 mov     ah,EMS_FREEPAGES
248                 mov     dx,[EMShandle]
249                 int     EMS_INT
250                 or      ah,ah
251                 jz      ok
252                 mov     errorflag,1
253                 ok:
254         }
255         if(errorflag==true) printf("MML_ShutdownEMS: Error freeing EMS!\n");    //++++ add something
256 }
257
258 /*
259 ====================
260 =
261 = MM_MapEMS
262 =
263 = Maps the 64k of EMS used by memory manager into the page frame
264 = for general use.  This only needs to be called if you are keeping
265 = other things in EMS.
266 =
267 ====================
268 */
269
270 byte MM_MapEMS(mminfo_t *mm, mminfotype *mmi)
271 {
272         byte    str[160];
273         unsigned        EMShandle;
274         byte err;
275         boolean errorflag=false;
276         int     i;
277         EMShandle=mm->EMShandle;
278
279         for (i=0;i<4/*MAPPAGES*/;i++)
280         {
281                 __asm
282                 {
283                         mov     ah,EMS_MAPPAGE
284                         mov     bx,[i]                  // logical page
285                         mov     al,bl                   // physical page
286                         mov     dx,[EMShandle]  // handle
287                         int     EMS_INT
288                         or      ah,ah
289                         jnz     error
290                         jmp End
291                         error:
292                         mov     err,ah
293                         mov     errorflag,1
294                         End:
295                 }
296                 if(errorflag==true)
297                 {
298                         //err = CPURegs.h.ah;
299                         strcpy(str,"MM_MapEMS: EMS error ");
300                         //itoa(err,str2,16);
301                         MM_EMSerr(str, err);
302                         printf("%s\n",str);
303                         //printf("FACK! %x\n", err);
304                         return err;
305                 }
306         }
307         mmi->EMSmem = (i)*0x4000lu;
308         return 0;
309 }
310
311 byte MM_MapXEMS(mminfo_t *mm, mminfotype *mmi)
312 {
313 //SUB EMS.MapXPages (PhysicalStart, LogicalStart, NumPages, Handle)
314
315         //Maps up to 4 logical EMS pages to physical pages in the page frame, where:
316         //PhysicalStart = Physical page first logical page is mapped to
317         //LogicalStart  = First logical page to map
318         //NumPages      = Number of pages to map (1 to 4)
319         //Handle        = EMS handle logical pages are allocated to
320
321   /*//Create a buffer containing the page information
322 //  FOR x = 0 TO NumPages - 1
323 //    MapInfo$ = MapInfo$ + MKI$(LogicalStart + x) + MKI$(PhysicalStart + x)
324 //  NEXT*/
325
326 //  Regs.ax = 0x5000                           //Map the pages in the buffer
327 //  Regs.cx = NumPages                         //to the pageframe
328 //  Regs.dx = Handle
329 //  Regs.ds = VARSEG(MapInfo$)
330 //  Regs.si = SADD(MapInfo$)
331 //  InterruptX 0x67, Regs, Regs
332 //      EMS.Error = (Regs.ax AND 0xFF00&) \ 0x100  //Store the status code
333
334 //END SUB
335         byte    str[160];
336         byte err;
337         word    EMShandle;
338         boolean errorflag=false;
339         int     i;
340         EMShandle=mm->EMShandle;
341
342         if(mm->EMSVer<0x40)
343                 return 5;
344
345         for (i=0;i<MAPPAGES;i++)
346         {
347                 __asm
348                 {
349                         mov     ah,EMS_MAPXPAGE
350                         mov     cx,[i]                  // logical page
351                         mov     al,bl                   // physical page
352                         mov     dx,[EMShandle]  // handle
353                         int     EMS_INT
354                         or      ah,ah
355                         jnz     error
356                         jmp End
357                         error:
358                         mov     err,ah
359                         mov     errorflag,1
360                         End:
361                 }
362                 if(errorflag==true)
363                 {
364                         //err = CPURegs.h.ah;
365                         //strcpy(str,"MM_MapXEMS: EMS error 0x");
366                         strcpy(str,"MM_MapXEMS: EMS error ");
367                         //itoa(err,str2,16);
368                         MM_EMSerr(&str, err);
369                         printf("%s\n",str);
370                         //printf("%s%x\n",str, err);
371                         //printf("FACK! %x\n", err);
372                         return err;
373                 }
374         }
375         mmi->EMSmem = (i)*0x4000lu;
376         return 0;
377 }
378
379 //==========================================================================
380
381 /*
382 ======================
383 =
384 = MML_CheckForXMS
385 =
386 = Check for XMM driver
387 =
388 =======================
389 */
390
391 boolean MML_CheckForXMS(mminfo_t *mm)
392 {
393         boolean errorflag=false;
394         mm->numUMBs = 0;
395
396         __asm
397         {
398                 mov     ax,0x4300
399                 int     0x2f                            // query status of installed diver
400                 cmp     al,0x80
401                 je      good
402                 mov     errorflag,1
403                 good:
404         }
405         if(errorflag==true) return false;
406         else return true;
407 }
408
409
410 /*
411 ======================
412 =
413 = MML_SetupXMS
414 =
415 = Try to allocate all upper memory block
416 =
417 =======================
418 */
419
420 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
421 {
422         unsigned        base,size;
423
424 getmemory:
425         __asm
426         {
427                 mov     ax,0x4310
428                 int     0x2f
429                 mov     [WORD PTR XMSaddr],bx
430                 mov     [WORD PTR XMSaddr+2],es         // function pointer to XMS driver
431
432                 mov     ah,XMS_ALLOCUMB
433                 mov     dx,0xffff                                       // try for largest block possible
434                 //mov     ax,dx                                         // Set available Kbytes.
435                 call    [DWORD PTR XMSaddr]
436                 or      ax,ax
437                 jnz     gotone
438
439                 cmp     bl,0xb0                                         // error: smaller UMB is available
440                 jne     done;
441
442                 mov     ah,XMS_ALLOCUMB
443                 call    [DWORD PTR XMSaddr]             // DX holds largest available UMB
444                 or      ax,ax
445                 jz      done                                            // another error...
446
447 gotone:
448                 mov     [base],bx
449                 mov     [size],dx
450 done:
451         }
452         printf("base=%u ", base); printf("size=%u\n", size);
453         MML_UseSpace(base,size, mm);
454         mmi->XMSmem += size*16;
455         mm->UMBbase[mm->numUMBs] = base;
456         mm->numUMBs++;
457         if(mm->numUMBs < MAXUMBS)
458                 goto getmemory;
459 }
460
461
462 /*
463 ======================
464 =
465 = MML_ShutdownXMS
466 =
467 ======================
468 */
469
470 void MML_ShutdownXMS(mminfo_t *mm)
471 {
472         int     i;
473         unsigned        base;
474
475         for (i=0;i<mm->numUMBs;i++)
476         {
477                 base = mm->UMBbase[i];
478                 __asm
479                 {
480                         mov     ah,XMS_FREEUMB
481                         mov     dx,[base]
482                         call    [DWORD PTR XMSaddr]
483                 }
484         }
485 }
486
487 //==========================================================================
488
489 /*
490 ======================
491 =
492 = MML_UseSpace
493 =
494 = Marks a range of paragraphs as usable by the memory manager
495 = This is used to mark space for the near heap, far heap, ems page frame,
496 = and upper memory blocks
497 =
498 ======================
499 */
500
501 void MML_UseSpace(/*d*/word segstart, dword seglength, mminfo_t *mm)
502 {
503         mmblocktype huge *scan,huge *last;
504         word            segm;
505         dword   oldend;
506         dword           extra;
507
508         scan = last = mm->mmhead;
509         mm->mmrover = mm->mmhead;               // reset rover to start of memory
510
511 //
512 // search for the block that contains the range of segments
513 //
514         while(scan->start+scan->length < segstart)
515         {
516                 last = scan;
517                 scan = scan->next;
518         }
519
520         //find out how many blocks it spans!
521         if(seglength>0xffffu)
522         {
523 //              segm=seglength/0x4000u;
524                 segm=seglength/0xffffu;
525         }
526         else segm=1;
527
528         //++++emsver stuff!
529         if(segm>1/*extra>0xfffflu*/)
530         {
531                 /*__asm
532                 {
533                         push    ds
534                         mov     ax,ds
535                         inc             ax
536                         mov     ds,ax
537                 }*/
538
539
540 //MML_UseSpace(?segstart?, ?length?, mm);
541
542                 /*__asm
543                 {
544                         pop ds
545                 }*/
546                 //printf("MML_UseSpace: Segment spans two blocks!\n");
547         }
548
549 //
550 // take the given range out of the block
551 //
552         oldend = scan->start + scan->length;
553         extra = oldend - (segstart+seglength);
554 /*
555 printf("segm=%u ", segm);
556 printf("ex=%lu  ", extra);
557 printf("start+seglen=%lu        ", segstart+seglength);
558 printf("len=%u  ", scan->length);
559 printf("segsta=%x       ", segstart);
560 printf("seglen=%lu\n", seglength);
561 */
562 //segu:
563 //++++todo: linked list of segment!
564 //printf("segm=%lu\n", segm);
565         if(segstart == scan->start)
566         {
567                 last->next = scan->next;                        // unlink block
568                 MM_FreeBlock(scan, mm);
569                 scan = last;
570         }
571         else
572                 scan->length = segstart-scan->start;    // shorten block
573
574 //      segm--;
575
576         if(extra > 0)
577         {
578                 MM_GetNewBlock(mm);
579                 mm->mmnew->next = scan->next;
580                 scan->next = mm->mmnew;
581                 mm->mmnew->start = segstart+seglength;
582                 mm->mmnew->length = extra;
583                 mm->mmnew->attributes = LOCKBIT;
584         }//else if(segm>0) goto segu;
585
586 }
587
588 //==========================================================================
589
590 /*
591 ====================
592 =
593 = MML_ClearBlock
594 =
595 = We are out of blocks, so free a purgable block
596 =
597 ====================
598 */
599
600 void MML_ClearBlock(mminfo_t *mm)
601 {
602         mmblocktype huge *scan,huge *last;
603
604         scan = mm->mmhead->next;
605
606         while(scan)
607         {
608                 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
609                 {
610                         MM_FreePtr(scan->useptr, mm);
611                         return;
612                 }
613                 scan = scan->next;
614         }
615
616         printf("MM_ClearBlock: No purgable blocks!\n");
617 }
618
619
620 //==========================================================================
621
622 /*
623 ===================
624 =
625 = MM_Startup
626 =
627 = Grabs all space from turbo with malloc/farmalloc
628 = Allocates bufferseg misc buffer
629 =
630 ===================
631 */
632
633 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
634 {
635         int i;
636         dword length,seglength;
637         //dword length; word seglength;
638         void huge       *start;
639         word    segstart;//,endfree;
640
641         if(mm->mmstarted)
642                 MM_Shutdown(mm);
643
644         mm->mmstarted = true;
645         mm->bombonerror = true;
646
647 //
648 // set up the linked list (everything in the free list;
649 //
650         //printf("              linked list making!\n");
651         mm->mmhead = NULL;
652         mm->mmfree = &(mm->mmblocks[0]);
653         for(i=0;i<MAXBLOCKS-1;i++)
654         {
655                 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
656         }
657         mm->mmblocks[i].next = NULL;
658
659 //
660 // locked block of all memory until we punch out free space
661 //
662         //printf("              newblock making!\n");
663         MM_GetNewBlock(mm);
664         mm->mmhead = mm->mmnew;                         // this will allways be the first node
665         mm->mmnew->start = 0;
666         mm->mmnew->length = 0xffff;
667         mm->mmnew->attributes = LOCKBIT;
668         mm->mmnew->next = NULL;
669         mm->mmrover = mm->mmhead;
670
671 //
672 // get all available near conventional memory segments
673 //
674 //----  length=coreleft();
675         printf("                nearheap making!\n");
676         _nheapgrow();
677         length=(dword)_memavl();//(dword)GetFreeSize();
678         start = (void huge *)(mm->nearheap = _nmalloc(length));
679         length -= 16-(FP_OFF(start)&15);
680         length -= SAVENEARHEAP;
681         seglength = length / 16;                        // now in paragraphs
682         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
683         MML_UseSpace(segstart,seglength, mm);
684         mmi->nearheap = length;
685         printf("start=%FP       segstart=%X     seglen=%lu      len=%lu\n", start, segstart, seglength, length);
686         //heapdump();
687         //getch();
688
689 //
690 // get all available far conventional memory segments
691 //
692 //----  length=farcoreleft();
693         printf("                farheap making!\n");
694         _fheapgrow();
695         length=(dword)GetFarFreeSize();//0xffffUL*4UL;
696         //start = mm->farheap = halloc(length, 1);
697         start = mm->farheap = _fmalloc(length);
698         length -= 16-(FP_OFF(start)&15);
699         length -= SAVEFARHEAP;
700         seglength = length / 16;                        // now in paragraphs
701         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
702         MML_UseSpace(segstart,seglength, mm);
703         mmi->farheap = length;
704         printf("start=%FP       segstart=%X     seglen=%lu      len=%lu\n", start, segstart, seglength, length);
705         //heapdump();
706
707         mmi->mainmem = mmi->nearheap + mmi->farheap;
708
709         getch();
710
711 //goto xmsskip;
712
713 //
714 // detect EMS and allocate up to 64K at page frame
715 //
716 //printf("              EMS1\n");
717 //printf("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");   //bug!
718         mmi->EMSmem = 0;
719         for(i = 1;i < __argc;i++)
720         {
721                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
722                         goto emsskip;                           // param NOEMS
723         }
724 //printf("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");   //bug!
725         if(MML_CheckForEMS())
726         {
727 //printf("              EMS2\n");
728 //printf("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");   //bug!
729                 MML_SetupEMS(mm);                                       // allocate space
730 //printf("              EMS3\n");
731 //printf("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");   //bug!
732                 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
733                 MML_UseSpace(mm->EMSpageframe,(MAPPAGES)*0x4000lu, mm);
734 //printf("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");   //bug!
735 //printf("              EMS4\n");
736                 //if(mm->EMSVer<0x40)
737                         MM_MapEMS(mm, mmi);                                     // map in used pages
738                 //else
739                         //MM_MapXEMS(mm, mmi);                                  // map in used pages
740         }
741
742 mmi->XMSmem=0;
743 goto xmsskip;
744
745 //
746 // detect XMS and get upper memory blocks
747 //
748 emsskip:
749         mmi->XMSmem = 0;
750         for(i = 1;i < __argc;i++)
751         {
752                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
753                         goto xmsskip;                           // param NOXMS
754         }
755 //printf("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");   //bug!
756         if(MML_CheckForXMS(mm))
757         {
758 //printf("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");   //bug!
759 //printf("              XMS!\n");
760                 MML_SetupXMS(mm, mmi);                                  // allocate as many UMBs as possible
761         }
762
763 //
764 // allocate the misc buffer
765 //
766 xmsskip:
767         mm->mmrover = mm->mmhead;               // start looking for space after low block
768
769         MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
770 }
771
772 //==========================================================================
773
774 /*
775 ====================
776 =
777 = MM_Shutdown
778 =
779 = Frees all conventional, EMS, and XMS allocated
780 =
781 ====================
782 */
783
784 void MM_Shutdown(mminfo_t *mm)
785 {
786         if(!(mm->mmstarted))
787                 return;
788
789         _ffree(mm->farheap);    printf("                far freed\n");
790         _nfree(mm->nearheap);   printf("                near freed\n");
791         if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("            EMS freed\n"); }
792         if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("          XMS freed\n"); }
793 }
794
795 //==========================================================================
796
797 /*
798 ====================
799 =
800 = MM_GetPtr
801 =
802 = Allocates an unlocked, unpurgable block
803 =
804 ====================
805 */
806
807 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
808 {
809         mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
810         int                     search;
811         unsigned        needed,startseg;
812
813         needed = (size+15)/16;          // convert size from bytes to paragraphs
814
815         MM_GetNewBlock(mm);                             // fill in start and next after a spot is found
816         mm->mmnew->length = needed;
817         mm->mmnew->useptr = baseptr;
818         mm->mmnew->attributes = BASEATTRIBUTES;
819
820         for(search = 0; search<3; search++)
821         {
822         //
823         // first search:        try to allocate right after the rover, then on up
824         // second search:       search from the head pointer up to the rover
825         // third search:        compress memory, then scan from start
826                 if(search == 1 && mm->mmrover == mm->mmhead)
827                         search++;
828
829                 switch(search)
830                 {
831                 case 0:
832                         lastscan = mm->mmrover;
833                         scan = mm->mmrover->next;
834                         endscan = NULL;
835                         break;
836                 case 1:
837                         lastscan = mm->mmhead;
838                         scan = mm->mmhead->next;
839                         endscan = mm->mmrover;
840                         break;
841                 case 2:
842                         MM_SortMem(mm);
843                         lastscan = mm->mmhead;
844                         scan = mm->mmhead->next;
845                         endscan = NULL;
846                         break;
847                 }
848
849                 startseg = lastscan->start + lastscan->length;
850
851                 while(scan != endscan)
852                 {
853                         if(scan->start - startseg >= needed)
854                         {
855                         //
856                         // got enough space between the end of lastscan and
857                         // the start of scan, so throw out anything in the middle
858                         // and allocate the new block
859                         //
860                                 purge = lastscan->next;
861                                 lastscan->next = mm->mmnew;
862                                 mm->mmnew->start = *(unsigned *)baseptr = startseg;
863                                 mm->mmnew->next = scan;
864                                 while(purge != scan)
865                                 {       // free the purgable block
866                                         next = purge->next;
867                                         MM_FreeBlock(purge, mm);
868                                         purge = next;           // purge another if not at scan
869                                 }
870                                 mm->mmrover = mm->mmnew;
871                                 return; // good allocation!
872                         }
873
874                         //
875                         // if this block is purge level zero or locked, skip past it
876                         //
877                         if((scan->attributes & LOCKBIT)
878                                 || !(scan->attributes & PURGEBITS) )
879                         {
880                                 lastscan = scan;
881                                 startseg = lastscan->start + lastscan->length;
882                         }
883
884
885                         scan=scan->next;                // look at next line
886                 }
887         }
888
889         if (mm->bombonerror)
890         {
891                 heapdump();
892                 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
893                 printf("for stability reasons the program will shut down! wwww\n");
894                 MM_Shutdown(mm);
895                 exit(-1);
896         }
897         else
898                 mm->mmerror = true;
899 }
900
901 //==========================================================================
902
903 /*
904 ====================
905 =
906 = MM_FreePtr
907 =
908 = Allocates an unlocked, unpurgable block
909 =
910 ====================
911 */
912
913 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
914 {
915         mmblocktype huge *scan,huge *last;
916
917         last = mm->mmhead;
918         scan = last->next;
919
920         if(baseptr == mm->mmrover->useptr)      // removed the last allocated block
921                 mm->mmrover = mm->mmhead;
922
923         while(scan->useptr != baseptr && scan)
924         {
925                 last = scan;
926                 scan = scan->next;
927         }
928
929         if(!scan)
930         {
931                 printf("MM_FreePtr: Block not found!\n");
932                 return;
933         }
934
935         last->next = scan->next;
936
937         MM_FreeBlock(scan, mm);
938 }
939 //==========================================================================
940
941 /*
942 =====================
943 =
944 = MM_SetPurge
945 =
946 = Sets the purge level for a block (locked blocks cannot be made purgable)
947 =
948 =====================
949 */
950
951 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
952 {
953         mmblocktype huge *start;
954
955         start = mm->mmrover;
956
957         do
958         {
959                 if(mm->mmrover->useptr == baseptr)
960                         break;
961
962                 mm->mmrover = mm->mmrover->next;
963
964                 if(!mm->mmrover)
965                         mm->mmrover = mm->mmhead;
966                 else if(mm->mmrover == start)
967                 {
968                         printf("MM_SetPurge: Block not found!");
969                         return;
970                 }
971
972         } while(1);
973
974         mm->mmrover->attributes &= ~PURGEBITS;
975         mm->mmrover->attributes |= purge;
976 }
977
978 //==========================================================================
979
980 /*
981 =====================
982 =
983 = MM_SetLock
984 =
985 = Locks / unlocks the block
986 =
987 =====================
988 */
989
990 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
991 {
992         mmblocktype huge *start;
993
994         start = mm->mmrover;
995
996         do
997         {
998                 if(mm->mmrover->useptr == baseptr)
999                         break;
1000
1001                 mm->mmrover = mm->mmrover->next;
1002
1003                 if(!mm->mmrover)
1004                         mm->mmrover = mm->mmhead;
1005                 else if(mm->mmrover == start)
1006                 {
1007                         printf("MM_SetLock: Block not found!");
1008                         return;
1009                 }
1010
1011         } while(1);
1012
1013         mm->mmrover->attributes &= ~LOCKBIT;
1014         mm->mmrover->attributes |= locked*LOCKBIT;
1015 }
1016
1017 //==========================================================================
1018
1019 /*
1020 =====================
1021 =
1022 = MM_SortMem
1023 =
1024 = Throws out all purgable stuff and compresses movable blocks
1025 =
1026 =====================
1027 */
1028
1029 void MM_SortMem(mminfo_t *mm)
1030 {
1031         mmblocktype huge *scan,huge *last,huge *next;
1032         unsigned        start,length,source,dest,oldborder;
1033         int                     playing;
1034
1035         //
1036         // lock down a currently playing sound
1037         //
1038 /*++++  playing = SD_SoundPlaying ();
1039         if(playing)
1040         {
1041                 switch (SoundMode)
1042                 {
1043                 case sdm_PC:
1044                         playing += STARTPCSOUNDS;
1045                         break;
1046                 case sdm_AdLib:
1047                         playing += STARTADLIBSOUNDS;
1048                         break;
1049                 }
1050                 MM_SetLock(&(memptr)audiosegs[playing],true);
1051         }
1052
1053
1054         SD_StopSound();*/
1055 //      oldborder = bordercolor;
1056 //      VW_ColorBorder (15);
1057
1058         if(beforesort)
1059                 beforesort();
1060
1061         scan = mm->mmhead;
1062
1063         last = NULL;            // shut up compiler warning
1064
1065         while(scan)
1066         {
1067                 if(scan->attributes & LOCKBIT)
1068                 {
1069                 //
1070                 // block is locked, so try to pile later blocks right after it
1071                 //
1072                         start = scan->start + scan->length;
1073                 }
1074                 else
1075                 {
1076                         if(scan->attributes & PURGEBITS)
1077                         {
1078                         //
1079                         // throw out the purgable block
1080                         //
1081                                 next = scan->next;
1082                                 MM_FreeBlock(scan, mm);
1083                                 last->next = next;
1084                                 scan = next;
1085                                 continue;
1086                         }
1087                         else
1088                         {
1089                         //
1090                         // push the non purgable block on top of the last moved block
1091                         //
1092                                 if(scan->start != start)
1093                                 {
1094                                         length = scan->length;
1095                                         source = scan->start;
1096                                         dest = start;
1097                                         while(length > 0xf00)
1098                                         {
1099                                                 movedata(source,0,dest,0,0xf00*16);
1100                                                 length -= 0xf00;
1101                                                 source += 0xf00;
1102                                                 dest += 0xf00;
1103                                         }
1104                                         movedata(source,0,dest,0,length*16);
1105
1106                                         scan->start = start;
1107                                         *(unsigned *)scan->useptr = start;
1108                                 }
1109                                 start = scan->start + scan->length;
1110                         }
1111                 }
1112
1113                 last = scan;
1114                 scan = scan->next;              // go to next block
1115         }
1116
1117         mm->mmrover = mm->mmhead;
1118
1119         if(aftersort)
1120                 aftersort();
1121
1122 //      VW_ColorBorder (oldborder);
1123
1124 /*++++  if(playing)
1125                 MM_SetLock(&(memptr)audiosegs[playing],false);*/
1126 }
1127
1128
1129 //==========================================================================
1130
1131 //****#if 0
1132 /*
1133 =====================
1134 =
1135 = MM_ShowMemory
1136 =
1137 =====================
1138 */
1139
1140 void MM_ShowMemory(/*page_t *page, */mminfo_t *mm)
1141 {
1142         mmblocktype huge *scan;
1143         word color,temp;
1144         long    end,owner;
1145         word chx,chy;
1146         byte    scratch[160],str[16];
1147
1148 //****  VW_SetDefaultColors();
1149 //****  VW_SetLineWidth(40);
1150 //++++mh        temp = bufferofs;
1151 //++++mh        bufferofs = 0;
1152 //****  VW_SetScreen (0,0);
1153
1154         scan = mm->mmhead;
1155
1156         end = -1;
1157
1158 CA_OpenDebug ();
1159
1160         chx=0;
1161         chy=0;
1162
1163         while(scan)
1164         {
1165                 if(scan->attributes & PURGEBITS)
1166                         color = 5;              // dark purple = purgable
1167                 else
1168                         color = 9;              // medium blue = non purgable
1169                 if(scan->attributes & LOCKBIT)
1170                         color = 12;             // red = locked
1171                 if(scan->start<=end)
1172                 {
1173                         //printf(");
1174                         write(debughandle,"\nMM_ShowMemory: Memory block order currupted!\n",strlen("\nMM_ShowMemory: Memory block order currupted!\n"));
1175                         //modexprint(&page, chx, chy, 1, 0, 24, "\nMM_ShowMemory: Memory block order currupted!\n");
1176                         return;
1177                 }
1178                 end = scan->start+scan->length-1;
1179                 chy = scan->start/320;
1180                 chx = scan->start%320;
1181                                 //modexhlin(page, scan->start, (unsigned)end, chy, color);
1182                                 //for(chx=scan->start;chx+4>=(word)end;chx+=4)
1183                                 //{
1184 //++++                                  modexClearRegion(page, chx, chy, 4, 4, color);
1185                                 //}
1186
1187 //++++          VW_Hlin(scan->start,(unsigned)end,0,color);
1188
1189 //++++          VW_Plot(scan->start,0,15);
1190 //++++                          modexClearRegion(page, chx, chy, 4, 4, 15);
1191                 if(scan->next->start > end+1)
1192 //++++                  VW_Hlin(end+1,scan->next->start,0,0);   // black = free
1193                         //for(chx=scan->next->start;chx+4>=(word)end+1;chx+=4)
1194                         //{
1195 //++++                          chx+=scan->next->start;
1196 //++++                          modexClearRegion(page, chx, chy, 4, 4, 2);
1197                         //}
1198                                         //modexhlin(page, end+1,scan->next->start, chy, 0);
1199
1200 /*
1201                 end = scan->length-1;
1202                 y = scan->start/320;
1203                 x = scan->start%320;
1204                 VW_Hlin(x,x+end,y,color);
1205                 VW_Plot(x,y,15);
1206                 if (scan->next && scan->next->start > end+1)
1207                         VW_Hlin(x+end+1,x+(scan->next->start-scan->start),y,0); // black = free
1208 */
1209
1210 //****#if 0
1211 printf("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");     //bug!
1212 strcpy(scratch,"Seg:");
1213 ultoa (scan->start,str,16);
1214 strcat (scratch,str);
1215 strcat (scratch,"\tSize:");
1216 ultoa ((dword)scan->length,str,10);
1217 strcat (scratch,str);
1218 strcat (scratch,"\tOwner:0x");
1219 owner = (unsigned)scan->useptr;
1220 ultoa (owner,str,16);
1221 strcat (scratch,str);
1222 strcat (scratch,"\n");
1223 write(debughandle,scratch,strlen(scratch));
1224 //modexprint(page, chx, chy, 1, 0, 24, &scratch);
1225 //++++chy+=4;
1226 //fprintf(stdout, "%s", scratch);
1227 //****#endif
1228
1229                 scan = scan->next;
1230         }
1231
1232 CA_CloseDebug ();
1233
1234 //++++mh        IN_Ack();
1235 //****  VW_SetLineWidth(64);
1236 //++++mh        bufferofs = temp;
1237 }
1238 //****#endif
1239
1240 //==========================================================================
1241
1242 /*
1243 =====================
1244 =
1245 = MM_DumpData
1246 =
1247 =====================
1248 */
1249
1250 void MM_DumpData(mminfo_t *mm)
1251 {
1252         mmblocktype far *scan,far *best;
1253         long    lowest,oldlowest;
1254         word    owner;
1255         byte    lock,purge;
1256         FILE    *dumpfile;
1257
1258
1259         //++++free(mm->nearheap);
1260         dumpfile = fopen ("mmdump.16","w");
1261         if (!dumpfile){
1262                 printf("MM_DumpData: Couldn't open MMDUMP.16!\n");
1263                 return;
1264         }
1265
1266         lowest = -1;
1267         do
1268         {
1269                 oldlowest = lowest;
1270                 lowest = 0xffff;
1271
1272                 scan = mm->mmhead;
1273                 while (scan)
1274                 {
1275                         owner = (word)scan->useptr;
1276
1277                         if (owner && owner<lowest && owner > oldlowest)
1278                         {
1279                                 best = scan;
1280                                 lowest = owner;
1281                         }
1282
1283                         scan = scan->next;
1284                 }
1285
1286                 if (lowest != 0xffff)
1287                 {
1288                         if (best->attributes & PURGEBITS)
1289                                 purge = 'P';
1290                         else
1291                                 purge = '-';
1292                         if (best->attributes & LOCKBIT)
1293                                 lock = 'L';
1294                         else
1295                                 lock = '-';
1296                         fprintf (dumpfile,"0x%p (%c%c) = %u\n"
1297                         ,(word)lowest,lock,purge,best->length);
1298                 }
1299
1300         } while (lowest != 0xffff);
1301
1302         fclose(dumpfile);
1303         printf("MMDUMP.16 created.\n");
1304 }
1305
1306 //==========================================================================
1307
1308
1309 /*
1310 ======================
1311 =
1312 = MM_UnusedMemory
1313 =
1314 = Returns the total free space without purging
1315 =
1316 ======================
1317 */
1318
1319 dword MM_UnusedMemory(mminfo_t *mm)
1320 {
1321         dword free;
1322         mmblocktype huge *scan;
1323
1324         free = 0;
1325         scan = mm->mmhead;
1326
1327         while(scan->next)
1328         {
1329                 free += scan->next->start - (scan->start + scan->length);
1330                 scan = scan->next;
1331         }
1332
1333 //      return free*16l;
1334         return free;
1335 }
1336
1337 //==========================================================================
1338
1339
1340 /*
1341 ======================
1342 =
1343 = MM_TotalFree
1344 =
1345 = Returns the total free space with purging
1346 =
1347 ======================
1348 */
1349
1350 dword MM_TotalFree(mminfo_t *mm)
1351 {
1352         dword free;
1353         mmblocktype huge *scan;
1354
1355         free = 0;
1356         scan = mm->mmhead;
1357
1358         while(scan->next)
1359         {
1360                 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1361                         free += scan->length;
1362                 free += scan->next->start - (scan->start + scan->length);
1363                 scan = scan->next;
1364         }
1365
1366 //      return free*16l;
1367         return free;
1368 }
1369
1370 //==========================================================================
1371
1372 /*
1373 =====================
1374 =
1375 = MM_Report
1376 =
1377 =====================
1378 */
1379
1380 void MM_Report(/*page_t *page, */mminfo_t *mm, mminfotype *mmi)
1381 {
1382         if(MML_CheckForEMS())
1383         {
1384                 printf("EMM v%x.%x available\n", mm->EMSVer>>4,mm->EMSVer&0x0F);
1385                 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1386                 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1387                 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1388         }
1389         if(MML_CheckForXMS(mm)) printf("XMSaddr=%X\n", *XMSaddr);
1390         printf("near=%lu\n", mmi->nearheap);
1391         printf("far=%lu\n", mmi->farheap);
1392         printf("EMSmem=%lu\n", mmi->EMSmem);
1393         printf("XMSmem=%lu\n", mmi->XMSmem);
1394         printf("mainmem=%lu\n", mmi->mainmem);
1395         printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1396         printf("TotalFree=%lu\n", MM_TotalFree(mm));
1397         //mmi->nearheap+mmi->farheap+
1398         printf("TotalUsed=%lu\n", mmi->mainmem+mmi->EMSmem+mmi->XMSmem);//+);
1399 //      printf("\n");
1400 //      printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1401 //      printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1402 }
1403
1404 //==========================================================================
1405
1406 /*
1407 =====================
1408 =
1409 = MM_EMSerr
1410 =
1411 =====================
1412 */
1413
1414 void MM_EMSerr(byte *stri, byte err)
1415 {
1416         //Returns a text string describing the error code in EMS.Error.
1417         switch(err)
1418         {
1419                 case 0x0:
1420                         strcat(stri, "successful");
1421                 break;
1422                 case 0x80:
1423                         strcat(stri, "internal error");
1424                 break;
1425                 case 0x81:
1426                         strcat(stri, "hardware malfunction");
1427                 break;
1428                 case 0x82:
1429                         strcat(stri, "busy .. retry later");
1430                 break;
1431                 case 0x83:
1432                         strcat(stri, "invalid handle");
1433                 break;
1434                 case 0x84:
1435                         strcat(stri, "undefined function requested by application");
1436                 break;
1437                 case 0x85:
1438                         strcat(stri, "no more handles available");
1439                 break;
1440                 case 0x86:
1441                         strcat(stri, "error in save or restore of mapping context");
1442                 break;
1443                 case 0x87:
1444                         strcat(stri, "insufficient memory pages in system");
1445                 break;
1446                 case 0x88:
1447                         strcat(stri, "insufficient memory pages available");
1448                 break;
1449                 case 0x89:
1450                         strcat(stri, "zero pages requested");
1451                 break;
1452                 case 0x8A:
1453                         strcat(stri, "invalid logical page number encountered");
1454                 break;
1455                 case 0x8B:
1456                         strcat(stri, "invalid physical page number encountered");
1457                 break;
1458                 case 0x8C:
1459                         strcat(stri, "page-mapping hardware state save area is full");
1460                 break;
1461                 case 0x8D:
1462                         strcat(stri, "save of mapping context failed");
1463                 break;
1464                 case 0x8E:
1465                         strcat(stri, "restore of mapping context failed");
1466                 break;
1467                 case 0x8F:
1468                         strcat(stri, "undefined subfunction");
1469                 break;
1470                 case 0x90:
1471                         strcat(stri, "undefined attribute type");
1472                 break;
1473                 case 0x91:
1474                         strcat(stri, "feature not supported");
1475                 break;
1476                 case 0x92:
1477                         strcat(stri, "successful, but a portion of the source region has been overwritten");
1478                 break;
1479                 case 0x93:
1480                         strcat(stri, "length of source or destination region exceeds length of region allocated to either source or destination handle");
1481                 break;
1482                 case 0x94:
1483                         strcat(stri, "conventional and expanded memory regions overlap");
1484                 break;
1485                 case 0x95:
1486                         strcat(stri, "offset within logical page exceeds size of logical page");
1487                 break;
1488                 case 0x96:
1489                         strcat(stri, "region length exceeds 1 MB");
1490                 break;
1491                 case 0x97:
1492                         strcat(stri, "source and destination EMS regions have same handle and overlap");
1493                 break;
1494                 case 0x98:
1495                         strcat(stri, "memory source or destination type undefined");
1496                 break;
1497                 case 0x9A:
1498                         strcat(stri, "specified alternate map register or DMA register set not supported");
1499                 break;
1500                 case 0x9B:
1501                         strcat(stri, "all alternate map register or DMA register sets currently allocated");
1502                 break;
1503                 case 0x9C:
1504                         strcat(stri, "alternate map register or DMA register sets not supported");
1505                 break;
1506                 case 0x9D:
1507                         strcat(stri, "undefined or unallocated alternate map register or DMA register set");
1508                 break;
1509                 case 0x9E:
1510                         strcat(stri, "dedicated DMA channels not supported");
1511                 break;
1512                 case 0x9F:
1513                         strcat(stri, "specified dedicated DMA channel not supported");
1514                 break;
1515                 case 0xA0:
1516                         strcat(stri, "no such handle name");
1517                 break;
1518                 case 0xA1:
1519                         strcat(stri, "a handle found had no name, or duplicate handle name");
1520                 break;
1521                 case 0xA2:
1522                         strcat(stri, "attempted to wrap around 1M conventional address space");
1523                 break;
1524                 case 0xA3:
1525                         strcat(stri, "source array corrupted");
1526                 break;
1527                 case 0xA4:
1528                         strcat(stri, "operating system denied access");
1529                 break;
1530                 default:
1531                         strcat(stri, "undefined error");
1532         }
1533 }
1534
1535 //==========================================================================
1536
1537 /*
1538 =====================
1539 =
1540 = MM_BombOnError
1541 =
1542 =====================
1543 */
1544
1545 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1546 {
1547         mm->bombonerror = bomb;
1548 }
1549
1550 void MM_GetNewBlock(mminfo_t *mm)
1551 {
1552         if(!mm->mmfree)
1553                 MML_ClearBlock(mm);
1554         mm->mmnew=mm->mmfree;
1555         mm->mmfree=mm->mmfree->next;
1556         if(!(mm->mmnew=mm->mmfree))
1557         {
1558                 printf("MM_GETNEWBLOCK: No free blocks!\n");
1559                 return;
1560         }
1561         mm->mmfree=mm->mmfree->next;
1562 }
1563
1564 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1565 {
1566         x->useptr=NULL;
1567         x->next=mm->mmfree;
1568         mm->mmfree=x;
1569 }
1570
1571 void MM_seguin(void)
1572 {
1573         __asm {
1574                 push    ds
1575                 mov     ax,ds
1576                 inc             ax
1577                 mov     ds,ax
1578         }
1579 }
1580
1581 void MM_segude(void)
1582 {
1583         __asm {
1584                 pop ds
1585         }
1586 }
1587
1588 /*
1589 pull data from far and put it into ds var
1590 mov ax,es:si
1591 mov x,ax
1592 */
1593 /*
1594 ss stack segment
1595 sp top of stack
1596 bp bottem of stack
1597 */