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
602 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!
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
625 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!
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");
664 if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
665 if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
668 //==========================================================================
675 = Allocates an unlocked, unpurgable block
680 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
682 mmblocktype far *scan,far *lastscan,far *endscan
683 ,far *purge,far *next;
685 unsigned needed,startseg;
687 needed = (size+15)/16; // convert size from bytes to paragraphs
689 MM_GetNewBlock(mm); // fill in start and next after a spot is found
690 mm->mmnew->length = needed;
691 mm->mmnew->useptr = baseptr;
692 mm->mmnew->attributes = BASEATTRIBUTES;
694 for(search = 0; search<3; search++)
697 // first search: try to allocate right after the rover, then on up
698 // second search: search from the head pointer up to the rover
699 // third search: compress memory, then scan from start
700 if(search == 1 && mm->mmrover == mm->mmhead)
706 lastscan = mm->mmrover;
707 scan = mm->mmrover->next;
711 lastscan = mm->mmhead;
712 scan = mm->mmhead->next;
713 endscan = mm->mmrover;
717 lastscan = mm->mmhead;
718 scan = mm->mmhead->next;
723 startseg = lastscan->start + lastscan->length;
725 while(scan != endscan)
727 if(scan->start - startseg >= needed)
730 // got enough space between the end of lastscan and
731 // the start of scan, so throw out anything in the middle
732 // and allocate the new block
734 purge = lastscan->next;
735 lastscan->next = mm->mmnew;
736 mm->mmnew->start = *(unsigned *)baseptr = startseg;
737 mm->mmnew->next = scan;
739 { // free the purgable block
741 MM_FreeBlock(purge, mm);
742 purge = next; // purge another if not at scan
744 mm->mmrover = mm->mmnew;
745 return; // good allocation!
749 // if this block is purge level zero or locked, skip past it
751 if((scan->attributes & LOCKBIT)
752 || !(scan->attributes & PURGEBITS) )
755 startseg = lastscan->start + lastscan->length;
759 scan=scan->next; // look at next line
764 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
769 //==========================================================================
776 = Allocates an unlocked, unpurgable block
781 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
783 mmblocktype far *scan,far *last;
788 if(baseptr == mm->mmrover->useptr) // removed the last allocated block
789 mm->mmrover = mm->mmhead;
791 while(scan->useptr != baseptr && scan)
799 printf("MM_FreePtr: Block not found!");
803 last->next = scan->next;
805 MM_FreeBlock(scan, mm);
807 //==========================================================================
810 =====================
814 = Sets the purge level for a block (locked blocks cannot be made purgable)
816 =====================
819 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
821 mmblocktype far *start;
827 if(mm->mmrover->useptr == baseptr)
830 mm->mmrover = mm->mmrover->next;
833 mm->mmrover = mm->mmhead;
834 else if(mm->mmrover == start)
836 printf("MM_SetPurge: Block not found!");
842 mm->mmrover->attributes &= ~PURGEBITS;
843 mm->mmrover->attributes |= purge;
846 //==========================================================================
849 =====================
853 = Locks / unlocks the block
855 =====================
858 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
860 mmblocktype far *start;
866 if(mm->mmrover->useptr == baseptr)
869 mm->mmrover = mm->mmrover->next;
872 mm->mmrover = mm->mmhead;
873 else if(mm->mmrover == start)
875 printf("MM_SetLock: Block not found!");
881 mm->mmrover->attributes &= ~LOCKBIT;
882 mm->mmrover->attributes |= locked*LOCKBIT;
885 //==========================================================================
888 =====================
892 = Throws out all purgable stuff and compresses movable blocks
894 =====================
897 void MM_SortMem(mminfo_t *mm)
899 mmblocktype far *scan,far *last,far *next;
900 unsigned start,length,source,dest,oldborder;
904 // lock down a currently playing sound
906 /*++++ playing = SD_SoundPlaying ();
912 playing += STARTPCSOUNDS;
915 playing += STARTADLIBSOUNDS;
918 MM_SetLock(&(memptr)audiosegs[playing],true);
923 // oldborder = bordercolor;
924 // VW_ColorBorder (15);
931 last = NULL; // shut up compiler warning
935 if(scan->attributes & LOCKBIT)
938 // block is locked, so try to pile later blocks right after it
940 start = scan->start + scan->length;
944 if(scan->attributes & PURGEBITS)
947 // throw out the purgable block
950 MM_FreeBlock(scan, mm);
958 // push the non purgable block on top of the last moved block
960 if(scan->start != start)
962 length = scan->length;
963 source = scan->start;
965 while(length > 0xf00)
967 movedata(source,0,dest,0,0xf00*16);
972 movedata(source,0,dest,0,length*16);
975 *(unsigned *)scan->useptr = start;
977 start = scan->start + scan->length;
982 scan = scan->next; // go to next block
985 mm->mmrover = mm->mmhead;
990 // VW_ColorBorder (oldborder);
993 MM_SetLock(&(memptr)audiosegs[playing],false);*/
997 //==========================================================================
1001 =====================
1005 =====================
1008 void MM_ShowMemory(mminfo_t *mm)
1010 mmblocktype far *scan;
1011 unsigned color,temp;//, i;
1013 char scratch[80],str[10];
1015 //**** VW_SetDefaultColors();
1016 //**** VW_SetLineWidth(40);
1017 //++++mh temp = bufferofs;
1018 //++++mh bufferofs = 0;
1019 //**** VW_SetScreen (0,0);
1029 if(scan->attributes & PURGEBITS)
1030 color = 5; // dark purple = purgable
1032 color = 9; // medium blue = non purgable
1033 if(scan->attributes & LOCKBIT)
1034 color = 12; // red = locked
1035 if(scan->start<=end)
1037 printf("MM_ShowMemory: Memory block order currupted!");
1040 end = scan->start+scan->length-1;
1041 //++++ VW_Hlin(scan->start,(unsigned)end,0,color);
1042 //++++ VW_Plot(scan->start,0,15);
1043 if(scan->next->start > end+1)
1044 //++++ VW_Hlin(end+1,scan->next->start,0,0); // black = free
1047 printf("Location:");
1048 printf("%x\t", scan->start);
1049 strcpy (scratch,"Size:");
1050 ltoa ((long)scan->length*16,str,10);
1051 strcat (scratch,str);
1052 strcat (scratch,"\tOwner:0x");
1053 owner = (unsigned)scan->useptr;
1054 ultoa (owner,str,16);
1055 strcat (scratch,str);
1056 strcat (scratch,"\n");
1057 //++++write (debughandle,scratch,strlen(scratch));
1058 fprintf(stdout, "%s", scratch);
1067 //**** VW_SetLineWidth(64);
1068 //++++mh bufferofs = temp;
1072 //==========================================================================
1076 ======================
1080 = Returns the total free space without purging
1082 ======================
1085 dword MM_UnusedMemory(mminfo_t *mm)
1088 mmblocktype far *scan;
1095 free += scan->next->start - (scan->start + scan->length);
1103 //==========================================================================
1107 ======================
1111 = Returns the total free space with purging
1113 ======================
1116 dword MM_TotalFree(mminfo_t *mm)
1119 mmblocktype far *scan;
1126 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1127 free += scan->length;
1128 free += scan->next->start - (scan->start + scan->length);
1136 //==========================================================================
1139 =====================
1143 =====================
1146 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1148 if(MML_CheckForEMS())
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);
1155 printf("near=%lu\n", mmi->nearheap);
1156 printf("far=%lu\n", mmi->farheap);
1157 printf("EMSmem=%lu\n", mmi->EMSmem);
1158 printf("XMSmem=%lu\n", mmi->XMSmem);
1159 printf("mainmem=%lu\n", mmi->mainmem);
1160 printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1161 printf("TotalFree=%lu\n", MM_TotalFree(mm));
1163 // printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1164 // printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1167 //==========================================================================
1170 =====================
1174 =====================
1189 //==========================================================================
1192 =====================
1196 =====================
1199 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1201 mm->bombonerror = bomb;
1204 void MM_GetNewBlock(mminfo_t *mm)
1208 mm->mmnew=mm->mmfree;
1209 mm->mmfree=mm->mmfree->next;
1210 /*if(!(mm->mmnew=mm->mmfree))
1212 printf("MM_GETNEWBLOCK: No free blocks!");
1215 mm->mmfree=mm->mmfree->next;*/
1218 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)