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<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");
296 printf("FACK! %u\n", err);
303 //==========================================================================
306 ======================
310 = Check for XMM driver
312 =======================
315 boolean MML_CheckForXMS(mminfo_t *mm)
317 boolean errorflag=false;
323 int 0x2f // query status of installed diver
329 if(errorflag==true) return false;
335 ======================
339 = Try to allocate all upper memory block
341 =======================
344 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
353 mov [WORD PTR XMSaddr],bx
354 mov [WORD PTR XMSaddr+2],es // function pointer to XMS driver
357 mov dx,0xffff // try for largest block possible
358 //mov ax,dx // Set available Kbytes.
359 call [DWORD PTR XMSaddr]
363 cmp bl,0xb0 // error: smaller UMB is available
367 call [DWORD PTR XMSaddr] // DX holds largest available UMB
369 jz done // another error...
376 printf("base=%u ", base); printf("size=%u\n", size);
377 MML_UseSpace(base,size, mm);
378 mmi->XMSmem += size*16;
379 mm->UMBbase[mm->numUMBs] = base;
381 if(mm->numUMBs < MAXUMBS)
387 ======================
391 ======================
394 void MML_ShutdownXMS(mminfo_t *mm)
399 for (i=0;i<mm->numUMBs;i++)
401 base = mm->UMBbase[i];
406 call [DWORD PTR XMSaddr]
411 //==========================================================================
414 ======================
418 = Marks a range of paragraphs as usable by the memory manager
419 = This is used to mark space for the near heap, far heap, ems page frame,
420 = and upper memory blocks
422 ======================
425 void MML_UseSpace(/*d*/word segstart, dword seglength, mminfo_t *mm)
427 mmblocktype huge *scan,huge *last;
432 scan = last = mm->mmhead;
433 mm->mmrover = mm->mmhead; // reset rover to start of memory
436 // search for the block that contains the range of segments
438 while(scan->start+scan->length < segstart)
444 //find out how many blocks it spans!
445 if(seglength>0xffffu)
447 // segm=seglength/0x4000u;
448 segm=seglength/0xffffu;
453 if(segm>1/*extra>0xfffflu*/)
464 //MML_UseSpace(?segstart?, ?length?, mm);
470 //printf("MML_UseSpace: Segment spans two blocks!\n");
474 // take the given range out of the block
476 oldend = scan->start + scan->length;
477 extra = oldend - (segstart+seglength);
479 printf("segm=%u ", segm);
480 printf("ex=%lu ", extra);
481 printf("start+seglen=%lu ", segstart+seglength);
482 printf("len=%u ", scan->length);
483 printf("segsta=%x ", segstart);
484 printf("seglen=%lu\n", seglength);
487 //++++todo: linked list of segment!
488 //printf("segm=%lu\n", segm);
489 if(segstart == scan->start)
491 last->next = scan->next; // unlink block
492 MM_FreeBlock(scan, mm);
496 scan->length = segstart-scan->start; // shorten block
503 mm->mmnew->next = scan->next;
504 scan->next = mm->mmnew;
505 mm->mmnew->start = segstart+seglength;
506 mm->mmnew->length = extra;
507 mm->mmnew->attributes = LOCKBIT;
508 }//else if(segm>0) goto segu;
512 //==========================================================================
519 = We are out of blocks, so free a purgable block
524 void MML_ClearBlock(mminfo_t *mm)
526 mmblocktype huge *scan,huge *last;
528 scan = mm->mmhead->next;
532 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
534 MM_FreePtr(scan->useptr, mm);
540 printf("MM_ClearBlock: No purgable blocks!\n");
544 //==========================================================================
551 = Grabs all space from turbo with malloc/farmalloc
552 = Allocates bufferseg misc buffer
557 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
562 unsigned segstart,seglength,endfree;
567 mm->mmstarted = true;
568 mm->bombonerror = true;
570 // set up the linked list (everything in the free list;
573 mm->mmfree = &(mm->mmblocks[0]);
574 for(i=0;i<MAXBLOCKS-1;i++)
576 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
578 mm->mmblocks[i].next = NULL;
581 // locked block of all memory until we punch out free space
584 mm->mmhead = mm->mmnew; // this will allways be the first node
585 mm->mmnew->start = 0;
586 mm->mmnew->length = 0xffff;
587 mm->mmnew->attributes = LOCKBIT;
588 mm->mmnew->next = NULL;
589 mm->mmrover = mm->mmhead;
591 // farlen=_bios_memsize()*1024;
594 // get all available near conventional memory segments
596 //---- length=coreleft();
599 start = (void huge *)(mm->nearheap = malloc(length));
600 length -= 16-(FP_OFF(start)&15);
601 length -= SAVENEARHEAP;
602 seglength = length / 16; // now in paragraphs
603 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
604 MML_UseSpace(segstart,seglength, mm);
605 mmi->nearheap = length;
606 //printf("near heap ok!\n");
609 // get all available far conventional memory segments
611 //---- length=farcoreleft();
614 start = mm->farheap = halloc(length, sizeof(byte));
615 //start = mm->farheap = _fmalloc(length);
616 length -= 16-(FP_OFF(start)&15);
617 length -= SAVEFARHEAP;
618 seglength = length / 16; // now in paragraphs
619 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
620 MML_UseSpace(segstart,seglength, mm);
621 mmi->farheap = length;
622 mmi->mainmem = mmi->nearheap + mmi->farheap;
623 //printf("far heap ok!\n");
627 // detect EMS and allocate up to 64K at page frame
629 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!
631 for(i = 1;i < __argc;i++)
633 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
634 goto emsskip; // param NOEMS
636 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!
637 if(MML_CheckForEMS())
640 MML_SetupEMS(mm); // allocate space
641 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!
642 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
643 MML_UseSpace(mm->EMSpageframe,(mm->EMSpagesmapped)*0x4000lu, mm);
645 MM_MapEMS(mm); // map in used pages
647 mmi->EMSmem = (mm->EMSpagesmapped)*0x4000lu;
651 // detect XMS and get upper memory blocks
655 for(i = 1;i < __argc;i++)
657 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
658 goto xmsskip; // param NOXMS
660 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!
661 if(MML_CheckForXMS(mm))
664 //MML_SetupXMS(mm, mmi); // allocate as many UMBs as possible
668 // allocate the misc buffer
671 mm->mmrover = mm->mmhead; // start looking for space after low block
673 MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
676 //==========================================================================
683 = Frees all conventional, EMS, and XMS allocated
688 void MM_Shutdown(mminfo_t *mm)
694 printf("far freed\n");
696 printf("near freed\n");
697 //hfree(mm->hugeheap);
698 //printf("huge freed\n");
699 if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
700 if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
703 //==========================================================================
710 = Allocates an unlocked, unpurgable block
715 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
717 mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
719 unsigned needed,startseg;
721 needed = (size+15)/16; // convert size from bytes to paragraphs
723 MM_GetNewBlock(mm); // fill in start and next after a spot is found
724 mm->mmnew->length = needed;
725 mm->mmnew->useptr = baseptr;
726 mm->mmnew->attributes = BASEATTRIBUTES;
728 for(search = 0; search<3; search++)
731 // first search: try to allocate right after the rover, then on up
732 // second search: search from the head pointer up to the rover
733 // third search: compress memory, then scan from start
734 if(search == 1 && mm->mmrover == mm->mmhead)
740 lastscan = mm->mmrover;
741 scan = mm->mmrover->next;
745 lastscan = mm->mmhead;
746 scan = mm->mmhead->next;
747 endscan = mm->mmrover;
751 lastscan = mm->mmhead;
752 scan = mm->mmhead->next;
757 startseg = lastscan->start + lastscan->length;
759 while(scan != endscan)
761 if(scan->start - startseg >= needed)
764 // got enough space between the end of lastscan and
765 // the start of scan, so throw out anything in the middle
766 // and allocate the new block
768 purge = lastscan->next;
769 lastscan->next = mm->mmnew;
770 mm->mmnew->start = *(unsigned *)baseptr = startseg;
771 mm->mmnew->next = scan;
773 { // free the purgable block
775 MM_FreeBlock(purge, mm);
776 purge = next; // purge another if not at scan
778 mm->mmrover = mm->mmnew;
779 return; // good allocation!
783 // if this block is purge level zero or locked, skip past it
785 if((scan->attributes & LOCKBIT)
786 || !(scan->attributes & PURGEBITS) )
789 startseg = lastscan->start + lastscan->length;
793 scan=scan->next; // look at next line
798 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
803 //==========================================================================
810 = Allocates an unlocked, unpurgable block
815 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
817 mmblocktype huge *scan,huge *last;
822 if(baseptr == mm->mmrover->useptr) // removed the last allocated block
823 mm->mmrover = mm->mmhead;
825 while(scan->useptr != baseptr && scan)
833 printf("MM_FreePtr: Block not found!");
837 last->next = scan->next;
839 MM_FreeBlock(scan, mm);
841 //==========================================================================
844 =====================
848 = Sets the purge level for a block (locked blocks cannot be made purgable)
850 =====================
853 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
855 mmblocktype huge *start;
861 if(mm->mmrover->useptr == baseptr)
864 mm->mmrover = mm->mmrover->next;
867 mm->mmrover = mm->mmhead;
868 else if(mm->mmrover == start)
870 printf("MM_SetPurge: Block not found!");
876 mm->mmrover->attributes &= ~PURGEBITS;
877 mm->mmrover->attributes |= purge;
880 //==========================================================================
883 =====================
887 = Locks / unlocks the block
889 =====================
892 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
894 mmblocktype huge *start;
900 if(mm->mmrover->useptr == baseptr)
903 mm->mmrover = mm->mmrover->next;
906 mm->mmrover = mm->mmhead;
907 else if(mm->mmrover == start)
909 printf("MM_SetLock: Block not found!");
915 mm->mmrover->attributes &= ~LOCKBIT;
916 mm->mmrover->attributes |= locked*LOCKBIT;
919 //==========================================================================
922 =====================
926 = Throws out all purgable stuff and compresses movable blocks
928 =====================
931 void MM_SortMem(mminfo_t *mm)
933 mmblocktype huge *scan,huge *last,huge *next;
934 unsigned start,length,source,dest,oldborder;
938 // lock down a currently playing sound
940 /*++++ playing = SD_SoundPlaying ();
946 playing += STARTPCSOUNDS;
949 playing += STARTADLIBSOUNDS;
952 MM_SetLock(&(memptr)audiosegs[playing],true);
957 // oldborder = bordercolor;
958 // VW_ColorBorder (15);
965 last = NULL; // shut up compiler warning
969 if(scan->attributes & LOCKBIT)
972 // block is locked, so try to pile later blocks right after it
974 start = scan->start + scan->length;
978 if(scan->attributes & PURGEBITS)
981 // throw out the purgable block
984 MM_FreeBlock(scan, mm);
992 // push the non purgable block on top of the last moved block
994 if(scan->start != start)
996 length = scan->length;
997 source = scan->start;
999 while(length > 0xf00)
1001 movedata(source,0,dest,0,0xf00*16);
1006 movedata(source,0,dest,0,length*16);
1008 scan->start = start;
1009 *(unsigned *)scan->useptr = start;
1011 start = scan->start + scan->length;
1016 scan = scan->next; // go to next block
1019 mm->mmrover = mm->mmhead;
1024 // VW_ColorBorder (oldborder);
1027 MM_SetLock(&(memptr)audiosegs[playing],false);*/
1031 //==========================================================================
1035 =====================
1039 =====================
1042 void MM_ShowMemory(mminfo_t *mm)
1044 mmblocktype huge *scan;
1045 unsigned color,temp;
1047 char scratch[160],str[16];
1049 //**** VW_SetDefaultColors();
1050 //**** VW_SetLineWidth(40);
1051 //++++mh temp = bufferofs;
1052 //++++mh bufferofs = 0;
1053 //**** VW_SetScreen (0,0);
1063 if(scan->attributes & PURGEBITS)
1064 color = 5; // dark purple = purgable
1066 color = 9; // medium blue = non purgable
1067 if(scan->attributes & LOCKBIT)
1068 color = 12; // red = locked
1069 if(scan->start<=end)
1071 printf("\nMM_ShowMemory: Memory block order currupted!\n");
1074 end = scan->start+scan->length-1;
1075 //++++ VW_Hlin(scan->start,(unsigned)end,0,color);
1076 //++++ VW_Plot(scan->start,0,15);
1077 if(scan->next->start > end+1)
1078 //++++ VW_Hlin(end+1,scan->next->start,0,0); // black = free
1081 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!
1082 strcpy(scratch,"Location:");
1083 ultoa (scan->start,str,16);
1084 strcat (scratch,str);
1085 strcat (scratch,"\tSize:");
1086 ltoa ((dword)scan->length*16,str,10);
1087 strcat (scratch,str);
1088 strcat (scratch,"\tOwner:0x");
1089 owner = (unsigned)scan->useptr;
1090 ultoa (owner,str,16);
1091 strcat (scratch,str);
1092 strcat (scratch,"\n");
1093 //++++write (debughandle,scratch,strlen(scratch));
1094 fprintf(stdout, "%s", scratch);
1103 //**** VW_SetLineWidth(64);
1104 //++++mh bufferofs = temp;
1108 //==========================================================================
1112 ======================
1116 = Returns the total free space without purging
1118 ======================
1121 dword MM_UnusedMemory(mminfo_t *mm)
1124 mmblocktype huge *scan;
1131 free += scan->next->start - (scan->start + scan->length);
1139 //==========================================================================
1143 ======================
1147 = Returns the total free space with purging
1149 ======================
1152 dword MM_TotalFree(mminfo_t *mm)
1155 mmblocktype huge *scan;
1162 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1163 free += scan->length;
1164 free += scan->next->start - (scan->start + scan->length);
1172 //==========================================================================
1175 =====================
1179 =====================
1182 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1184 if(MML_CheckForEMS())
1186 printf("EMM %x available\n", mm->EMSVer);
1187 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1188 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1189 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1191 if(MML_CheckForXMS(mm)) printf("XMSaddr=%Fp\n", *XMSaddr);
1192 printf("near=%lu\n", mmi->nearheap);
1193 printf("far=%lu\n", mmi->farheap);
1194 printf("EMSmem=%lu\n", mmi->EMSmem);
1195 printf("XMSmem=%lu\n", mmi->XMSmem);
1196 printf("mainmem=%lu\n", mmi->mainmem);
1197 printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1198 printf("TotalFree=%lu\n", MM_TotalFree(mm));
1200 // printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1201 // printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1204 //==========================================================================
1207 =====================
1211 =====================
1226 //==========================================================================
1229 =====================
1233 =====================
1236 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1238 mm->bombonerror = bomb;
1241 void MM_GetNewBlock(mminfo_t *mm)
1245 mm->mmnew=mm->mmfree;
1246 mm->mmfree=mm->mmfree->next;
1247 /*if(!(mm->mmnew=mm->mmfree))
1249 printf("MM_GETNEWBLOCK: No free blocks!");
1252 mm->mmfree=mm->mmfree->next;*/
1255 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1262 void MM_seguin(void)
1273 void MM_segude(void)
1282 pull data from far and put it into ds var