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
329 //==========================================================================
332 ======================
336 = Check for XMM driver
338 =======================
341 boolean MML_CheckForXMS(mminfo_t *mm)
343 boolean errorflag=false;
349 int 0x2f // query status of installed diver
355 if(errorflag==true) return false;
361 ======================
365 = Try to allocate all upper memory block
367 =======================
370 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
379 mov [WORD PTR XMSaddr],bx
380 mov [WORD PTR XMSaddr+2],es // function pointer to XMS driver
383 mov dx,0xffff // try for largest block possible
384 //mov ax,dx // Set available Kbytes.
385 call [DWORD PTR XMSaddr]
389 cmp bl,0xb0 // error: smaller UMB is available
393 call [DWORD PTR XMSaddr] // DX holds largest available UMB
395 jz done // another error...
402 printf("base=%u ", base); printf("size=%u\n", size);
403 MML_UseSpace(base,size, mm);
404 mmi->XMSmem += size*16;
405 mm->UMBbase[mm->numUMBs] = base;
407 if(mm->numUMBs < MAXUMBS)
413 ======================
417 ======================
420 void MML_ShutdownXMS(mminfo_t *mm)
425 for (i=0;i<mm->numUMBs;i++)
427 base = mm->UMBbase[i];
432 call [DWORD PTR XMSaddr]
437 //==========================================================================
440 ======================
444 = Marks a range of paragraphs as usable by the memory manager
445 = This is used to mark space for the near heap, far heap, ems page frame,
446 = and upper memory blocks
448 ======================
451 void MML_UseSpace(/*d*/word segstart, dword seglength, mminfo_t *mm)
453 mmblocktype huge *scan,huge *last;
458 scan = last = mm->mmhead;
459 mm->mmrover = mm->mmhead; // reset rover to start of memory
462 // search for the block that contains the range of segments
464 while(scan->start+scan->length < segstart)
470 //find out how many blocks it spans!
471 if(seglength>0xffffu)
473 // segm=seglength/0x4000u;
474 segm=seglength/0xffffu;
479 if(segm>1/*extra>0xfffflu*/)
490 //MML_UseSpace(?segstart?, ?length?, mm);
496 //printf("MML_UseSpace: Segment spans two blocks!\n");
500 // take the given range out of the block
502 oldend = scan->start + scan->length;
503 extra = oldend - (segstart+seglength);
505 printf("segm=%u ", segm);
506 printf("ex=%lu ", extra);
507 printf("start+seglen=%lu ", segstart+seglength);
508 printf("len=%u ", scan->length);
509 printf("segsta=%x ", segstart);
510 printf("seglen=%lu\n", seglength);
513 //++++todo: linked list of segment!
514 //printf("segm=%lu\n", segm);
515 if(segstart == scan->start)
517 last->next = scan->next; // unlink block
518 MM_FreeBlock(scan, mm);
522 scan->length = segstart-scan->start; // shorten block
529 mm->mmnew->next = scan->next;
530 scan->next = mm->mmnew;
531 mm->mmnew->start = segstart+seglength;
532 mm->mmnew->length = extra;
533 mm->mmnew->attributes = LOCKBIT;
534 }//else if(segm>0) goto segu;
538 //==========================================================================
545 = We are out of blocks, so free a purgable block
550 void MML_ClearBlock(mminfo_t *mm)
552 mmblocktype huge *scan,huge *last;
554 scan = mm->mmhead->next;
558 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
560 MM_FreePtr(scan->useptr, mm);
566 printf("MM_ClearBlock: No purgable blocks!\n");
570 //==========================================================================
577 = Grabs all space from turbo with malloc/farmalloc
578 = Allocates bufferseg misc buffer
583 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
588 unsigned segstart,seglength,endfree;
593 mm->mmstarted = true;
594 mm->bombonerror = true;
596 // set up the linked list (everything in the free list;
599 mm->mmfree = &(mm->mmblocks[0]);
600 for(i=0;i<MAXBLOCKS-1;i++)
602 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
604 mm->mmblocks[i].next = NULL;
607 // locked block of all memory until we punch out free space
610 mm->mmhead = mm->mmnew; // this will allways be the first node
611 mm->mmnew->start = 0;
612 mm->mmnew->length = 0xffff;
613 mm->mmnew->attributes = LOCKBIT;
614 mm->mmnew->next = NULL;
615 mm->mmrover = mm->mmhead;
617 // farlen=_bios_memsize()*1024;
620 // get all available near conventional memory segments
622 //---- length=coreleft();
625 start = (void huge *)(mm->nearheap = malloc(length));
626 length -= 16-(FP_OFF(start)&15);
627 length -= SAVENEARHEAP;
628 seglength = length / 16; // now in paragraphs
629 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
630 MML_UseSpace(segstart,seglength, mm);
631 mmi->nearheap = length;
632 //printf("near heap ok!\n");
635 // get all available far conventional memory segments
637 //---- length=farcoreleft();
640 start = mm->farheap = halloc(length, sizeof(byte));
641 //start = mm->farheap = _fmalloc(length);
642 length -= 16-(FP_OFF(start)&15);
643 length -= SAVEFARHEAP;
644 seglength = length / 16; // now in paragraphs
645 segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
646 MML_UseSpace(segstart,seglength, mm);
647 mmi->farheap = length;
648 mmi->mainmem = mmi->nearheap + mmi->farheap;
649 //printf("far heap ok!\n");
653 // detect EMS and allocate up to 64K at page frame
655 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!
657 for(i = 1;i < __argc;i++)
659 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
660 goto emsskip; // param NOEMS
662 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!
663 if(MML_CheckForEMS())
666 MML_SetupEMS(mm); // allocate space
667 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!
668 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
669 MML_UseSpace(mm->EMSpageframe,(mm->EMSpagesmapped)*0x4000lu, mm);
671 MM_MapEMS(mm); // map in used pages
673 mmi->EMSmem = (mm->EMSpagesmapped)*0x4000lu;
677 // detect XMS and get upper memory blocks
681 for(i = 1;i < __argc;i++)
683 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
684 goto xmsskip; // param NOXMS
686 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!
687 if(MML_CheckForXMS(mm))
690 //MML_SetupXMS(mm, mmi); // allocate as many UMBs as possible
694 // allocate the misc buffer
697 mm->mmrover = mm->mmhead; // start looking for space after low block
699 MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
702 //==========================================================================
709 = Frees all conventional, EMS, and XMS allocated
714 void MM_Shutdown(mminfo_t *mm)
720 printf("far freed\n");
722 printf("near freed\n");
723 //hfree(mm->hugeheap);
724 //printf("huge freed\n");
725 if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
726 if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
729 //==========================================================================
736 = Allocates an unlocked, unpurgable block
741 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
743 mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
745 unsigned needed,startseg;
747 needed = (size+15)/16; // convert size from bytes to paragraphs
749 MM_GetNewBlock(mm); // fill in start and next after a spot is found
750 mm->mmnew->length = needed;
751 mm->mmnew->useptr = baseptr;
752 mm->mmnew->attributes = BASEATTRIBUTES;
754 for(search = 0; search<3; search++)
757 // first search: try to allocate right after the rover, then on up
758 // second search: search from the head pointer up to the rover
759 // third search: compress memory, then scan from start
760 if(search == 1 && mm->mmrover == mm->mmhead)
766 lastscan = mm->mmrover;
767 scan = mm->mmrover->next;
771 lastscan = mm->mmhead;
772 scan = mm->mmhead->next;
773 endscan = mm->mmrover;
777 lastscan = mm->mmhead;
778 scan = mm->mmhead->next;
783 startseg = lastscan->start + lastscan->length;
785 while(scan != endscan)
787 if(scan->start - startseg >= needed)
790 // got enough space between the end of lastscan and
791 // the start of scan, so throw out anything in the middle
792 // and allocate the new block
794 purge = lastscan->next;
795 lastscan->next = mm->mmnew;
796 mm->mmnew->start = *(unsigned *)baseptr = startseg;
797 mm->mmnew->next = scan;
799 { // free the purgable block
801 MM_FreeBlock(purge, mm);
802 purge = next; // purge another if not at scan
804 mm->mmrover = mm->mmnew;
805 return; // good allocation!
809 // if this block is purge level zero or locked, skip past it
811 if((scan->attributes & LOCKBIT)
812 || !(scan->attributes & PURGEBITS) )
815 startseg = lastscan->start + lastscan->length;
819 scan=scan->next; // look at next line
824 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
829 //==========================================================================
836 = Allocates an unlocked, unpurgable block
841 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
843 mmblocktype huge *scan,huge *last;
848 if(baseptr == mm->mmrover->useptr) // removed the last allocated block
849 mm->mmrover = mm->mmhead;
851 while(scan->useptr != baseptr && scan)
859 printf("MM_FreePtr: Block not found!");
863 last->next = scan->next;
865 MM_FreeBlock(scan, mm);
867 //==========================================================================
870 =====================
874 = Sets the purge level for a block (locked blocks cannot be made purgable)
876 =====================
879 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
881 mmblocktype huge *start;
887 if(mm->mmrover->useptr == baseptr)
890 mm->mmrover = mm->mmrover->next;
893 mm->mmrover = mm->mmhead;
894 else if(mm->mmrover == start)
896 printf("MM_SetPurge: Block not found!");
902 mm->mmrover->attributes &= ~PURGEBITS;
903 mm->mmrover->attributes |= purge;
906 //==========================================================================
909 =====================
913 = Locks / unlocks the block
915 =====================
918 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
920 mmblocktype huge *start;
926 if(mm->mmrover->useptr == baseptr)
929 mm->mmrover = mm->mmrover->next;
932 mm->mmrover = mm->mmhead;
933 else if(mm->mmrover == start)
935 printf("MM_SetLock: Block not found!");
941 mm->mmrover->attributes &= ~LOCKBIT;
942 mm->mmrover->attributes |= locked*LOCKBIT;
945 //==========================================================================
948 =====================
952 = Throws out all purgable stuff and compresses movable blocks
954 =====================
957 void MM_SortMem(mminfo_t *mm)
959 mmblocktype huge *scan,huge *last,huge *next;
960 unsigned start,length,source,dest,oldborder;
964 // lock down a currently playing sound
966 /*++++ playing = SD_SoundPlaying ();
972 playing += STARTPCSOUNDS;
975 playing += STARTADLIBSOUNDS;
978 MM_SetLock(&(memptr)audiosegs[playing],true);
983 // oldborder = bordercolor;
984 // VW_ColorBorder (15);
991 last = NULL; // shut up compiler warning
995 if(scan->attributes & LOCKBIT)
998 // block is locked, so try to pile later blocks right after it
1000 start = scan->start + scan->length;
1004 if(scan->attributes & PURGEBITS)
1007 // throw out the purgable block
1010 MM_FreeBlock(scan, mm);
1018 // push the non purgable block on top of the last moved block
1020 if(scan->start != start)
1022 length = scan->length;
1023 source = scan->start;
1025 while(length > 0xf00)
1027 movedata(source,0,dest,0,0xf00*16);
1032 movedata(source,0,dest,0,length*16);
1034 scan->start = start;
1035 *(unsigned *)scan->useptr = start;
1037 start = scan->start + scan->length;
1042 scan = scan->next; // go to next block
1045 mm->mmrover = mm->mmhead;
1050 // VW_ColorBorder (oldborder);
1053 MM_SetLock(&(memptr)audiosegs[playing],false);*/
1057 //==========================================================================
1061 =====================
1065 =====================
1068 void MM_ShowMemory(mminfo_t *mm)
1070 mmblocktype huge *scan;
1071 unsigned color,temp;
1073 char scratch[160],str[16];
1075 //**** VW_SetDefaultColors();
1076 //**** VW_SetLineWidth(40);
1077 //++++mh temp = bufferofs;
1078 //++++mh bufferofs = 0;
1079 //**** VW_SetScreen (0,0);
1089 if(scan->attributes & PURGEBITS)
1090 color = 5; // dark purple = purgable
1092 color = 9; // medium blue = non purgable
1093 if(scan->attributes & LOCKBIT)
1094 color = 12; // red = locked
1095 if(scan->start<=end)
1097 printf("\nMM_ShowMemory: Memory block order currupted!\n");
1100 end = scan->start+scan->length-1;
1101 //++++ VW_Hlin(scan->start,(unsigned)end,0,color);
1102 //++++ VW_Plot(scan->start,0,15);
1103 if(scan->next->start > end+1)
1104 //++++ VW_Hlin(end+1,scan->next->start,0,0); // black = free
1107 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!
1108 strcpy(scratch,"Location:");
1109 ultoa (scan->start,str,16);
1110 strcat (scratch,str);
1111 strcat (scratch,"\tSize:");
1112 ltoa ((dword)scan->length*16,str,10);
1113 strcat (scratch,str);
1114 strcat (scratch,"\tOwner:0x");
1115 owner = (unsigned)scan->useptr;
1116 ultoa (owner,str,16);
1117 strcat (scratch,str);
1118 strcat (scratch,"\n");
1119 //++++write (debughandle,scratch,strlen(scratch));
1120 fprintf(stdout, "%s", scratch);
1129 //**** VW_SetLineWidth(64);
1130 //++++mh bufferofs = temp;
1134 //==========================================================================
1138 ======================
1142 = Returns the total free space without purging
1144 ======================
1147 dword MM_UnusedMemory(mminfo_t *mm)
1150 mmblocktype huge *scan;
1157 free += scan->next->start - (scan->start + scan->length);
1165 //==========================================================================
1169 ======================
1173 = Returns the total free space with purging
1175 ======================
1178 dword MM_TotalFree(mminfo_t *mm)
1181 mmblocktype huge *scan;
1188 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1189 free += scan->length;
1190 free += scan->next->start - (scan->start + scan->length);
1198 //==========================================================================
1201 =====================
1205 =====================
1208 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1210 if(MML_CheckForEMS())
1212 printf("EMM %x available\n", mm->EMSVer);
1213 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1214 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1215 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1217 if(MML_CheckForXMS(mm)) printf("XMSaddr=%Fp\n", *XMSaddr);
1218 printf("near=%lu\n", mmi->nearheap);
1219 printf("far=%lu\n", mmi->farheap);
1220 printf("EMSmem=%lu\n", mmi->EMSmem);
1221 printf("XMSmem=%lu\n", mmi->XMSmem);
1222 printf("mainmem=%lu\n", mmi->mainmem);
1223 printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1224 printf("TotalFree=%lu\n", MM_TotalFree(mm));
1226 // printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1227 // printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1230 //==========================================================================
1233 =====================
1237 =====================
1252 //==========================================================================
1255 =====================
1259 =====================
1262 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1264 mm->bombonerror = bomb;
1267 void MM_GetNewBlock(mminfo_t *mm)
1271 mm->mmnew=mm->mmfree;
1272 mm->mmfree=mm->mmfree->next;
1273 /*if(!(mm->mmnew=mm->mmfree))
1275 printf("MM_GETNEWBLOCK: No free blocks!");
1278 mm->mmfree=mm->mmfree->next;*/
1281 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1288 void MM_seguin(void)
1299 void MM_segude(void)
1308 pull data from far and put it into ds var