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)
342 mov [WORD PTR XMSaddr],bx
343 mov [WORD PTR XMSaddr+2],es // function pointer to XMS driver
349 mov dx,0xffff // try for largest block possible
350 call [DWORD PTR XMSaddr]
354 cmp bl,0xb0 // error: smaller UMB is available
358 call [DWORD PTR XMSaddr] // DX holds largest available UMB
360 jz done // another error...
367 MML_UseSpace(base,size, mm);
368 mmi->XMSmem += size*16;
369 mm->UMBbase[mm->numUMBs] = base;
371 if(mm->numUMBs < MAXUMBS)
377 ======================
381 ======================
384 void MML_ShutdownXMS(mminfo_t *mm)
389 for (i=0;i<mm->numUMBs;i++)
391 base = mm->UMBbase[i];
396 call [DWORD PTR XMSaddr]
401 //==========================================================================
404 ======================
408 = Marks a range of paragraphs as usable by the memory manager
409 = This is used to mark space for the near heap, far heap, ems page frame,
410 = and upper memory blocks
412 ======================
415 void MML_UseSpace(unsigned segstart, unsigned seglength, mminfo_t *mm)
417 mmblocktype huge *scan,huge *last;
422 scan = last = mm->mmhead;
423 mm->mmrover = mm->mmhead; // reset rover to start of memory
426 // search for the block that contains the range of segments
428 while(scan->start+scan->length < segstart)
435 // take the given range out of the block
437 oldend = scan->start + scan->length;
438 extra = oldend - (segstart+seglength);
442 printf("MML_UseSpace: Segment spans two blocks!");
447 if(segstart == scan->start)
449 last->next = scan->next; // unlink block
450 MM_FreeBlock(scan, mm);
454 scan->length = segstart-scan->start; // shorten block
459 mm->mmnew->next = scan->next;
460 scan->next = mm->mmnew;
461 mm->mmnew->start = segstart+seglength;
462 mm->mmnew->length = extra;
463 mm->mmnew->attributes = LOCKBIT;
468 //==========================================================================
475 = We are out of blocks, so free a purgable block
480 void MML_ClearBlock(mminfo_t *mm)
482 mmblocktype huge *scan,huge *last;
484 scan = mm->mmhead->next;
488 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
490 MM_FreePtr(scan->useptr, mm);
496 printf("MM_ClearBlock: No purgable blocks!");
500 //==========================================================================
507 = Grabs all space from turbo with malloc/farmalloc
508 = Allocates bufferseg misc buffer
513 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
518 unsigned segstart,seglength,endfree;
523 mm->mmstarted = true;
524 mm->bombonerror = true;
526 // set up the linked list (everything in the free list;
529 mm->mmfree = &(mm->mmblocks[0]);
530 for(i=0;i<MAXBLOCKS-1;i++)
532 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
534 mm->mmblocks[i].next = NULL;
537 // locked block of all memory until we punch out free space
540 mm->mmhead = mm->mmnew; // this will allways be the first node
541 mm->mmnew->start = 0;
542 mm->mmnew->length = 0xffff;
543 mm->mmnew->attributes = LOCKBIT;
544 mm->mmnew->next = NULL;
545 mm->mmrover = mm->mmhead;
549 // get all available near conventional memory segments
551 //---- length=coreleft();
554 start = (void huge *)(mm->nearheap = malloc(length));
556 length -= 16-(FP_OFF(start)&15);
557 length -= SAVENEARHEAP;
558 seglength = length / 16; // now in paragraphs
559 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
560 MML_UseSpace(segstart,seglength, mm);
561 mmi->nearheap = length;
564 // get all available far conventional memory segments
566 //---- length=farcoreleft();
569 start = mm->farheap = halloc(length, 1);
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 MML_UseSpace(mm->EMSpageframe,mm->EMSpagesmapped*0x400, mm);
597 MM_MapEMS(mm); // map in used pages
599 mmi->EMSmem = mm->EMSpagesmapped*0x4000l;
603 // detect XMS and get upper memory blocks
607 for(i = 1;i < __argc;i++)
609 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
610 goto xmsskip; // param NOXMS
612 // 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!
613 if(MML_CheckForXMS(mm))
616 MML_SetupXMS(mm, mmi); // allocate as many UMBs as possible
620 // allocate the misc buffer
623 mm->mmrover = mm->mmhead; // start looking for space after low block
625 MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
628 //==========================================================================
635 = Frees all conventional, EMS, and XMS allocated
640 void MM_Shutdown(mminfo_t *mm)
646 printf("far freed\n");
648 printf("near freed\n");
649 //hfree(mm->hugeheap);
650 //printf("huge freed\n");
651 if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
652 if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
655 //==========================================================================
662 = Allocates an unlocked, unpurgable block
667 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
669 mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
671 unsigned needed,startseg;
673 needed = (size+15)/16; // convert size from bytes to paragraphs
675 MM_GetNewBlock(mm); // fill in start and next after a spot is found
676 mm->mmnew->length = needed;
677 mm->mmnew->useptr = baseptr;
678 mm->mmnew->attributes = BASEATTRIBUTES;
680 for(search = 0; search<3; search++)
683 // first search: try to allocate right after the rover, then on up
684 // second search: search from the head pointer up to the rover
685 // third search: compress memory, then scan from start
686 if(search == 1 && mm->mmrover == mm->mmhead)
692 lastscan = mm->mmrover;
693 scan = mm->mmrover->next;
697 lastscan = mm->mmhead;
698 scan = mm->mmhead->next;
699 endscan = mm->mmrover;
703 lastscan = mm->mmhead;
704 scan = mm->mmhead->next;
709 startseg = lastscan->start + lastscan->length;
711 while(scan != endscan)
713 if(scan->start - startseg >= needed)
716 // got enough space between the end of lastscan and
717 // the start of scan, so throw out anything in the middle
718 // and allocate the new block
720 purge = lastscan->next;
721 lastscan->next = mm->mmnew;
722 mm->mmnew->start = *(unsigned *)baseptr = startseg;
723 mm->mmnew->next = scan;
725 { // free the purgable block
727 MM_FreeBlock(purge, mm);
728 purge = next; // purge another if not at scan
730 mm->mmrover = mm->mmnew;
731 return; // good allocation!
735 // if this block is purge level zero or locked, skip past it
737 if((scan->attributes & LOCKBIT)
738 || !(scan->attributes & PURGEBITS) )
741 startseg = lastscan->start + lastscan->length;
745 scan=scan->next; // look at next line
750 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
755 //==========================================================================
762 = Allocates an unlocked, unpurgable block
767 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
769 mmblocktype huge *scan,huge *last;
774 if(baseptr == mm->mmrover->useptr) // removed the last allocated block
775 mm->mmrover = mm->mmhead;
777 while(scan->useptr != baseptr && scan)
785 printf("MM_FreePtr: Block not found!");
789 last->next = scan->next;
791 MM_FreeBlock(scan, mm);
793 //==========================================================================
796 =====================
800 = Sets the purge level for a block (locked blocks cannot be made purgable)
802 =====================
805 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
807 mmblocktype huge *start;
813 if(mm->mmrover->useptr == baseptr)
816 mm->mmrover = mm->mmrover->next;
819 mm->mmrover = mm->mmhead;
820 else if(mm->mmrover == start)
822 printf("MM_SetPurge: Block not found!");
828 mm->mmrover->attributes &= ~PURGEBITS;
829 mm->mmrover->attributes |= purge;
832 //==========================================================================
835 =====================
839 = Locks / unlocks the block
841 =====================
844 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
846 mmblocktype huge *start;
852 if(mm->mmrover->useptr == baseptr)
855 mm->mmrover = mm->mmrover->next;
858 mm->mmrover = mm->mmhead;
859 else if(mm->mmrover == start)
861 printf("MM_SetLock: Block not found!");
867 mm->mmrover->attributes &= ~LOCKBIT;
868 mm->mmrover->attributes |= locked*LOCKBIT;
871 //==========================================================================
874 =====================
878 = Throws out all purgable stuff and compresses movable blocks
880 =====================
883 void MM_SortMem(mminfo_t *mm)
885 mmblocktype huge *scan,huge *last,huge *next;
886 unsigned start,length,source,dest,oldborder;
890 // lock down a currently playing sound
892 /*++++ playing = SD_SoundPlaying ();
898 playing += STARTPCSOUNDS;
901 playing += STARTADLIBSOUNDS;
904 MM_SetLock(&(memptr)audiosegs[playing],true);
909 // oldborder = bordercolor;
910 // VW_ColorBorder (15);
917 last = NULL; // shut up compiler warning
921 if(scan->attributes & LOCKBIT)
924 // block is locked, so try to pile later blocks right after it
926 start = scan->start + scan->length;
930 if(scan->attributes & PURGEBITS)
933 // throw out the purgable block
936 MM_FreeBlock(scan, mm);
944 // push the non purgable block on top of the last moved block
946 if(scan->start != start)
948 length = scan->length;
949 source = scan->start;
951 while(length > 0xf00)
953 movedata(source,0,dest,0,0xf00*16);
958 movedata(source,0,dest,0,length*16);
961 *(unsigned *)scan->useptr = start;
963 start = scan->start + scan->length;
968 scan = scan->next; // go to next block
971 mm->mmrover = mm->mmhead;
976 // VW_ColorBorder (oldborder);
979 MM_SetLock(&(memptr)audiosegs[playing],false);*/
983 //==========================================================================
987 =====================
991 =====================
994 void MM_ShowMemory(mminfo_t *mm)
996 mmblocktype huge *scan;
997 unsigned color,temp;//, i;
999 char scratch[80],str[10];
1001 //**** VW_SetDefaultColors();
1002 //**** VW_SetLineWidth(40);
1003 //++++mh temp = bufferofs;
1004 //++++mh bufferofs = 0;
1005 //**** VW_SetScreen (0,0);
1015 if(scan->attributes & PURGEBITS)
1016 color = 5; // dark purple = purgable
1018 color = 9; // medium blue = non purgable
1019 if(scan->attributes & LOCKBIT)
1020 color = 12; // red = locked
1021 if(scan->start<=end)
1023 printf("MM_ShowMemory: Memory block order currupted!");
1026 end = scan->start+scan->length-1;
1027 //++++ VW_Hlin(scan->start,(unsigned)end,0,color);
1028 //++++ VW_Plot(scan->start,0,15);
1029 if(scan->next->start > end+1)
1030 //++++ VW_Hlin(end+1,scan->next->start,0,0); // black = free
1033 printf("Location:");
1034 printf("%x\t", scan->start);
1035 strcpy (scratch,"Size:");
1036 ltoa ((long)scan->length*16,str,10);
1037 strcat (scratch,str);
1038 strcat (scratch,"\tOwner:0x");
1039 owner = (unsigned)scan->useptr;
1040 ultoa (owner,str,16);
1041 strcat (scratch,str);
1042 strcat (scratch,"\n");
1043 //++++write (debughandle,scratch,strlen(scratch));
1044 fprintf(stdout, "%s", scratch);
1053 //**** VW_SetLineWidth(64);
1054 //++++mh bufferofs = temp;
1058 //==========================================================================
1062 ======================
1066 = Returns the total free space without purging
1068 ======================
1071 dword MM_UnusedMemory(mminfo_t *mm)
1074 mmblocktype huge *scan;
1081 free += scan->next->start - (scan->start + scan->length);
1089 //==========================================================================
1093 ======================
1097 = Returns the total free space with purging
1099 ======================
1102 dword MM_TotalFree(mminfo_t *mm)
1105 mmblocktype huge *scan;
1112 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1113 free += scan->length;
1114 free += scan->next->start - (scan->start + scan->length);
1122 //==========================================================================
1125 =====================
1129 =====================
1132 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1134 if(MML_CheckForEMS())
1136 printf("EMM %x available\n", mm->EMSVer);
1137 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1138 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1139 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1141 if(MML_CheckForXMS(mm)) printf("XMSaddr=%x\n", *XMSaddr);
1142 printf("near=%lu\n", mmi->nearheap);
1143 printf("far=%lu\n", mmi->farheap);
1144 printf("EMSmem=%lu\n", mmi->EMSmem);
1145 printf("XMSmem=%lu\n", mmi->XMSmem);
1146 printf("mainmem=%lu\n", mmi->mainmem);
1147 printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1148 printf("TotalFree=%lu\n", MM_TotalFree(mm));
1150 // printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1151 // printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1154 //==========================================================================
1157 =====================
1161 =====================
1176 //==========================================================================
1179 =====================
1183 =====================
1186 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1188 mm->bombonerror = bomb;
1191 void MM_GetNewBlock(mminfo_t *mm)
1195 mm->mmnew=mm->mmfree;
1196 mm->mmfree=mm->mmfree->next;
1197 /*if(!(mm->mmnew=mm->mmfree))
1199 printf("MM_GETNEWBLOCK: No free blocks!");
1202 mm->mmfree=mm->mmfree->next;*/
1205 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)