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 =============================================================================
45 #include "src/lib/16_mm.h"
48 =============================================================================
52 =============================================================================
59 void (* beforesort) (void);
60 void (* aftersort) (void);
61 void (* XMSaddr) (void); // far pointer to XMS driver
64 =============================================================================
68 =============================================================================
76 //mmblocktype far mmblocks[MAXBLOCKS],far *mmhead,far *mmfree,far *mmrover,far *mmnew;
78 //boolean bombonerror;
80 //unsigned totalEMSpages,freeEMSpages,EMSpageframe,EMSpagesmapped,EMShandle;
81 //unsigned int EMSVer;
83 //void (* XMSaddr) (void); // far pointer to XMS driver
85 //unsigned numUMBs,UMBbase[MAXUMBS];
87 static char *ParmStringsexmm[] = {"noems","noxms",""};
90 ======================
94 = Routine from p36 of Extending DOS
96 =======================
99 boolean MML_CheckForEMS(void)
102 char emmname[] = "EMMXXXX0";
103 // mov dx,OFFSET emmname
105 LEA DX, emmname //fix by andrius4669
107 int 0x21 // try to open EMMXXXX0 device
113 int 0x21 // get device info
121 int 0x21 // get status
127 int 0x21 // close handle
146 ======================
150 =======================
153 unsigned MML_SetupEMS(mminfo_t *mm)
155 char str[80],str2[10];
157 boolean errorflag=false;
160 unsigned int EMSVer = 0;
161 unsigned totalEMSpages,freeEMSpages,EMSpageframe,EMSpagesmapped,EMShandle;
162 totalEMSpages = freeEMSpages = EMSpageframe = EMSpagesmapped = 0;
167 int EMS_INT // make sure EMS hardware is present
175 mov [EMSVer],ax // set EMSVer
176 cmp al,0x32 // only work on ems 3.2 or greater
180 int EMS_INT // find the page frame address
183 mov [EMSpageframe],bx
186 int EMS_INT // find out how much EMS is there
189 mov [totalEMSpages],dx
190 mov [freeEMSpages],bx
192 jz noEMS // no EMS at all to allocate
195 jle getpages // there is only 1,2,3,or 4 pages
196 mov bx,4 // we can't use more than 4 pages
199 mov [EMSpagesmapped],bx
200 mov ah,EMS_ALLOCPAGES // allocate up to 64k of EMS
215 strcpy(str,"MML_SetupEMS: EMS error 0x");
221 mm->totalEMSpages=totalEMSpages;
222 mm->freeEMSpages=freeEMSpages;
223 mm->EMSpageframe=EMSpageframe;
224 mm->EMSpagesmapped=EMSpagesmapped;
225 mm->EMShandle=EMShandle;
232 ======================
236 =======================
239 void MML_ShutdownEMS(mminfo_t *mm)
241 boolean errorflag=false;
242 unsigned EMShandle=mm->EMShandle;
256 if(errorflag==true) printf("MML_ShutdownEMS: Error freeing EMS!"); //++++ add something
264 = Maps the 64k of EMS used by memory manager into the page frame
265 = for general use. This only needs to be called if you are keeping
266 = other things in EMS.
271 unsigned MM_MapEMS(mminfo_t *mm)
273 char str[80],str2[10];
274 unsigned err, EMShandle;
275 boolean errorflag=false;
278 EMShandle=mm->EMShandle;
280 for (i=0;i<mm->EMSpagesmapped;i++)
285 mov bx,[i] // logical page
286 mov al,bl // physical page
287 mov dx,[EMShandle] // handle
299 strcpy(str,"MM_MapEMS: EMS error 0x");
309 //==========================================================================
312 ======================
316 = Check for XMM driver
318 =======================
321 boolean MML_CheckForXMS(mminfo_t *mm)
323 boolean errorflag=false;
329 int 0x2f // query status of installed diver
335 if(errorflag==true) return false;
341 ======================
345 = Try to allocate all upper memory block
347 =======================
350 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
358 mov [WORD PTR XMSaddr],bx
359 mov [WORD PTR XMSaddr+2],es // function pointer to XMS driver
365 mov dx,0xffff // try for largest block possible
366 call [DWORD PTR XMSaddr]
370 cmp bl,0xb0 // error: smaller UMB is available
374 call [DWORD PTR XMSaddr] // DX holds largest available UMB
376 jz done // another error...
383 MML_UseSpace(base,size, mm);
384 mmi->XMSmem += size*16;
385 mm->UMBbase[mm->numUMBs] = base;
387 if(mm->numUMBs < MAXUMBS)
393 ======================
397 ======================
400 void MML_ShutdownXMS(mminfo_t *mm)
405 for (i=0;i<mm->numUMBs;i++)
407 base = mm->UMBbase[i];
412 call [DWORD PTR XMSaddr]
417 //==========================================================================
420 ======================
424 = Marks a range of paragraphs as usable by the memory manager
425 = This is used to mark space for the near heap, far heap, ems page frame,
426 = and upper memory blocks
428 ======================
431 void MML_UseSpace(unsigned segstart, unsigned seglength, mminfo_t *mm)
433 mmblocktype far *scan,far *last;
437 scan = last = mm->mmhead;
438 mm->mmrover = mm->mmhead; // reset rover to start of memory
441 // search for the block that contains the range of segments
443 while(scan->start+scan->length < segstart)
450 // take the given range out of the block
452 oldend = scan->start + scan->length;
453 extra = oldend - (segstart+seglength);
456 printf("MML_UseSpace: Segment spans two blocks!");
461 if(segstart == scan->start)
463 last->next = scan->next; // unlink block
464 MM_FreeBlock(scan, mm);
468 scan->length = segstart-scan->start; // shorten block
473 mm->mmnew->next = scan->next;
474 scan->next = mm->mmnew;
475 mm->mmnew->start = segstart+seglength;
476 mm->mmnew->length = extra;
477 mm->mmnew->attributes = LOCKBIT;
482 //==========================================================================
489 = We are out of blocks, so free a purgable block
494 void MML_ClearBlock(mminfo_t *mm)
496 mmblocktype far *scan,far *last;
498 scan = mm->mmhead->next;
502 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
504 MM_FreePtr(scan->useptr, mm);
510 printf("MM_ClearBlock: No purgable blocks!");
514 //==========================================================================
521 = Grabs all space from turbo with malloc/farmalloc
522 = Allocates bufferseg misc buffer
527 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
532 unsigned segstart,seglength,endfree;
537 mm->mmstarted = true;
538 mm->bombonerror = true;
540 // set up the linked list (everything in the free list;
543 mm->mmfree = &(mm->mmblocks[0]);
544 for(i=0;i<MAXBLOCKS-1;i++)
546 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
548 mm->mmblocks[i].next = NULL;
551 // locked block of all memory until we punch out free space
554 mm->mmhead = mm->mmnew; // this will allways be the first node
555 mm->mmnew->start = 0;
556 mm->mmnew->length = 0xffff;
557 mm->mmnew->attributes = LOCKBIT;
558 mm->mmnew->next = NULL;
559 mm->mmrover = mm->mmhead;
563 // get all available near conventional memory segments
565 //---- length=coreleft();
568 start = (void far *)(mm->nearheap = malloc(length));
570 length -= 16-(FP_OFF(start)&15);
571 length -= SAVENEARHEAP;
572 seglength = length / 16; // now in paragraphs
573 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
574 MML_UseSpace(segstart,seglength, mm);
575 mmi->nearheap = length;
578 // get all available far conventional memory segments
580 //---- length=farcoreleft();
583 start = mm->farheap = _fmalloc(length);
584 length -= 16-(FP_OFF(start)&15);
585 length -= SAVEFARHEAP;
586 seglength = length / 16; // now in paragraphs
587 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
588 MML_UseSpace(segstart,seglength, mm);
589 mmi->farheap = length;
590 mmi->mainmem = mmi->nearheap + mmi->farheap;
594 // detect EMS and allocate up to 64K at page frame
597 for(i = 1;i < __argc;i++)
599 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
600 goto emsskip; // param NOEMS
603 if(MML_CheckForEMS())
606 MML_SetupEMS(mm); // allocate space
607 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!
608 MML_UseSpace(mm->EMSpageframe,mm->EMSpagesmapped*0x400, mm);
610 MM_MapEMS(mm); // map in used pages
612 mmi->EMSmem = mm->EMSpagesmapped*0x4000l;
616 // detect XMS and get upper memory blocks
620 for(i = 1;i < __argc;i++)
622 if( US_CheckParm(__argv[i],ParmStringsexmm) == 0)
623 goto xmsskip; // param NOXMS
626 if(MML_CheckForXMS(mm))
629 MML_SetupXMS(mm, mmi); // allocate as many UMBs as possible
633 // allocate the misc buffer
636 mm->mmrover = mm->mmhead; // start looking for space after low block
638 MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
641 //==========================================================================
648 = Frees all conventional, EMS, and XMS allocated
653 void MM_Shutdown(mminfo_t *mm)
659 printf("far freed\n");
661 printf("near freed\n");
662 //hfree(mm->hugeheap);
663 //printf("huge freed\n");
665 printf("EMS freed\n");
667 printf("XMS freed\n");
670 //==========================================================================
677 = Allocates an unlocked, unpurgable block
682 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
684 mmblocktype far *scan,far *lastscan,far *endscan
685 ,far *purge,far *next;
687 unsigned needed,startseg;
689 needed = (size+15)/16; // convert size from bytes to paragraphs
691 MM_GetNewBlock(mm); // fill in start and next after a spot is found
692 mm->mmnew->length = needed;
693 mm->mmnew->useptr = baseptr;
694 mm->mmnew->attributes = BASEATTRIBUTES;
696 for(search = 0; search<3; search++)
699 // first search: try to allocate right after the rover, then on up
700 // second search: search from the head pointer up to the rover
701 // third search: compress memory, then scan from start
702 if(search == 1 && mm->mmrover == mm->mmhead)
708 lastscan = mm->mmrover;
709 scan = mm->mmrover->next;
713 lastscan = mm->mmhead;
714 scan = mm->mmhead->next;
715 endscan = mm->mmrover;
719 lastscan = mm->mmhead;
720 scan = mm->mmhead->next;
725 startseg = lastscan->start + lastscan->length;
727 while(scan != endscan)
729 if(scan->start - startseg >= needed)
732 // got enough space between the end of lastscan and
733 // the start of scan, so throw out anything in the middle
734 // and allocate the new block
736 purge = lastscan->next;
737 lastscan->next = mm->mmnew;
738 mm->mmnew->start = *(unsigned *)baseptr = startseg;
739 mm->mmnew->next = scan;
741 { // free the purgable block
743 MM_FreeBlock(purge, mm);
744 purge = next; // purge another if not at scan
746 mm->mmrover = mm->mmnew;
747 return; // good allocation!
751 // if this block is purge level zero or locked, skip past it
753 if((scan->attributes & LOCKBIT)
754 || !(scan->attributes & PURGEBITS) )
757 startseg = lastscan->start + lastscan->length;
761 scan=scan->next; // look at next line
766 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
771 //==========================================================================
778 = Allocates an unlocked, unpurgable block
783 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
785 mmblocktype far *scan,far *last;
790 if(baseptr == mm->mmrover->useptr) // removed the last allocated block
791 mm->mmrover = mm->mmhead;
793 while(scan->useptr != baseptr && scan)
801 printf("MM_FreePtr: Block not found!");
805 last->next = scan->next;
807 MM_FreeBlock(scan, mm);
809 //==========================================================================
812 =====================
816 = Sets the purge level for a block (locked blocks cannot be made purgable)
818 =====================
821 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
823 mmblocktype far *start;
829 if(mm->mmrover->useptr == baseptr)
832 mm->mmrover = mm->mmrover->next;
835 mm->mmrover = mm->mmhead;
836 else if(mm->mmrover == start)
838 printf("MM_SetPurge: Block not found!");
844 mm->mmrover->attributes &= ~PURGEBITS;
845 mm->mmrover->attributes |= purge;
848 //==========================================================================
851 =====================
855 = Locks / unlocks the block
857 =====================
860 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
862 mmblocktype far *start;
868 if(mm->mmrover->useptr == baseptr)
871 mm->mmrover = mm->mmrover->next;
874 mm->mmrover = mm->mmhead;
875 else if(mm->mmrover == start)
877 printf("MM_SetLock: Block not found!");
883 mm->mmrover->attributes &= ~LOCKBIT;
884 mm->mmrover->attributes |= locked*LOCKBIT;
887 //==========================================================================
890 =====================
894 = Throws out all purgable stuff and compresses movable blocks
896 =====================
899 void MM_SortMem(mminfo_t *mm)
901 mmblocktype far *scan,far *last,far *next;
902 unsigned start,length,source,dest,oldborder;
906 // lock down a currently playing sound
908 /*++++ playing = SD_SoundPlaying ();
914 playing += STARTPCSOUNDS;
917 playing += STARTADLIBSOUNDS;
920 MM_SetLock(&(memptr)audiosegs[playing],true);
925 // oldborder = bordercolor;
926 // VW_ColorBorder (15);
933 last = NULL; // shut up compiler warning
937 if(scan->attributes & LOCKBIT)
940 // block is locked, so try to pile later blocks right after it
942 start = scan->start + scan->length;
946 if(scan->attributes & PURGEBITS)
949 // throw out the purgable block
952 MM_FreeBlock(scan, mm);
960 // push the non purgable block on top of the last moved block
962 if(scan->start != start)
964 length = scan->length;
965 source = scan->start;
967 while(length > 0xf00)
969 movedata(source,0,dest,0,0xf00*16);
974 movedata(source,0,dest,0,length*16);
977 *(unsigned *)scan->useptr = start;
979 start = scan->start + scan->length;
984 scan = scan->next; // go to next block
987 mm->mmrover = mm->mmhead;
992 // VW_ColorBorder (oldborder);
995 MM_SetLock(&(memptr)audiosegs[playing],false);*/
999 //==========================================================================
1003 =====================
1007 =====================
1010 void MM_ShowMemory(mminfo_t *mm)
1012 mmblocktype far *scan;
1013 unsigned color,temp;//, i;
1015 char scratch[80],str[10];
1017 //**** VW_SetDefaultColors();
1018 //**** VW_SetLineWidth(40);
1019 //++++mh temp = bufferofs;
1020 //++++mh bufferofs = 0;
1021 //**** VW_SetScreen (0,0);
1031 if(scan->attributes & PURGEBITS)
1032 color = 5; // dark purple = purgable
1034 color = 9; // medium blue = non purgable
1035 if(scan->attributes & LOCKBIT)
1036 color = 12; // red = locked
1037 if(scan->start<=end)
1039 printf("MM_ShowMemory: Memory block order currupted!");
1042 end = scan->start+scan->length-1;
1043 //++++ VW_Hlin(scan->start,(unsigned)end,0,color);
1044 //++++ VW_Plot(scan->start,0,15);
1045 if(scan->next->start > end+1)
1046 //++++ VW_Hlin(end+1,scan->next->start,0,0); // black = free
1049 printf("Location:");
1050 printf("%x\t", scan->start);
1051 strcpy (scratch,"Size:");
1052 ltoa ((long)scan->length*16,str,10);
1053 strcat (scratch,str);
1054 strcat (scratch,"\tOwner:0x");
1055 owner = (unsigned)scan->useptr;
1056 ultoa (owner,str,16);
1057 strcat (scratch,str);
1058 strcat (scratch,"\n");
1059 //++++write (debughandle,scratch,strlen(scratch));
1060 fprintf(stdout, "%s", scratch);
1069 //**** VW_SetLineWidth(64);
1070 //++++mh bufferofs = temp;
1074 //==========================================================================
1078 ======================
1082 = Returns the total free space without purging
1084 ======================
1087 dword MM_UnusedMemory(mminfo_t *mm)
1090 mmblocktype far *scan;
1097 free += scan->next->start - (scan->start + scan->length);
1105 //==========================================================================
1109 ======================
1113 = Returns the total free space with purging
1115 ======================
1118 dword MM_TotalFree(mminfo_t *mm)
1121 mmblocktype far *scan;
1128 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1129 free += scan->length;
1130 free += scan->next->start - (scan->start + scan->length);
1138 //==========================================================================
1141 =====================
1145 =====================
1148 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1150 printf("EMM %x available\n", mm->EMSVer);
1151 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1152 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1153 printf("EMSpageframe=%Fp\n", mm->EMSpageframe);
1154 printf("near=%lu\n", mmi->nearheap);
1155 printf("far=%lu\n", mmi->farheap);
1156 printf("EMSmem=%lu\n", mmi->EMSmem);
1157 printf("XMSmem=%lu\n", mmi->XMSmem);
1158 printf("mainmem=%lu\n", mmi->mainmem);
1159 printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1160 printf("TotalFree=%lu\n", MM_TotalFree(mm));
1162 // printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1163 // printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1166 //==========================================================================
1169 =====================
1173 =====================
1188 //==========================================================================
1191 =====================
1195 =====================
1198 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1200 mm->bombonerror = bomb;
1203 void MM_GetNewBlock(mminfo_t *mm)
1207 mm->mmnew=mm->mmfree;
1208 mm->mmfree=mm->mmfree->next;
1209 /*if(!(mm->mmnew=mm->mmfree))
1211 printf("MM_GETNEWBLOCK: No free blocks!");
1214 mm->mmfree=mm->mmfree->next;*/
1217 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)