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
177 //++++EXPAND DONG!!!!
180 cmp bx,[freeEMSpages]
182 mov bx,[freeEMSpages]
187 jle getpages // there is only 1,2,3,or 4 pages
188 mov bx,4 // we can't use more than 4 pages
191 mov [EMSpagesmapped],bx
192 mov ah,EMS_ALLOCPAGES // allocate up to 64k of EMS
207 strcpy(str,"MML_SetupEMS: EMS error 0x");
213 mm->totalEMSpages=totalEMSpages;
214 mm->freeEMSpages=freeEMSpages;
215 mm->EMSpageframe=EMSpageframe;
216 mm->EMSpagesmapped=EMSpagesmapped;
217 mm->EMShandle=EMShandle;
224 ======================
228 =======================
231 void MML_ShutdownEMS(mminfo_t *mm)
233 boolean errorflag=false;
234 unsigned EMShandle=mm->EMShandle;
248 if(errorflag==true) printf("MML_ShutdownEMS: Error freeing EMS!"); //++++ add something
256 = Maps the 64k of EMS used by memory manager into the page frame
257 = for general use. This only needs to be called if you are keeping
258 = other things in EMS.
263 unsigned MM_MapEMS(mminfo_t *mm)
265 char str[80],str2[10];
266 unsigned err, EMShandle;
267 boolean errorflag=false;
270 EMShandle=mm->EMShandle;
272 for (i=0;i<mm->EMSpagesmapped;i++)
277 mov bx,[i] // logical page
278 mov al,bl // physical page
279 mov dx,[EMShandle] // handle
291 strcpy(str,"MM_MapEMS: EMS error 0x");
301 //==========================================================================
304 ======================
308 = Check for XMM driver
310 =======================
313 boolean MML_CheckForXMS(mminfo_t *mm)
315 boolean errorflag=false;
321 int 0x2f // query status of installed diver
327 if(errorflag==true) return false;
333 ======================
337 = Try to allocate all upper memory block
339 =======================
342 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
351 mov [WORD PTR XMSaddr],bx
352 mov [WORD PTR XMSaddr+2],es // function pointer to XMS driver
355 mov dx,0xffff // try for largest block possible
356 //mov ax,dx // Set available Kbytes.
357 call [DWORD PTR XMSaddr]
361 cmp bl,0xb0 // error: smaller UMB is available
365 call [DWORD PTR XMSaddr] // DX holds largest available UMB
367 jz done // another error...
374 MML_UseSpace(base,size, mm);
375 mmi->XMSmem += size*16;
376 mm->UMBbase[mm->numUMBs] = base;
378 if(mm->numUMBs < MAXUMBS)
384 ======================
388 ======================
391 void MML_ShutdownXMS(mminfo_t *mm)
396 for (i=0;i<mm->numUMBs;i++)
398 base = mm->UMBbase[i];
403 call [DWORD PTR XMSaddr]
408 //==========================================================================
411 ======================
415 = Marks a range of paragraphs as usable by the memory manager
416 = This is used to mark space for the near heap, far heap, ems page frame,
417 = and upper memory blocks
419 ======================
422 void MML_UseSpace(unsigned segstart, dword seglength, mminfo_t *mm)
424 mmblocktype huge *scan,huge *last;
430 scan = last = mm->mmhead;
431 mm->mmrover = mm->mmhead; // reset rover to start of memory
434 // search for the block that contains the range of segments
436 while(scan->start+scan->length < segstart)
443 // take the given range out of the block
445 oldend = scan->start + scan->length;
446 extra = oldend - (segstart+seglength);
450 segm=(extra%(0xfffflu))-1;
453 //printf("extra=%lu ", extra);
454 //printf("segm=%lu\n", segm);
455 printf("MML_UseSpace: Segment spans two blocks!\n");
459 //++++todo: linked list of segment!
460 //printf("segm=%lu\n", segm);
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
472 if(0xfffflu > extra > 0)
475 mm->mmnew->next = scan->next;
476 scan->next = mm->mmnew;
477 mm->mmnew->start = segstart+seglength;
478 mm->mmnew->length = extra;
479 mm->mmnew->attributes = LOCKBIT;
480 }//else if(segm>0) goto segu;
484 //==========================================================================
491 = We are out of blocks, so free a purgable block
496 void MML_ClearBlock(mminfo_t *mm)
498 mmblocktype huge *scan,huge *last;
500 scan = mm->mmhead->next;
504 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
506 MM_FreePtr(scan->useptr, mm);
512 printf("MM_ClearBlock: No purgable blocks!\n");
516 //==========================================================================
523 = Grabs all space from turbo with malloc/farmalloc
524 = Allocates bufferseg misc buffer
529 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
532 dword length;//,farlen;
534 unsigned segstart,seglength,endfree;
539 mm->mmstarted = true;
540 mm->bombonerror = true;
542 // set up the linked list (everything in the free list;
545 mm->mmfree = &(mm->mmblocks[0]);
546 for(i=0;i<MAXBLOCKS-1;i++)
548 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
550 mm->mmblocks[i].next = NULL;
553 // locked block of all memory until we punch out free space
556 mm->mmhead = mm->mmnew; // this will allways be the first node
557 mm->mmnew->start = 0;
558 mm->mmnew->length = 0xffff; //todo: mm make it fucking massive as fuck!~
559 mm->mmnew->attributes = LOCKBIT;
560 mm->mmnew->next = NULL;
561 mm->mmrover = mm->mmhead;
563 // farlen=_bios_memsize()*1024;
566 // get all available near conventional memory segments
568 //---- length=coreleft();
571 start = (void huge *)(mm->nearheap = malloc(length));
573 length -= 16-(FP_OFF(start)&15);
574 length -= SAVENEARHEAP;
575 seglength = length / 16; // now in paragraphs
576 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
577 MML_UseSpace(segstart,seglength, mm);
578 mmi->nearheap = length;
581 // get all available far conventional memory segments
583 //---- length=farcoreleft();
587 start = mm->farheap = halloc(length, sizeof(dword));
588 //start = mm->farheap = _fmalloc(length);
589 length -= 16-(FP_OFF(start)&15);
590 length -= SAVEFARHEAP;
591 seglength = length / 16; // now in paragraphs
592 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
593 MML_UseSpace(segstart,seglength, mm);
594 mmi->farheap = length;
595 mmi->mainmem = mmi->nearheap + mmi->farheap;
599 // detect EMS and allocate up to 64K at page frame
602 for(i = 1;i < __argc;i++)
604 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
605 goto emsskip; // param NOEMS
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 if(MML_CheckForEMS())
611 MML_SetupEMS(mm); // allocate space
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 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
614 MML_UseSpace(mm->EMSpageframe,((dword)mm->EMSpagesmapped)*0x4000lu, mm);
616 MM_MapEMS(mm); // map in used pages
618 mmi->EMSmem = ((dword)mm->EMSpagesmapped)*0x4000lu;
622 // detect XMS and get upper memory blocks
626 for(i = 1;i < __argc;i++)
628 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
629 goto xmsskip; // param NOXMS
631 // 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!
632 if(MML_CheckForXMS(mm))
635 MML_SetupXMS(mm, mmi); // allocate as many UMBs as possible
639 // allocate the misc buffer
642 mm->mmrover = mm->mmhead; // start looking for space after low block
644 MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
647 //==========================================================================
654 = Frees all conventional, EMS, and XMS allocated
659 void MM_Shutdown(mminfo_t *mm)
665 printf("far freed\n");
667 printf("near freed\n");
668 //hfree(mm->hugeheap);
669 //printf("huge freed\n");
670 if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
671 if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
674 //==========================================================================
681 = Allocates an unlocked, unpurgable block
686 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
688 mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
690 unsigned needed,startseg;
692 needed = (size+15)/16; // convert size from bytes to paragraphs
694 MM_GetNewBlock(mm); // fill in start and next after a spot is found
695 mm->mmnew->length = needed;
696 mm->mmnew->useptr = baseptr;
697 mm->mmnew->attributes = BASEATTRIBUTES;
699 for(search = 0; search<3; search++)
702 // first search: try to allocate right after the rover, then on up
703 // second search: search from the head pointer up to the rover
704 // third search: compress memory, then scan from start
705 if(search == 1 && mm->mmrover == mm->mmhead)
711 lastscan = mm->mmrover;
712 scan = mm->mmrover->next;
716 lastscan = mm->mmhead;
717 scan = mm->mmhead->next;
718 endscan = mm->mmrover;
722 lastscan = mm->mmhead;
723 scan = mm->mmhead->next;
728 startseg = lastscan->start + lastscan->length;
730 while(scan != endscan)
732 if(scan->start - startseg >= needed)
735 // got enough space between the end of lastscan and
736 // the start of scan, so throw out anything in the middle
737 // and allocate the new block
739 purge = lastscan->next;
740 lastscan->next = mm->mmnew;
741 mm->mmnew->start = *(unsigned *)baseptr = startseg;
742 mm->mmnew->next = scan;
744 { // free the purgable block
746 MM_FreeBlock(purge, mm);
747 purge = next; // purge another if not at scan
749 mm->mmrover = mm->mmnew;
750 return; // good allocation!
754 // if this block is purge level zero or locked, skip past it
756 if((scan->attributes & LOCKBIT)
757 || !(scan->attributes & PURGEBITS) )
760 startseg = lastscan->start + lastscan->length;
764 scan=scan->next; // look at next line
769 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
774 //==========================================================================
781 = Allocates an unlocked, unpurgable block
786 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
788 mmblocktype huge *scan,huge *last;
793 if(baseptr == mm->mmrover->useptr) // removed the last allocated block
794 mm->mmrover = mm->mmhead;
796 while(scan->useptr != baseptr && scan)
804 printf("MM_FreePtr: Block not found!");
808 last->next = scan->next;
810 MM_FreeBlock(scan, mm);
812 //==========================================================================
815 =====================
819 = Sets the purge level for a block (locked blocks cannot be made purgable)
821 =====================
824 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
826 mmblocktype huge *start;
832 if(mm->mmrover->useptr == baseptr)
835 mm->mmrover = mm->mmrover->next;
838 mm->mmrover = mm->mmhead;
839 else if(mm->mmrover == start)
841 printf("MM_SetPurge: Block not found!");
847 mm->mmrover->attributes &= ~PURGEBITS;
848 mm->mmrover->attributes |= purge;
851 //==========================================================================
854 =====================
858 = Locks / unlocks the block
860 =====================
863 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
865 mmblocktype huge *start;
871 if(mm->mmrover->useptr == baseptr)
874 mm->mmrover = mm->mmrover->next;
877 mm->mmrover = mm->mmhead;
878 else if(mm->mmrover == start)
880 printf("MM_SetLock: Block not found!");
886 mm->mmrover->attributes &= ~LOCKBIT;
887 mm->mmrover->attributes |= locked*LOCKBIT;
890 //==========================================================================
893 =====================
897 = Throws out all purgable stuff and compresses movable blocks
899 =====================
902 void MM_SortMem(mminfo_t *mm)
904 mmblocktype huge *scan,huge *last,huge *next;
905 unsigned start,length,source,dest,oldborder;
909 // lock down a currently playing sound
911 /*++++ playing = SD_SoundPlaying ();
917 playing += STARTPCSOUNDS;
920 playing += STARTADLIBSOUNDS;
923 MM_SetLock(&(memptr)audiosegs[playing],true);
928 // oldborder = bordercolor;
929 // VW_ColorBorder (15);
936 last = NULL; // shut up compiler warning
940 if(scan->attributes & LOCKBIT)
943 // block is locked, so try to pile later blocks right after it
945 start = scan->start + scan->length;
949 if(scan->attributes & PURGEBITS)
952 // throw out the purgable block
955 MM_FreeBlock(scan, mm);
963 // push the non purgable block on top of the last moved block
965 if(scan->start != start)
967 length = scan->length;
968 source = scan->start;
970 while(length > 0xf00)
972 movedata(source,0,dest,0,0xf00*16);
977 movedata(source,0,dest,0,length*16);
980 *(unsigned *)scan->useptr = start;
982 start = scan->start + scan->length;
987 scan = scan->next; // go to next block
990 mm->mmrover = mm->mmhead;
995 // VW_ColorBorder (oldborder);
998 MM_SetLock(&(memptr)audiosegs[playing],false);*/
1002 //==========================================================================
1006 =====================
1010 =====================
1013 void MM_ShowMemory(mminfo_t *mm)
1015 mmblocktype huge *scan;
1016 unsigned color,temp;//, i;
1018 char scratch[80],str[10];
1020 //**** VW_SetDefaultColors();
1021 //**** VW_SetLineWidth(40);
1022 //++++mh temp = bufferofs;
1023 //++++mh bufferofs = 0;
1024 //**** VW_SetScreen (0,0);
1034 if(scan->attributes & PURGEBITS)
1035 color = 5; // dark purple = purgable
1037 color = 9; // medium blue = non purgable
1038 if(scan->attributes & LOCKBIT)
1039 color = 12; // red = locked
1040 if(scan->start<=end)
1042 printf("MM_ShowMemory: Memory block order currupted!");
1045 end = scan->start+scan->length-1;
1046 //++++ VW_Hlin(scan->start,(unsigned)end,0,color);
1047 //++++ VW_Plot(scan->start,0,15);
1048 if(scan->next->start > end+1)
1049 //++++ VW_Hlin(end+1,scan->next->start,0,0); // black = free
1052 printf("Location:");
1053 printf("%x\t", scan->start);
1054 strcpy (scratch,"Size:");
1055 ltoa ((dword)scan->length*16,str,10);
1056 strcat (scratch,str);
1057 strcat (scratch,"\tOwner:0x");
1058 owner = (unsigned)scan->useptr;
1059 ultoa (owner,str,16);
1060 strcat (scratch,str);
1061 strcat (scratch,"\n");
1062 //++++write (debughandle,scratch,strlen(scratch));
1063 fprintf(stdout, "%s", scratch);
1072 //**** VW_SetLineWidth(64);
1073 //++++mh bufferofs = temp;
1077 //==========================================================================
1081 ======================
1085 = Returns the total free space without purging
1087 ======================
1090 dword MM_UnusedMemory(mminfo_t *mm)
1093 mmblocktype huge *scan;
1100 free += scan->next->start - (scan->start + scan->length);
1108 //==========================================================================
1112 ======================
1116 = Returns the total free space with purging
1118 ======================
1121 dword MM_TotalFree(mminfo_t *mm)
1124 mmblocktype huge *scan;
1131 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1132 free += scan->length;
1133 free += scan->next->start - (scan->start + scan->length);
1141 //==========================================================================
1144 =====================
1148 =====================
1151 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1153 if(MML_CheckForEMS())
1155 printf("EMM %x available\n", mm->EMSVer);
1156 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1157 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1158 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1160 if(MML_CheckForXMS(mm)) printf("XMSaddr=%x\n", *XMSaddr);
1161 printf("near=%lu\n", mmi->nearheap);
1162 printf("far=%lu\n", mmi->farheap);
1163 printf("EMSmem=%lu\n", mmi->EMSmem);
1164 printf("XMSmem=%lu\n", mmi->XMSmem);
1165 printf("mainmem=%lu\n", mmi->mainmem);
1166 printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1167 printf("TotalFree=%lu\n", MM_TotalFree(mm));
1169 // printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1170 // printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1173 //==========================================================================
1176 =====================
1180 =====================
1195 //==========================================================================
1198 =====================
1202 =====================
1205 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1207 mm->bombonerror = bomb;
1210 void MM_GetNewBlock(mminfo_t *mm)
1214 mm->mmnew=mm->mmfree;
1215 mm->mmfree=mm->mmfree->next;
1216 /*if(!(mm->mmnew=mm->mmfree))
1218 printf("MM_GETNEWBLOCK: No free blocks!");
1221 mm->mmfree=mm->mmfree->next;*/
1224 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)