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 static char emmname[] = "EMMXXXX0"; //fix by andrius4669
87 // mov dx,OFFSET emmname
89 //LEA DX, emmname //fix by andrius4669
90 mov dx,OFFSET emmname //fix by andrius4669
92 int 0x21 // try to open EMMXXXX0 device
98 int 0x21 // get device info
106 int 0x21 // get status
112 int 0x21 // close handle
131 ======================
135 =======================
138 unsigned MML_SetupEMS(mminfo_t *mm)
140 char str[80],str2[10];
142 boolean errorflag=false;
145 unsigned int EMSVer = 0;
146 unsigned totalEMSpages,freeEMSpages,EMSpageframe,EMSpagesmapped,EMShandle;
147 totalEMSpages = freeEMSpages = EMSpageframe = EMSpagesmapped = 0;
152 int EMS_INT // make sure EMS hardware is present
160 mov [EMSVer],ax // set EMSVer
161 cmp al,0x32 // only work on ems 3.2 or greater
165 int EMS_INT // find the page frame address
168 mov [EMSpageframe],bx
171 int EMS_INT // find out how much EMS is there
174 mov [totalEMSpages],dx
175 mov [freeEMSpages],bx
177 jz noEMS // no EMS at all to allocate
181 cmp bx,[freeEMSpages]
183 mov bx,[freeEMSpages]
188 jle getpages // there is only 1,2,3,or 4 pages
189 mov bx,4 // we can't use more than 4 pages
192 mov [EMSpagesmapped],bx
193 mov ah,EMS_ALLOCPAGES // allocate up to 64k of EMS
208 strcpy(str,"MML_SetupEMS: EMS error 0x");
214 mm->totalEMSpages=totalEMSpages;
215 mm->freeEMSpages=freeEMSpages;
216 mm->EMSpageframe=EMSpageframe;
217 mm->EMSpagesmapped=EMSpagesmapped;
218 mm->EMShandle=EMShandle;
225 ======================
229 =======================
232 void MML_ShutdownEMS(mminfo_t *mm)
234 boolean errorflag=false;
235 unsigned EMShandle=mm->EMShandle;
249 if(errorflag==true) printf("MML_ShutdownEMS: Error freeing EMS!"); //++++ add something
257 = Maps the 64k of EMS used by memory manager into the page frame
258 = for general use. This only needs to be called if you are keeping
259 = other things in EMS.
264 unsigned MM_MapEMS(mminfo_t *mm)
266 char str[80],str2[10];
267 unsigned err, EMShandle;
268 boolean errorflag=false;
271 EMShandle=mm->EMShandle;
273 for (i=0;i<4/*mm->EMSpagesmapped*/;i++)
278 mov bx,[i] // logical page
279 mov al,bl // physical page
280 mov dx,[EMShandle] // handle
292 strcpy(str,"MM_MapEMS: EMS error 0x");
295 //printf("%s\n",str);
296 printf("FACK! %u\n", err);
304 SUB EMS.MapXPages (PhysicalStart, LogicalStart, NumPages, Handle)
\r
306 'Maps up to 4 logical EMS pages to physical pages in the page frame, where:
\r
308 'PhysicalStart = Physical page first logical page is mapped to
\r
309 'LogicalStart = First logical page to map
\r
310 'NumPages = Number of pages to map (1 to 4)
\r
311 'Handle = EMS handle logical pages are allocated to
\r
313 'Create a buffer containing the page information
\r
314 FOR x = 0 TO NumPages - 1
\r
315 MapInfo$ = MapInfo$ + MKI$(LogicalStart + x) + MKI$(PhysicalStart + x)
\r
318 Regs.ax = &H5000 'Map the pages in the buffer
\r
319 Regs.cx = NumPages 'to the pageframe
\r
321 Regs.ds = VARSEG(MapInfo$)
\r
322 Regs.si = SADD(MapInfo$)
\r
323 InterruptX &H67, Regs, Regs
\r
324 EMS.Error = (Regs.ax AND &HFF00&) \ &H100 'Store the status code
\r
328 void MM_MapXEMS(mminfo_t *mm)
333 //==========================================================================
336 ======================
340 = Check for XMM driver
342 =======================
345 boolean MML_CheckForXMS(mminfo_t *mm)
347 boolean errorflag=false;
353 int 0x2f // query status of installed diver
359 if(errorflag==true) return false;
365 ======================
369 = Try to allocate all upper memory block
371 =======================
374 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
383 mov [WORD PTR XMSaddr],bx
384 mov [WORD PTR XMSaddr+2],es // function pointer to XMS driver
387 mov dx,0xffff // try for largest block possible
388 //mov ax,dx // Set available Kbytes.
389 call [DWORD PTR XMSaddr]
393 cmp bl,0xb0 // error: smaller UMB is available
397 call [DWORD PTR XMSaddr] // DX holds largest available UMB
399 jz done // another error...
406 printf("base=%u ", base); printf("size=%u\n", size);
407 MML_UseSpace(base,size, mm);
408 mmi->XMSmem += size*16;
409 mm->UMBbase[mm->numUMBs] = base;
411 if(mm->numUMBs < MAXUMBS)
417 ======================
421 ======================
424 void MML_ShutdownXMS(mminfo_t *mm)
429 for (i=0;i<mm->numUMBs;i++)
431 base = mm->UMBbase[i];
436 call [DWORD PTR XMSaddr]
441 //==========================================================================
444 ======================
448 = Marks a range of paragraphs as usable by the memory manager
449 = This is used to mark space for the near heap, far heap, ems page frame,
450 = and upper memory blocks
452 ======================
455 void MML_UseSpace(/*d*/word segstart, dword seglength, mminfo_t *mm)
457 mmblocktype huge *scan,huge *last;
462 scan = last = mm->mmhead;
463 mm->mmrover = mm->mmhead; // reset rover to start of memory
466 // search for the block that contains the range of segments
468 while(scan->start+scan->length < segstart)
474 //find out how many blocks it spans!
475 if(seglength>0xffffu)
477 // segm=seglength/0x4000u;
478 segm=seglength/0xffffu;
483 if(segm>1/*extra>0xfffflu*/)
494 //MML_UseSpace(?segstart?, ?length?, mm);
500 //printf("MML_UseSpace: Segment spans two blocks!\n");
504 // take the given range out of the block
506 oldend = scan->start + scan->length;
507 extra = oldend - (segstart+seglength);
509 printf("segm=%u ", segm);
510 printf("ex=%lu ", extra);
511 printf("start+seglen=%lu ", segstart+seglength);
512 printf("len=%u ", scan->length);
513 printf("segsta=%x ", segstart);
514 printf("seglen=%lu\n", seglength);
517 //++++todo: linked list of segment!
518 //printf("segm=%lu\n", segm);
519 if(segstart == scan->start)
521 last->next = scan->next; // unlink block
522 MM_FreeBlock(scan, mm);
526 scan->length = segstart-scan->start; // shorten block
533 mm->mmnew->next = scan->next;
534 scan->next = mm->mmnew;
535 mm->mmnew->start = segstart+seglength;
536 mm->mmnew->length = extra;
537 mm->mmnew->attributes = LOCKBIT;
538 }//else if(segm>0) goto segu;
542 //==========================================================================
549 = We are out of blocks, so free a purgable block
554 void MML_ClearBlock(mminfo_t *mm)
556 mmblocktype huge *scan,huge *last;
558 scan = mm->mmhead->next;
562 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
564 MM_FreePtr(scan->useptr, mm);
570 printf("MM_ClearBlock: No purgable blocks!\n");
574 //==========================================================================
581 = Grabs all space from turbo with malloc/farmalloc
582 = Allocates bufferseg misc buffer
587 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
592 unsigned segstart,seglength,endfree;
597 mm->mmstarted = true;
598 mm->bombonerror = true;
600 // set up the linked list (everything in the free list;
603 mm->mmfree = &(mm->mmblocks[0]);
604 for(i=0;i<MAXBLOCKS-1;i++)
606 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
608 mm->mmblocks[i].next = NULL;
611 // locked block of all memory until we punch out free space
614 mm->mmhead = mm->mmnew; // this will allways be the first node
615 mm->mmnew->start = 0;
616 mm->mmnew->length = 0xffff;
617 mm->mmnew->attributes = LOCKBIT;
618 mm->mmnew->next = NULL;
619 mm->mmrover = mm->mmhead;
621 // farlen=_bios_memsize()*1024;
624 // get all available near conventional memory segments
626 //---- length=coreleft();
629 start = (void huge *)(mm->nearheap = malloc(length));
630 length -= 16-(FP_OFF(start)&15);
631 length -= SAVENEARHEAP;
632 seglength = length / 16; // now in paragraphs
633 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
634 MML_UseSpace(segstart,seglength, mm);
635 mmi->nearheap = length;
636 //printf("near heap ok!\n");
639 // get all available far conventional memory segments
641 //---- length=farcoreleft();
644 start = mm->farheap = halloc(length, sizeof(byte));
645 //start = mm->farheap = _fmalloc(length);
646 length -= 16-(FP_OFF(start)&15);
647 length -= SAVEFARHEAP;
648 seglength = length / 16; // now in paragraphs
649 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
650 MML_UseSpace(segstart,seglength, mm);
651 mmi->farheap = length;
652 mmi->mainmem = mmi->nearheap + mmi->farheap;
653 //printf("far heap ok!\n");
657 // detect EMS and allocate up to 64K at page frame
659 printf("EMS!\n\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!
661 for(i = 1;i < __argc;i++)
663 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
664 goto emsskip; // param NOEMS
666 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!
667 if(MML_CheckForEMS())
670 MML_SetupEMS(mm); // allocate space
671 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!
672 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
673 MML_UseSpace(mm->EMSpageframe,(mm->EMSpagesmapped)*0x4000lu, mm);
675 MM_MapEMS(mm); // map in used pages
677 mmi->EMSmem = (mm->EMSpagesmapped)*0x4000lu;
681 // detect XMS and get upper memory blocks
685 for(i = 1;i < __argc;i++)
687 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
688 goto xmsskip; // param NOXMS
690 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!
691 if(MML_CheckForXMS(mm))
694 //MML_SetupXMS(mm, mmi); // allocate as many UMBs as possible
698 // allocate the misc buffer
701 mm->mmrover = mm->mmhead; // start looking for space after low block
703 MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
706 //==========================================================================
713 = Frees all conventional, EMS, and XMS allocated
718 void MM_Shutdown(mminfo_t *mm)
724 printf("far freed\n");
726 printf("near freed\n");
727 //hfree(mm->hugeheap);
728 //printf("huge freed\n");
729 if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
730 if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
733 //==========================================================================
740 = Allocates an unlocked, unpurgable block
745 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
747 mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
749 unsigned needed,startseg;
751 needed = (size+15)/16; // convert size from bytes to paragraphs
753 MM_GetNewBlock(mm); // fill in start and next after a spot is found
754 mm->mmnew->length = needed;
755 mm->mmnew->useptr = baseptr;
756 mm->mmnew->attributes = BASEATTRIBUTES;
758 for(search = 0; search<3; search++)
761 // first search: try to allocate right after the rover, then on up
762 // second search: search from the head pointer up to the rover
763 // third search: compress memory, then scan from start
764 if(search == 1 && mm->mmrover == mm->mmhead)
770 lastscan = mm->mmrover;
771 scan = mm->mmrover->next;
775 lastscan = mm->mmhead;
776 scan = mm->mmhead->next;
777 endscan = mm->mmrover;
781 lastscan = mm->mmhead;
782 scan = mm->mmhead->next;
787 startseg = lastscan->start + lastscan->length;
789 while(scan != endscan)
791 if(scan->start - startseg >= needed)
794 // got enough space between the end of lastscan and
795 // the start of scan, so throw out anything in the middle
796 // and allocate the new block
798 purge = lastscan->next;
799 lastscan->next = mm->mmnew;
800 mm->mmnew->start = *(unsigned *)baseptr = startseg;
801 mm->mmnew->next = scan;
803 { // free the purgable block
805 MM_FreeBlock(purge, mm);
806 purge = next; // purge another if not at scan
808 mm->mmrover = mm->mmnew;
809 return; // good allocation!
813 // if this block is purge level zero or locked, skip past it
815 if((scan->attributes & LOCKBIT)
816 || !(scan->attributes & PURGEBITS) )
819 startseg = lastscan->start + lastscan->length;
823 scan=scan->next; // look at next line
828 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
833 //==========================================================================
840 = Allocates an unlocked, unpurgable block
845 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
847 mmblocktype huge *scan,huge *last;
852 if(baseptr == mm->mmrover->useptr) // removed the last allocated block
853 mm->mmrover = mm->mmhead;
855 while(scan->useptr != baseptr && scan)
863 printf("MM_FreePtr: Block not found!");
867 last->next = scan->next;
869 MM_FreeBlock(scan, mm);
871 //==========================================================================
874 =====================
878 = Sets the purge level for a block (locked blocks cannot be made purgable)
880 =====================
883 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
885 mmblocktype huge *start;
891 if(mm->mmrover->useptr == baseptr)
894 mm->mmrover = mm->mmrover->next;
897 mm->mmrover = mm->mmhead;
898 else if(mm->mmrover == start)
900 printf("MM_SetPurge: Block not found!");
906 mm->mmrover->attributes &= ~PURGEBITS;
907 mm->mmrover->attributes |= purge;
910 //==========================================================================
913 =====================
917 = Locks / unlocks the block
919 =====================
922 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
924 mmblocktype huge *start;
930 if(mm->mmrover->useptr == baseptr)
933 mm->mmrover = mm->mmrover->next;
936 mm->mmrover = mm->mmhead;
937 else if(mm->mmrover == start)
939 printf("MM_SetLock: Block not found!");
945 mm->mmrover->attributes &= ~LOCKBIT;
946 mm->mmrover->attributes |= locked*LOCKBIT;
949 //==========================================================================
952 =====================
956 = Throws out all purgable stuff and compresses movable blocks
958 =====================
961 void MM_SortMem(mminfo_t *mm)
963 mmblocktype huge *scan,huge *last,huge *next;
964 unsigned start,length,source,dest,oldborder;
968 // lock down a currently playing sound
970 /*++++ playing = SD_SoundPlaying ();
976 playing += STARTPCSOUNDS;
979 playing += STARTADLIBSOUNDS;
982 MM_SetLock(&(memptr)audiosegs[playing],true);
987 // oldborder = bordercolor;
988 // VW_ColorBorder (15);
995 last = NULL; // shut up compiler warning
999 if(scan->attributes & LOCKBIT)
1002 // block is locked, so try to pile later blocks right after it
1004 start = scan->start + scan->length;
1008 if(scan->attributes & PURGEBITS)
1011 // throw out the purgable block
1014 MM_FreeBlock(scan, mm);
1022 // push the non purgable block on top of the last moved block
1024 if(scan->start != start)
1026 length = scan->length;
1027 source = scan->start;
1029 while(length > 0xf00)
1031 movedata(source,0,dest,0,0xf00*16);
1036 movedata(source,0,dest,0,length*16);
1038 scan->start = start;
1039 *(unsigned *)scan->useptr = start;
1041 start = scan->start + scan->length;
1046 scan = scan->next; // go to next block
1049 mm->mmrover = mm->mmhead;
1054 // VW_ColorBorder (oldborder);
1057 MM_SetLock(&(memptr)audiosegs[playing],false);*/
1061 //==========================================================================
1065 =====================
1069 =====================
1072 void MM_ShowMemory(mminfo_t *mm)
1074 mmblocktype huge *scan;
1075 unsigned color,temp;
1077 char scratch[160],str[16];
1079 //**** VW_SetDefaultColors();
1080 //**** VW_SetLineWidth(40);
1081 //++++mh temp = bufferofs;
1082 //++++mh bufferofs = 0;
1083 //**** VW_SetScreen (0,0);
1093 if(scan->attributes & PURGEBITS)
1094 color = 5; // dark purple = purgable
1096 color = 9; // medium blue = non purgable
1097 if(scan->attributes & LOCKBIT)
1098 color = 12; // red = locked
1099 if(scan->start<=end)
1101 printf("\nMM_ShowMemory: Memory block order currupted!\n");
1104 end = scan->start+scan->length-1;
1105 //++++ VW_Hlin(scan->start,(unsigned)end,0,color);
1106 //++++ VW_Plot(scan->start,0,15);
1107 if(scan->next->start > end+1)
1108 //++++ VW_Hlin(end+1,scan->next->start,0,0); // black = free
1111 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!
1112 strcpy(scratch,"Location:");
1113 ultoa (scan->start,str,16);
1114 strcat (scratch,str);
1115 strcat (scratch,"\tSize:");
1116 ltoa ((dword)scan->length*16,str,10);
1117 strcat (scratch,str);
1118 strcat (scratch,"\tOwner:0x");
1119 owner = (unsigned)scan->useptr;
1120 ultoa (owner,str,16);
1121 strcat (scratch,str);
1122 strcat (scratch,"\n");
1123 //++++write (debughandle,scratch,strlen(scratch));
1124 fprintf(stdout, "%s", scratch);
1133 //**** VW_SetLineWidth(64);
1134 //++++mh bufferofs = temp;
1138 //==========================================================================
1142 ======================
1146 = Returns the total free space without purging
1148 ======================
1151 dword MM_UnusedMemory(mminfo_t *mm)
1154 mmblocktype huge *scan;
1161 free += scan->next->start - (scan->start + scan->length);
1169 //==========================================================================
1173 ======================
1177 = Returns the total free space with purging
1179 ======================
1182 dword MM_TotalFree(mminfo_t *mm)
1185 mmblocktype huge *scan;
1192 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1193 free += scan->length;
1194 free += scan->next->start - (scan->start + scan->length);
1202 //==========================================================================
1205 =====================
1209 =====================
1212 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1214 if(MML_CheckForEMS())
1216 printf("EMM %x available\n", mm->EMSVer);
1217 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1218 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1219 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1221 if(MML_CheckForXMS(mm)) printf("XMSaddr=%Fp\n", *XMSaddr);
1222 printf("near=%lu\n", mmi->nearheap);
1223 printf("far=%lu\n", mmi->farheap);
1224 printf("EMSmem=%lu\n", mmi->EMSmem);
1225 printf("XMSmem=%lu\n", mmi->XMSmem);
1226 printf("mainmem=%lu\n", mmi->mainmem);
1227 printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1228 printf("TotalFree=%lu\n", MM_TotalFree(mm));
1230 // printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1231 // printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1234 //==========================================================================
1237 =====================
1241 =====================
1256 //==========================================================================
1259 =====================
1263 =====================
1266 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1268 mm->bombonerror = bomb;
1271 void MM_GetNewBlock(mminfo_t *mm)
1275 mm->mmnew=mm->mmfree;
1276 mm->mmfree=mm->mmfree->next;
1277 /*if(!(mm->mmnew=mm->mmfree))
1279 printf("MM_GETNEWBLOCK: No free blocks!");
1282 mm->mmfree=mm->mmfree->next;*/
1285 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1292 void MM_seguin(void)
1303 void MM_segude(void)
1312 pull data from far and put it into ds var