1 /* Catacomb Apocalypse Source Code
2 * Copyright (C) 1993-2014 Flat Rock Software
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.
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.
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.
22 =============================================================================
24 ID software memory manager
25 --------------------------
27 Primary coder: John Carmack
31 Quit (char *error) function
36 MM_SizePtr to change the size of a given pointer
38 Multiple purge levels utilized
40 EMS / XMS unmanaged routines
42 =============================================================================
46 Open Watcom port by sparky4
49 #include "src/lib/16_mm.h"
52 =============================================================================
56 =============================================================================
59 void (* beforesort) (void);
60 void (* aftersort) (void);
61 void (* XMSaddr) (void); // far pointer to XMS driver
64 =============================================================================
68 =============================================================================
71 static char *ParmStringsexmm[] = {"noems","noxms",""};
74 ======================
78 = Routine from p36 of Extending DOS
80 =======================
83 boolean MML_CheckForEMS(void)
86 char emmname[] = "EMMXXXX0";
87 // mov dx,OFFSET emmname
89 LEA DX, emmname //fix by andrius4669
91 int 0x21 // try to open EMMXXXX0 device
97 int 0x21 // get device info
105 int 0x21 // get status
111 int 0x21 // close handle
130 ======================
134 =======================
137 unsigned MML_SetupEMS(mminfo_t *mm)
139 char str[80],str2[10];
141 boolean errorflag=false;
144 unsigned int EMSVer = 0;
145 unsigned totalEMSpages,freeEMSpages,EMSpageframe,EMSpagesmapped,EMShandle;
146 totalEMSpages = freeEMSpages = EMSpageframe = EMSpagesmapped = 0;
151 int EMS_INT // make sure EMS hardware is present
159 mov [EMSVer],ax // set EMSVer
160 cmp al,0x32 // only work on ems 3.2 or greater
164 int EMS_INT // find the page frame address
167 mov [EMSpageframe],bx
170 int EMS_INT // find out how much EMS is there
173 mov [totalEMSpages],dx
174 mov [freeEMSpages],bx
176 jz noEMS // no EMS at all to allocate
179 jle getpages // there is only 1,2,3,or 4 pages
180 mov bx,4 // we can't use more than 4 pages
183 mov [EMSpagesmapped],bx
184 mov ah,EMS_ALLOCPAGES // allocate up to 64k of EMS
199 strcpy(str,"MML_SetupEMS: EMS error 0x");
205 mm->totalEMSpages=totalEMSpages;
206 mm->freeEMSpages=freeEMSpages;
207 mm->EMSpageframe=EMSpageframe;
208 mm->EMSpagesmapped=EMSpagesmapped;
209 mm->EMShandle=EMShandle;
216 ======================
220 =======================
223 void MML_ShutdownEMS(mminfo_t *mm)
225 boolean errorflag=false;
226 unsigned EMShandle=mm->EMShandle;
240 if(errorflag==true) printf("MML_ShutdownEMS: Error freeing EMS!"); //++++ add something
248 = Maps the 64k of EMS used by memory manager into the page frame
249 = for general use. This only needs to be called if you are keeping
250 = other things in EMS.
255 unsigned MM_MapEMS(mminfo_t *mm)
257 char str[80],str2[10];
258 unsigned err, EMShandle;
259 boolean errorflag=false;
262 EMShandle=mm->EMShandle;
264 for (i=0;i<mm->EMSpagesmapped;i++)
269 mov bx,[i] // logical page
270 mov al,bl // physical page
271 mov dx,[EMShandle] // handle
283 strcpy(str,"MM_MapEMS: EMS error 0x");
293 //==========================================================================
296 ======================
300 = Check for XMM driver
302 =======================
305 boolean MML_CheckForXMS(mminfo_t *mm)
307 boolean errorflag=false;
313 int 0x2f // query status of installed diver
319 if(errorflag==true) return false;
325 ======================
329 = Try to allocate all upper memory block
331 =======================
334 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
343 mov [WORD PTR XMSaddr],bx
344 mov [WORD PTR XMSaddr+2],es // function pointer to XMS driver
347 mov dx,0xffff // try for largest block possible
348 call [DWORD PTR XMSaddr]
352 cmp bl,0xb0 // error: smaller UMB is available
356 call [DWORD PTR XMSaddr] // DX holds largest available UMB
358 jz done // another error...
365 MML_UseSpace(base,size, mm);
366 mmi->XMSmem += size*16;
367 mm->UMBbase[mm->numUMBs] = base;
369 if(mm->numUMBs < MAXUMBS)
375 ======================
379 ======================
382 void MML_ShutdownXMS(mminfo_t *mm)
387 for (i=0;i<mm->numUMBs;i++)
389 base = mm->UMBbase[i];
394 call [DWORD PTR XMSaddr]
399 //==========================================================================
402 ======================
406 = Marks a range of paragraphs as usable by the memory manager
407 = This is used to mark space for the near heap, far heap, ems page frame,
408 = and upper memory blocks
410 ======================
413 void MML_UseSpace(unsigned segstart, dword seglength, mminfo_t *mm)
415 mmblocktype huge *scan,huge *last;
420 scan = last = mm->mmhead;
421 mm->mmrover = mm->mmhead; // reset rover to start of memory
424 // search for the block that contains the range of segments
426 while(scan->start+scan->length < segstart)
433 // take the given range out of the block
435 oldend = scan->start + scan->length;
436 extra = oldend - (segstart+seglength);
440 printf("MML_UseSpace: Segment spans two blocks!\n");
445 if(segstart == scan->start)
447 last->next = scan->next; // unlink block
448 MM_FreeBlock(scan, mm);
452 scan->length = segstart-scan->start; // shorten block
457 mm->mmnew->next = scan->next;
458 scan->next = mm->mmnew;
459 mm->mmnew->start = segstart+seglength;
460 mm->mmnew->length = extra;
461 mm->mmnew->attributes = LOCKBIT;
466 //==========================================================================
473 = We are out of blocks, so free a purgable block
478 void MML_ClearBlock(mminfo_t *mm)
480 mmblocktype huge *scan,huge *last;
482 scan = mm->mmhead->next;
486 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
488 MM_FreePtr(scan->useptr, mm);
494 printf("MM_ClearBlock: No purgable blocks!");
498 //==========================================================================
505 = Grabs all space from turbo with malloc/farmalloc
506 = Allocates bufferseg misc buffer
511 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
514 dword length;//,farlen;
516 unsigned segstart,seglength,endfree;
521 mm->mmstarted = true;
522 mm->bombonerror = true;
524 // set up the linked list (everything in the free list;
527 mm->mmfree = &(mm->mmblocks[0]);
528 for(i=0;i<MAXBLOCKS-1;i++)
530 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
532 mm->mmblocks[i].next = NULL;
535 // locked block of all memory until we punch out free space
538 mm->mmhead = mm->mmnew; // this will allways be the first node
539 mm->mmnew->start = 0;
540 mm->mmnew->length = 0xffff; //todo: mm make it fucking massive as fuck!~
541 mm->mmnew->attributes = LOCKBIT;
542 mm->mmnew->next = NULL;
543 mm->mmrover = mm->mmhead;
545 // farlen=_bios_memsize()*1024;
548 // get all available near conventional memory segments
550 //---- length=coreleft();
553 start = (void huge *)(mm->nearheap = malloc(length));
555 length -= 16-(FP_OFF(start)&15);
556 length -= SAVENEARHEAP;
557 seglength = length / 16; // now in paragraphs
558 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
559 MML_UseSpace(segstart,seglength, mm);
560 mmi->nearheap = length;
563 // get all available far conventional memory segments
565 //---- length=farcoreleft();
569 start = mm->farheap = halloc(length, sizeof(length));
570 //start = mm->farheap = _fmalloc(length);
571 length -= 16-(FP_OFF(start)&15);
572 length -= SAVEFARHEAP;
573 seglength = length / 16; // now in paragraphs
574 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
575 MML_UseSpace(segstart,seglength, mm);
576 mmi->farheap = length;
577 mmi->mainmem = mmi->nearheap + mmi->farheap;
581 // detect EMS and allocate up to 64K at page frame
584 for(i = 1;i < __argc;i++)
586 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
587 goto emsskip; // param NOEMS
589 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!
590 if(MML_CheckForEMS())
593 MML_SetupEMS(mm); // allocate space
594 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!
595 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
596 if(mm->EMSVer>=0x40) MML_UseSpace(mm->EMSpageframe,((dword)mm->EMSpagesmapped)*((dword)mm->freeEMSpages), mm);
597 else MML_UseSpace(mm->EMSpageframe,mm->EMSpagesmapped*0x400, mm);
599 MM_MapEMS(mm); // map in used pages
601 if(mm->EMSVer>=0x40) mmi->EMSmem = ((dword)mm->EMSpagesmapped)*((dword)mm->freeEMSpages);
602 else mmi->EMSmem = mm->EMSpagesmapped*0x4000l;
606 // detect XMS and get upper memory blocks
610 for(i = 1;i < __argc;i++)
612 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
613 goto xmsskip; // param NOXMS
615 // 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!
616 if(MML_CheckForXMS(mm))
619 MML_SetupXMS(mm, mmi); // allocate as many UMBs as possible
623 // allocate the misc buffer
626 mm->mmrover = mm->mmhead; // start looking for space after low block
628 MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
631 //==========================================================================
638 = Frees all conventional, EMS, and XMS allocated
643 void MM_Shutdown(mminfo_t *mm)
649 printf("far freed\n");
651 printf("near freed\n");
652 //hfree(mm->hugeheap);
653 //printf("huge freed\n");
654 if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
655 if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
658 //==========================================================================
665 = Allocates an unlocked, unpurgable block
670 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
672 mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
674 unsigned needed,startseg;
676 needed = (size+15)/16; // convert size from bytes to paragraphs
678 MM_GetNewBlock(mm); // fill in start and next after a spot is found
679 mm->mmnew->length = needed;
680 mm->mmnew->useptr = baseptr;
681 mm->mmnew->attributes = BASEATTRIBUTES;
683 for(search = 0; search<3; search++)
686 // first search: try to allocate right after the rover, then on up
687 // second search: search from the head pointer up to the rover
688 // third search: compress memory, then scan from start
689 if(search == 1 && mm->mmrover == mm->mmhead)
695 lastscan = mm->mmrover;
696 scan = mm->mmrover->next;
700 lastscan = mm->mmhead;
701 scan = mm->mmhead->next;
702 endscan = mm->mmrover;
706 lastscan = mm->mmhead;
707 scan = mm->mmhead->next;
712 startseg = lastscan->start + lastscan->length;
714 while(scan != endscan)
716 if(scan->start - startseg >= needed)
719 // got enough space between the end of lastscan and
720 // the start of scan, so throw out anything in the middle
721 // and allocate the new block
723 purge = lastscan->next;
724 lastscan->next = mm->mmnew;
725 mm->mmnew->start = *(unsigned *)baseptr = startseg;
726 mm->mmnew->next = scan;
728 { // free the purgable block
730 MM_FreeBlock(purge, mm);
731 purge = next; // purge another if not at scan
733 mm->mmrover = mm->mmnew;
734 return; // good allocation!
738 // if this block is purge level zero or locked, skip past it
740 if((scan->attributes & LOCKBIT)
741 || !(scan->attributes & PURGEBITS) )
744 startseg = lastscan->start + lastscan->length;
748 scan=scan->next; // look at next line
753 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
758 //==========================================================================
765 = Allocates an unlocked, unpurgable block
770 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
772 mmblocktype huge *scan,huge *last;
777 if(baseptr == mm->mmrover->useptr) // removed the last allocated block
778 mm->mmrover = mm->mmhead;
780 while(scan->useptr != baseptr && scan)
788 printf("MM_FreePtr: Block not found!");
792 last->next = scan->next;
794 MM_FreeBlock(scan, mm);
796 //==========================================================================
799 =====================
803 = Sets the purge level for a block (locked blocks cannot be made purgable)
805 =====================
808 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
810 mmblocktype huge *start;
816 if(mm->mmrover->useptr == baseptr)
819 mm->mmrover = mm->mmrover->next;
822 mm->mmrover = mm->mmhead;
823 else if(mm->mmrover == start)
825 printf("MM_SetPurge: Block not found!");
831 mm->mmrover->attributes &= ~PURGEBITS;
832 mm->mmrover->attributes |= purge;
835 //==========================================================================
838 =====================
842 = Locks / unlocks the block
844 =====================
847 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
849 mmblocktype huge *start;
855 if(mm->mmrover->useptr == baseptr)
858 mm->mmrover = mm->mmrover->next;
861 mm->mmrover = mm->mmhead;
862 else if(mm->mmrover == start)
864 printf("MM_SetLock: Block not found!");
870 mm->mmrover->attributes &= ~LOCKBIT;
871 mm->mmrover->attributes |= locked*LOCKBIT;
874 //==========================================================================
877 =====================
881 = Throws out all purgable stuff and compresses movable blocks
883 =====================
886 void MM_SortMem(mminfo_t *mm)
888 mmblocktype huge *scan,huge *last,huge *next;
889 unsigned start,length,source,dest,oldborder;
893 // lock down a currently playing sound
895 /*++++ playing = SD_SoundPlaying ();
901 playing += STARTPCSOUNDS;
904 playing += STARTADLIBSOUNDS;
907 MM_SetLock(&(memptr)audiosegs[playing],true);
912 // oldborder = bordercolor;
913 // VW_ColorBorder (15);
920 last = NULL; // shut up compiler warning
924 if(scan->attributes & LOCKBIT)
927 // block is locked, so try to pile later blocks right after it
929 start = scan->start + scan->length;
933 if(scan->attributes & PURGEBITS)
936 // throw out the purgable block
939 MM_FreeBlock(scan, mm);
947 // push the non purgable block on top of the last moved block
949 if(scan->start != start)
951 length = scan->length;
952 source = scan->start;
954 while(length > 0xf00)
956 movedata(source,0,dest,0,0xf00*16);
961 movedata(source,0,dest,0,length*16);
964 *(unsigned *)scan->useptr = start;
966 start = scan->start + scan->length;
971 scan = scan->next; // go to next block
974 mm->mmrover = mm->mmhead;
979 // VW_ColorBorder (oldborder);
982 MM_SetLock(&(memptr)audiosegs[playing],false);*/
986 //==========================================================================
990 =====================
994 =====================
997 void MM_ShowMemory(mminfo_t *mm)
999 mmblocktype huge *scan;
1000 unsigned color,temp;//, i;
1002 char scratch[80],str[10];
1004 //**** VW_SetDefaultColors();
1005 //**** VW_SetLineWidth(40);
1006 //++++mh temp = bufferofs;
1007 //++++mh bufferofs = 0;
1008 //**** VW_SetScreen (0,0);
1018 if(scan->attributes & PURGEBITS)
1019 color = 5; // dark purple = purgable
1021 color = 9; // medium blue = non purgable
1022 if(scan->attributes & LOCKBIT)
1023 color = 12; // red = locked
1024 if(scan->start<=end)
1026 printf("MM_ShowMemory: Memory block order currupted!");
1029 end = scan->start+scan->length-1;
1030 //++++ VW_Hlin(scan->start,(unsigned)end,0,color);
1031 //++++ VW_Plot(scan->start,0,15);
1032 if(scan->next->start > end+1)
1033 //++++ VW_Hlin(end+1,scan->next->start,0,0); // black = free
1036 printf("Location:");
1037 printf("%x\t", scan->start);
1038 strcpy (scratch,"Size:");
1039 ltoa ((dword)scan->length*16,str,10);
1040 strcat (scratch,str);
1041 strcat (scratch,"\tOwner:0x");
1042 owner = (unsigned)scan->useptr;
1043 ultoa (owner,str,16);
1044 strcat (scratch,str);
1045 strcat (scratch,"\n");
1046 //++++write (debughandle,scratch,strlen(scratch));
1047 fprintf(stdout, "%s", scratch);
1056 //**** VW_SetLineWidth(64);
1057 //++++mh bufferofs = temp;
1061 //==========================================================================
1065 ======================
1069 = Returns the total free space without purging
1071 ======================
1074 dword MM_UnusedMemory(mminfo_t *mm)
1077 mmblocktype huge *scan;
1084 free += scan->next->start - (scan->start + scan->length);
1092 //==========================================================================
1096 ======================
1100 = Returns the total free space with purging
1102 ======================
1105 dword MM_TotalFree(mminfo_t *mm)
1108 mmblocktype huge *scan;
1115 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1116 free += scan->length;
1117 free += scan->next->start - (scan->start + scan->length);
1125 //==========================================================================
1128 =====================
1132 =====================
1135 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1137 if(MML_CheckForEMS())
1139 printf("EMM %x available\n", mm->EMSVer);
1140 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1141 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1142 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1144 if(MML_CheckForXMS(mm)) printf("XMSaddr=%x\n", *XMSaddr);
1145 printf("near=%lu\n", mmi->nearheap);
1146 printf("far=%lu\n", mmi->farheap);
1147 printf("EMSmem=%lu\n", mmi->EMSmem);
1148 printf("XMSmem=%lu\n", mmi->XMSmem);
1149 printf("mainmem=%lu\n", mmi->mainmem);
1150 printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1151 printf("TotalFree=%lu\n", MM_TotalFree(mm));
1153 // printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1154 // printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1157 //==========================================================================
1160 =====================
1164 =====================
1179 //==========================================================================
1182 =====================
1186 =====================
1189 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1191 mm->bombonerror = bomb;
1194 void MM_GetNewBlock(mminfo_t *mm)
1198 mm->mmnew=mm->mmfree;
1199 mm->mmfree=mm->mmfree->next;
1200 /*if(!(mm->mmnew=mm->mmfree))
1202 printf("MM_GETNEWBLOCK: No free blocks!");
1205 mm->mmfree=mm->mmfree->next;*/
1208 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)