1 /* Reconstructed Commander Keen 4-6 Source Code
\r
2 * Copyright (C) 2021 K1n9_Duk3
\r
4 * This file is primarily based on:
\r
5 * Catacomb 3-D Source Code
\r
6 * Copyright (C) 1993-2014 Flat Rock Software
\r
8 * This program is free software; you can redistribute it and/or modify
\r
9 * it under the terms of the GNU General Public License as published by
\r
10 * the Free Software Foundation; either version 2 of the License, or
\r
11 * (at your option) any later version.
\r
13 * This program is distributed in the hope that it will be useful,
\r
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
16 * GNU General Public License for more details.
\r
18 * You should have received a copy of the GNU General Public License along
\r
19 * with this program; if not, write to the Free Software Foundation, Inc.,
\r
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
\r
26 =============================================================================
\r
28 ID software memory manager
\r
29 --------------------------
\r
31 Primary coder: John Carmack
\r
35 Quit (char *error) function
\r
40 MM_SizePtr to change the size of a given pointer
\r
42 Multiple purge levels utilized
\r
44 EMS / XMS unmanaged routines
\r
46 =============================================================================
\r
49 #include "ID_HEADS.H"
\r
56 =============================================================================
\r
60 =============================================================================
\r
63 #define LOCKBIT 0x80 // if set in attributes, block cannot be moved
\r
64 #define PURGEBITS 3 // 0-3 level, 0= unpurgable, 3= purge first
\r
65 #define PURGEMASK 0xfffc
\r
66 #define BASEATTRIBUTES 0 // unlocked, non purgable
\r
70 typedef struct mmblockstruct
\r
72 unsigned start,length;
\r
73 unsigned attributes;
\r
74 memptr *useptr; // pointer to the segment start
\r
75 struct mmblockstruct far *next;
\r
79 //#define GETNEWBLOCK {if(!(mmnew=mmfree))Quit("MM_GETNEWBLOCK: No free blocks!")\
\r
80 // ;mmfree=mmfree->next;}
\r
82 #define GETNEWBLOCK {if(!mmfree)MML_ClearBlock();mmnew=mmfree;mmfree=mmfree->next;}
\r
84 #define FREEBLOCK(x) {*x->useptr=NULL;x->next=mmfree;mmfree=x;}
\r
87 =============================================================================
\r
91 =============================================================================
\r
98 void (* beforesort) (void);
\r
99 void (* aftersort) (void);
\r
102 =============================================================================
\r
106 =============================================================================
\r
114 mmblocktype far mmblocks[MAXBLOCKS]
\r
115 ,far *mmhead,far *mmfree,far *mmrover,far *mmnew;
\r
117 boolean bombonerror;
\r
119 unsigned totalEMSpages,freeEMSpages,EMSpageframe,EMSpagesmapped,EMShandle;
\r
121 void (* XMSaddr) (void); // far pointer to XMS driver
\r
123 unsigned numUMBs,UMBbase[MAXUMBS];
\r
125 //==========================================================================
\r
128 // local prototypes
\r
131 boolean MML_CheckForEMS (void);
\r
132 void MML_ShutdownEMS (void);
\r
133 void MM_MapEMS (void);
\r
134 boolean MML_CheckForXMS (void);
\r
135 void MML_ShutdownXMS (void);
\r
136 void MML_UseSpace (unsigned segstart, unsigned seglength);
\r
137 void MML_ClearBlock (void);
\r
139 //==========================================================================
\r
142 ======================
\r
146 = Routine from p36 of Extending DOS
\r
148 =======================
\r
151 char emmname[9] = "EMMXXXX0";
\r
153 boolean MML_CheckForEMS (void)
\r
155 asm mov dx,OFFSET emmname[0]
\r
157 asm int 0x21 // try to open EMMXXXX0 device
\r
163 asm int 0x21 // get device info
\r
171 asm int 0x21 // get status
\r
177 asm int 0x21 // close handle
\r
194 ======================
\r
198 =======================
\r
201 void MML_SetupEMS (void)
\r
203 char str[80],str2[10];
\r
206 totalEMSpages = freeEMSpages = EMSpageframe = EMSpagesmapped = 0;
\r
210 int EMS_INT // make sure EMS hardware is present
\r
218 cmp al,0x32 // only work on ems 3.2 or greater
\r
221 mov ah,EMS_GETFRAME
\r
222 int EMS_INT // find the page frame address
\r
225 mov [EMSpageframe],bx
\r
227 mov ah,EMS_GETPAGES
\r
228 int EMS_INT // find out how much EMS is there
\r
231 mov [totalEMSpages],dx
\r
232 mov [freeEMSpages],bx
\r
234 jz noEMS // no EMS at all to allocate
\r
237 jle getpages // there is only 1,2,3,or 4 pages
\r
238 mov bx,4 // we can't use more than 4 pages
\r
243 mov [EMSpagesmapped],bx
\r
244 mov ah,EMS_ALLOCPAGES // allocate up to 64k of EMS
\r
254 strcpy (str,"MML_SetupEMS: EMS error 0x");
\r
255 itoa(error,str2,16);
\r
265 ======================
\r
269 =======================
\r
272 void MML_ShutdownEMS (void)
\r
278 mov ah,EMS_FREEPAGES
\r
285 Quit ("MML_ShutdownEMS: Error freeing EMS!");
\r
292 ====================
\r
296 = Maps the 64k of EMS used by memory manager into the page frame
\r
297 = for general use. This only needs to be called if you are keeping
\r
298 = other things in EMS.
\r
300 ====================
\r
303 void MM_MapEMS (void)
\r
305 char str[80],str2[10];
\r
309 for (i=0;i<EMSpagesmapped;i++)
\r
313 mov bx,[i] // logical page
\r
314 mov al,bl // physical page
\r
315 mov dx,[EMShandle] // handle
\r
326 strcpy (str,"MM_MapEMS: EMS error 0x");
\r
327 itoa(error,str2,16);
\r
332 //==========================================================================
\r
335 ======================
\r
339 = Check for XMM driver
\r
341 =======================
\r
344 boolean MML_CheckForXMS (void)
\r
350 int 0x2f // query status of installed diver
\r
361 ======================
\r
365 = Try to allocate all upper memory block
\r
367 =======================
\r
370 void MML_SetupXMS (void)
\r
372 unsigned base,size;
\r
377 mov [WORD PTR XMSaddr],bx
\r
378 mov [WORD PTR XMSaddr+2],es // function pointer to XMS driver
\r
383 mov ah,XMS_ALLOCUMB
\r
384 mov dx,0xffff // try for largest block possible
\r
385 call [DWORD PTR XMSaddr]
\r
389 cmp bl,0xb0 // error: smaller UMB is available
\r
392 mov ah,XMS_ALLOCUMB
\r
393 call [DWORD PTR XMSaddr] // DX holds largest available UMB
\r
395 jz done // another error...
\r
403 MML_UseSpace (base,size);
\r
404 mminfo.XMSmem += size*16;
\r
405 UMBbase[numUMBs] = base;
\r
407 if (numUMBs < MAXUMBS)
\r
415 ======================
\r
419 ======================
\r
422 void MML_ShutdownXMS (void)
\r
427 for (i=0;i<numUMBs;i++)
\r
431 asm mov ah,XMS_FREEUMB
\r
433 asm call [DWORD PTR XMSaddr]
\r
437 //==========================================================================
\r
440 ======================
\r
444 = Marks a range of paragraphs as usable by the memory manager
\r
445 = This is used to mark space for the near heap, far heap, ems page frame,
\r
446 = and upper memory blocks
\r
448 ======================
\r
451 void MML_UseSpace (unsigned segstart, unsigned seglength)
\r
453 mmblocktype far *scan,far *last;
\r
457 scan = last = mmhead;
\r
458 mmrover = mmhead; // reset rover to start of memory
\r
461 // search for the block that contains the range of segments
\r
463 while (scan->start+scan->length < segstart)
\r
470 // take the given range out of the block
\r
472 oldend = scan->start + scan->length;
\r
473 extra = oldend - (segstart+seglength);
\r
475 Quit ("MML_UseSpace: Segment spans two blocks!");
\r
477 if (segstart == scan->start)
\r
479 last->next = scan->next; // unlink block
\r
484 scan->length = segstart-scan->start; // shorten block
\r
489 mmnew->useptr = NULL; // Keen addition
\r
491 mmnew->next = scan->next;
\r
492 scan->next = mmnew;
\r
493 mmnew->start = segstart+seglength;
\r
494 mmnew->length = extra;
\r
495 mmnew->attributes = LOCKBIT;
\r
500 //==========================================================================
\r
503 ====================
\r
507 = We are out of blocks, so free a purgable block
\r
509 ====================
\r
512 void MML_ClearBlock (void)
\r
514 mmblocktype far *scan,far *last;
\r
516 scan = mmhead->next;
\r
520 if (!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS) )
\r
522 MM_FreePtr(scan->useptr);
\r
528 Quit ("MM_ClearBlock: No purgable blocks!");
\r
532 //==========================================================================
\r
535 ===================
\r
539 = Grabs all space from turbo with malloc/farmalloc
\r
540 = Allocates bufferseg misc buffer
\r
542 ===================
\r
545 static char *ParmStrings[] = {"noems","noxms",""};
\r
547 void MM_Startup (void)
\r
550 unsigned long length;
\r
552 unsigned segstart,seglength,endfree;
\r
559 bombonerror = true;
\r
561 // set up the linked list (everything in the free list;
\r
564 mmfree = &mmblocks[0];
\r
565 for (i=0;i<MAXBLOCKS-1;i++)
\r
566 mmblocks[i].next = &mmblocks[i+1];
\r
567 mmblocks[i].next = NULL;
\r
570 // locked block of all memory until we punch out free space
\r
573 mmhead = mmnew; // this will allways be the first node
\r
575 mmnew->length = 0xffff;
\r
576 mmnew->attributes = LOCKBIT;
\r
577 mmnew->next = NULL;
\r
582 // get all available near conventional memory segments
\r
585 start = (void far *)(nearheap = malloc(length));
\r
587 length -= 16-(FP_OFF(start)&15);
\r
588 length -= SAVENEARHEAP;
\r
589 seglength = length / 16; // now in paragraphs
\r
590 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
\r
591 MML_UseSpace (segstart,seglength);
\r
592 mminfo.nearheap = length;
\r
595 // get all available far conventional memory segments
\r
597 length=farcoreleft();
\r
598 start = farheap = farmalloc(length);
\r
599 length -= 16-(FP_OFF(start)&15);
\r
600 length -= SAVEFARHEAP;
\r
601 seglength = length / 16; // now in paragraphs
\r
602 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
\r
603 MML_UseSpace (segstart,seglength);
\r
604 mminfo.farheap = length;
\r
605 mminfo.mainmem = mminfo.nearheap + mminfo.farheap;
\r
609 // detect EMS and allocate up to 64K at page frame
\r
612 for (i = 1;i < _argc;i++)
\r
614 if ( US_CheckParm(_argv[i],ParmStrings) == 0)
\r
615 goto emsskip; // param NOEMS
\r
618 if (MML_CheckForEMS())
\r
620 MML_SetupEMS(); // allocate space
\r
621 MML_UseSpace (EMSpageframe,EMSpagesmapped*0x400);
\r
622 MM_MapEMS(); // map in used pages
\r
623 mminfo.EMSmem = EMSpagesmapped*0x4000l;
\r
627 // detect XMS and get upper memory blocks
\r
631 for (i = 1;i < _argc;i++)
\r
633 if ( US_CheckParm(_argv[i],ParmStrings) == 0) // BUG: NOXMS is index 1, not 0
\r
634 goto xmsskip; // param NOXMS
\r
637 if (MML_CheckForXMS())
\r
638 MML_SetupXMS(); // allocate as many UMBs as possible
\r
641 // allocate the misc buffer
\r
644 mmrover = mmhead; // start looking for space after low block
\r
646 MM_GetPtr (&bufferseg,BUFFERSIZE);
\r
649 //==========================================================================
\r
652 ====================
\r
656 = Frees all conventional, EMS, and XMS allocated
\r
658 ====================
\r
661 void MM_Shutdown (void)
\r
668 MML_ShutdownEMS ();
\r
669 MML_ShutdownXMS ();
\r
672 //==========================================================================
\r
675 ====================
\r
679 = Allocates an unlocked, unpurgable block
\r
681 ====================
\r
684 void MM_GetPtr (memptr *baseptr,unsigned long size)
\r
686 mmblocktype far *scan,far *lastscan,far *endscan
\r
687 ,far *purge,far *next;
\r
689 unsigned needed,startseg;
\r
691 needed = (size+15)/16; // convert size from bytes to paragraphs
\r
693 GETNEWBLOCK; // fill in start and next after a spot is found
\r
694 mmnew->length = needed;
\r
695 mmnew->useptr = baseptr;
\r
696 mmnew->attributes = BASEATTRIBUTES;
\r
698 for (search = 0; search<3; search++)
\r
701 // first search: try to allocate right after the rover, then on up
\r
702 // second search: search from the head pointer up to the rover
\r
703 // third search: compress memory, then scan from start
\r
704 if (search == 1 && mmrover == mmhead)
\r
710 lastscan = mmrover;
\r
711 scan = mmrover->next;
\r
716 scan = mmhead->next;
\r
722 scan = mmhead->next;
\r
727 startseg = lastscan->start + lastscan->length;
\r
729 while (scan != endscan)
\r
731 if (scan->start - startseg >= needed)
\r
734 // got enough space between the end of lastscan and
\r
735 // the start of scan, so throw out anything in the middle
\r
736 // and allocate the new block
\r
738 purge = lastscan->next;
\r
739 lastscan->next = mmnew;
\r
740 mmnew->start = *(unsigned *)baseptr = startseg;
\r
741 mmnew->next = scan;
\r
742 while ( purge != scan)
\r
743 { // free the purgable block
\r
744 next = purge->next;
\r
746 purge = next; // purge another if not at scan
\r
749 return; // good allocation!
\r
753 // if this block is purge level zero or locked, skip past it
\r
755 if ( (scan->attributes & LOCKBIT)
\r
756 || !(scan->attributes & PURGEBITS) )
\r
759 startseg = lastscan->start + lastscan->length;
\r
763 scan=scan->next; // look at next line
\r
768 Quit ("MM_GetPtr: Out of memory!");
\r
773 //==========================================================================
\r
776 ====================
\r
780 = Allocates an unlocked, unpurgable block
\r
782 ====================
\r
785 void MM_FreePtr (memptr *baseptr)
\r
787 mmblocktype far *scan,far *last;
\r
792 if (baseptr == mmrover->useptr) // removed the last allocated block
\r
795 while (scan->useptr != baseptr && scan)
\r
802 Quit ("MM_FreePtr: Block not found!");
\r
804 last->next = scan->next;
\r
808 //==========================================================================
\r
811 =====================
\r
815 = Sets the purge level for a block (locked blocks cannot be made purgable)
\r
817 =====================
\r
820 void MM_SetPurge (memptr *baseptr, int purge)
\r
822 mmblocktype far *start;
\r
828 if (mmrover->useptr == baseptr)
\r
831 mmrover = mmrover->next;
\r
835 else if (mmrover == start)
\r
836 Quit ("MM_SetPurge: Block not found!");
\r
840 mmrover->attributes &= ~PURGEBITS;
\r
841 mmrover->attributes |= purge;
\r
844 //==========================================================================
\r
847 =====================
\r
851 = Locks / unlocks the block
\r
853 =====================
\r
856 void MM_SetLock (memptr *baseptr, boolean locked)
\r
858 mmblocktype far *start;
\r
864 if (mmrover->useptr == baseptr)
\r
867 mmrover = mmrover->next;
\r
871 else if (mmrover == start)
\r
872 Quit ("MM_SetLock: Block not found!");
\r
876 mmrover->attributes &= ~LOCKBIT;
\r
877 mmrover->attributes |= locked*LOCKBIT;
\r
880 //==========================================================================
\r
883 =====================
\r
887 = Throws out all purgable stuff and compresses movable blocks
\r
889 =====================
\r
892 void MM_SortMem (void)
\r
894 mmblocktype far *scan,far *last,far *next;
\r
895 unsigned start,length,source,dest,oldborder;
\r
899 // lock down a currently playing sound
\r
901 playing = SD_SoundPlaying ();
\r
907 playing += STARTPCSOUNDS;
\r
910 playing += STARTADLIBSOUNDS;
\r
913 MM_SetLock(&(memptr)audiosegs[playing],true);
\r
918 oldborder = bordercolor;
\r
919 VW_ColorBorder (15);
\r
926 last = NULL; // shut up compiler warning
\r
930 if (scan->attributes & LOCKBIT)
\r
933 // block is locked, so try to pile later blocks right after it
\r
935 start = scan->start + scan->length;
\r
939 if (scan->attributes & PURGEBITS)
\r
942 // throw out the purgable block
\r
953 // push the non purgable block on top of the last moved block
\r
955 if (scan->start != start)
\r
957 length = scan->length;
\r
958 source = scan->start;
\r
960 while (length > 0xf00)
\r
962 movedata(source,0,dest,0,0xf00*16);
\r
967 movedata(source,0,dest,0,length*16);
\r
969 scan->start = start;
\r
970 *(unsigned *)scan->useptr = start;
\r
972 start = scan->start + scan->length;
\r
977 scan = scan->next; // go to next block
\r
985 VW_ColorBorder (oldborder);
\r
988 MM_SetLock(&(memptr)audiosegs[playing],false);
\r
992 //==========================================================================
\r
995 =====================
\r
999 =====================
\r
1002 void MM_ShowMemory (void)
\r
1004 mmblocktype far *scan;
\r
1005 unsigned color,temp;
\r
1007 char scratch[80],str[10];
\r
1009 VW_SetDefaultColors();
\r
1010 VW_SetLineWidth(40);
\r
1013 VW_SetScreen (0,0);
\r
1019 //CA_OpenDebug ();
\r
1023 if (scan->attributes & PURGEBITS)
\r
1024 color = 5; // dark purple = purgable
\r
1026 color = 9; // medium blue = non purgable
\r
1027 if (scan->attributes & LOCKBIT)
\r
1028 color = 12; // red = locked
\r
1029 if (scan->start<=end)
\r
1030 Quit ("MM_ShowMemory: Memory block order corrupted!");
\r
1031 end = scan->start+scan->length-1;
\r
1032 VW_Hlin(scan->start,(unsigned)end,0,color);
\r
1033 VW_Plot(scan->start,0,15);
\r
1034 if (scan->next->start > end+1)
\r
1035 VW_Hlin(end+1,scan->next->start,0,0); // black = free
\r
1038 strcpy (scratch,"Size:");
\r
1039 ltoa ((long)scan->length*16,str,10);
\r
1040 strcat (scratch,str);
\r
1041 strcat (scratch,"\tOwner:0x");
\r
1042 owner = (unsigned)scan->useptr;
\r
1043 ultoa (owner,str,16);
\r
1044 strcat (scratch,str);
\r
1045 strcat (scratch,"\n");
\r
1046 write (debughandle,scratch,strlen(scratch));
\r
1049 scan = scan->next;
\r
1052 //CA_CloseDebug ();
\r
1055 VW_SetLineWidth(64);
\r
1059 //==========================================================================
\r
1063 ======================
\r
1067 = Returns the total free space without purging
\r
1069 ======================
\r
1072 long MM_UnusedMemory (void)
\r
1075 mmblocktype far *scan;
\r
1080 while (scan->next)
\r
1082 free += scan->next->start - (scan->start + scan->length);
\r
1083 scan = scan->next;
\r
1089 //==========================================================================
\r
1093 ======================
\r
1097 = Returns the total free space with purging
\r
1099 ======================
\r
1102 long MM_TotalFree (void)
\r
1105 mmblocktype far *scan;
\r
1110 while (scan->next)
\r
1112 if ((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
\r
1113 free += scan->length;
\r
1114 free += scan->next->start - (scan->start + scan->length);
\r
1115 scan = scan->next;
\r
1121 //==========================================================================
\r
1124 =====================
\r
1128 =====================
\r
1131 void MM_BombOnError (boolean bomb)
\r
1133 bombonerror = bomb;
\r