]> 4ch.mooo.com Git - 16.git/blob - src/lib/16_mm.c
divide the memory blob into chunks
[16.git] / src / lib / 16_mm.c
1 /* Catacomb Apocalypse Source Code
2  * Copyright (C) 1993-2014 Flat Rock Software
3  *
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.
8  *
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.
13  *
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.
17  */
18
19 // NEWMM.C
20
21 /*
22 =============================================================================
23
24                         ID software memory manager
25                         --------------------------
26
27 Primary coder: John Carmack
28
29 RELIES ON
30 ---------
31 Quit (char *error) function
32
33
34 WORK TO DO
35 ----------
36 MM_SizePtr to change the size of a given pointer
37
38 Multiple purge levels utilized
39
40 EMS / XMS unmanaged routines
41
42 =============================================================================
43 */
44 /*
45
46 Open Watcom port by sparky4
47
48 */
49 #include "src/lib/16_mm.h"
50
51 /*
52 =============================================================================
53
54                                                  GLOBAL VARIABLES
55
56 =============================================================================
57 */
58
59 void            (* beforesort) (void);
60 void            (* aftersort) (void);
61 void            (* XMSaddr) (void);             // far pointer to XMS driver
62
63 /*
64 =============================================================================
65
66                                                  LOCAL VARIABLES
67
68 =============================================================================
69 */
70
71 static  char *ParmStringsexmm[] = {"noems","noxms",""};
72
73 /*
74 ======================
75 =
76 = MML_CheckForEMS
77 =
78 = Routine from p36 of Extending DOS
79 =
80 =======================
81 */
82
83 boolean MML_CheckForEMS(void)
84 {
85         boolean emmcfems;
86         char    emmname[] = "EMMXXXX0";
87 //              mov     dx,OFFSET emmname
88         __asm {
89                 LEA     DX, emmname     //fix by andrius4669
90                 mov     ax,0x3d00
91                 int     0x21            // try to open EMMXXXX0 device
92                 jc      error
93
94                 mov     bx,ax
95                 mov     ax,0x4400
96
97                 int     0x21            // get device info
98                 jc      error
99
100                 and     dx,0x80
101                 jz      error
102
103                 mov     ax,0x4407
104
105                 int     0x21            // get status
106                 jc      error
107                 or      al,al
108                 jz      error
109
110                 mov     ah,0x3e
111                 int     0x21            // close handle
112                 jc      error
113                 //
114                 // EMS is good
115                 //
116                 mov     emmcfems,1
117                 jmp End
118                 error:
119                 //
120                 // EMS is bad
121                 //
122                 mov     emmcfems,0
123                 End:
124         }
125         return(emmcfems);
126 }
127
128
129 /*
130 ======================
131 =
132 = MML_SetupEMS
133 =
134 =======================
135 */
136
137 unsigned MML_SetupEMS(mminfo_t *mm)
138 {
139         char    str[80],str2[10];
140         unsigned        err;
141         boolean errorflag=false;
142         union REGS CPURegs;
143
144         unsigned int EMSVer = 0;
145         unsigned        totalEMSpages,freeEMSpages,EMSpageframe,EMSpagesmapped,EMShandle;
146         totalEMSpages = freeEMSpages = EMSpageframe = EMSpagesmapped = 0;
147
148         __asm
149                 {
150                 mov     ah,EMS_STATUS
151                 int     EMS_INT                                         // make sure EMS hardware is present
152                 or      ah,ah
153                 jnz     error
154
155                 mov     ah,EMS_VERSION
156                 int     EMS_INT
157                 or      ah,ah
158                 jnz     error
159                 mov     [EMSVer],ax                             //      set EMSVer
160                 cmp     al,0x32                                         // only work on ems 3.2 or greater
161                 jb      error
162
163                 mov     ah,EMS_GETFRAME
164                 int     EMS_INT                                         // find the page frame address
165                 or      ah,ah
166                 jnz     error
167                 mov     [EMSpageframe],bx
168
169                 mov     ah,EMS_GETPAGES
170                 int     EMS_INT                                         // find out how much EMS is there
171                 or      ah,ah
172                 jnz     error
173                 mov     [totalEMSpages],dx
174                 mov     [freeEMSpages],bx
175                 or      bx,bx
176                 jz      noEMS                                           // no EMS at all to allocate
177
178                 cmp     bx,4
179                 jle     getpages                                        // there is only 1,2,3,or 4 pages
180                 mov     bx,4                                            // we can't use more than 4 pages
181
182 getpages:
183                 mov     [EMSpagesmapped],bx
184                 mov     ah,EMS_ALLOCPAGES                       // allocate up to 64k of EMS
185                 int     EMS_INT
186                 or      ah,ah
187                 jnz     error
188                 mov     [EMShandle],dx
189                 jmp End
190 error:
191                 mov     errorflag,1
192                 jmp End
193 noEMS:
194 End:
195         }
196         if(errorflag==true)
197         {
198                 err = CPURegs.h.ah;
199                 strcpy(str,"MML_SetupEMS: EMS error 0x");
200                 itoa(err,str2,16);
201                 strcpy(str,str2);
202                 printf("%s\n",str);
203                 return err;
204         }
205         mm->totalEMSpages=totalEMSpages;
206         mm->freeEMSpages=freeEMSpages;
207         mm->EMSpageframe=EMSpageframe;
208         mm->EMSpagesmapped=EMSpagesmapped;
209         mm->EMShandle=EMShandle;
210         mm->EMSVer=EMSVer;
211         return 0;
212 }
213
214
215 /*
216 ======================
217 =
218 = MML_ShutdownEMS
219 =
220 =======================
221 */
222
223 void MML_ShutdownEMS(mminfo_t *mm)
224 {
225         boolean errorflag=false;
226         unsigned EMShandle=mm->EMShandle;
227
228         if(!EMShandle)
229                 return;
230         __asm
231         {
232                 mov     ah,EMS_FREEPAGES
233                 mov     dx,[EMShandle]
234                 int     EMS_INT
235                 or      ah,ah
236                 jz      ok
237                 mov     errorflag,1
238                 ok:
239         }
240         if(errorflag==true) printf("MML_ShutdownEMS: Error freeing EMS!");      //++++ add something
241 }
242
243 /*
244 ====================
245 =
246 = MM_MapEMS
247 =
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.
251 =
252 ====================
253 */
254
255 unsigned MM_MapEMS(mminfo_t *mm)
256 {
257         char    str[80],str2[10];
258         unsigned        err, EMShandle;
259         boolean errorflag=false;
260         int     i;
261         union REGS CPURegs;
262         EMShandle=mm->EMShandle;
263
264         for (i=0;i<mm->EMSpagesmapped;i++)
265         {
266                 __asm
267                 {
268                         mov     ah,EMS_MAPPAGE
269                         mov     bx,[i]                  // logical page
270                         mov     al,bl                   // physical page
271                         mov     dx,[EMShandle]  // handle
272                         int     EMS_INT
273                         or      ah,ah
274                         jnz     error
275                         jmp End
276                         error:
277                         mov     errorflag,1
278                         End:
279                 }
280                 if(errorflag==true)
281                 {
282                         err = CPURegs.h.ah;
283                         strcpy(str,"MM_MapEMS: EMS error 0x");
284                         itoa(err,str2,16);
285                         strcpy(str,str2);
286                         printf("%s\n",str);
287                         return err;
288                 }
289         }
290         return 0;
291 }
292
293 //==========================================================================
294
295 /*
296 ======================
297 =
298 = MML_CheckForXMS
299 =
300 = Check for XMM driver
301 =
302 =======================
303 */
304
305 boolean MML_CheckForXMS(mminfo_t *mm)
306 {
307         boolean errorflag=false;
308         mm->numUMBs = 0;
309
310         __asm
311         {
312                 mov     ax,0x4300
313                 int     0x2f                            // query status of installed diver
314                 cmp     al,0x80
315                 je      good
316                 mov     errorflag,1
317                 good:
318         }
319         if(errorflag==true) return false;
320         else return true;
321 }
322
323
324 /*
325 ======================
326 =
327 = MML_SetupXMS
328 =
329 = Try to allocate all upper memory block
330 =
331 =======================
332 */
333
334 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
335 {
336         unsigned        base,size;
337
338 getmemory:
339         __asm
340         {
341                 mov     ax,0x4310
342                 int     0x2f
343                 mov     [WORD PTR XMSaddr],bx
344                 mov     [WORD PTR XMSaddr+2],es         // function pointer to XMS driver
345
346                 mov     ah,XMS_ALLOCUMB
347                 mov     dx,0xffff                                       // try for largest block possible
348                 call    [DWORD PTR XMSaddr]
349                 or      ax,ax
350                 jnz     gotone
351
352                 cmp     bl,0xb0                                         // error: smaller UMB is available
353                 jne     done;
354
355                 mov     ah,XMS_ALLOCUMB
356                 call    [DWORD PTR XMSaddr]             // DX holds largest available UMB
357                 or      ax,ax
358                 jz      done                                            // another error...
359
360 gotone:
361                 mov     [base],bx
362                 mov     [size],dx
363 done:
364         }
365         MML_UseSpace(base,size, mm);
366         mmi->XMSmem += size*16;
367         mm->UMBbase[mm->numUMBs] = base;
368         mm->numUMBs++;
369         if(mm->numUMBs < MAXUMBS)
370                 goto getmemory;
371 }
372
373
374 /*
375 ======================
376 =
377 = MML_ShutdownXMS
378 =
379 ======================
380 */
381
382 void MML_ShutdownXMS(mminfo_t *mm)
383 {
384         int     i;
385         unsigned        base;
386
387         for (i=0;i<mm->numUMBs;i++)
388         {
389                 base = mm->UMBbase[i];
390                 __asm
391                 {
392                         mov     ah,XMS_FREEUMB
393                         mov     dx,[base]
394                         call    [DWORD PTR XMSaddr]
395                 }
396         }
397 }
398
399 //==========================================================================
400
401 /*
402 ======================
403 =
404 = MML_UseSpace
405 =
406 = Marks a range of paragraphs as usable by the memory manager
407 = This is used to mark space for the near heap, far heap, ems page frame,
408 = and upper memory blocks
409 =
410 ======================
411 */
412
413 void MML_UseSpace(unsigned segstart, dword seglength, mminfo_t *mm)
414 {
415         mmblocktype huge *scan,huge *last;
416         unsigned        oldend;
417         //++++if(mm->EMSVer)
418         dword           extra;
419
420         scan = last = mm->mmhead;
421         mm->mmrover = mm->mmhead;               // reset rover to start of memory
422
423 //
424 // search for the block that contains the range of segments
425 //
426         while(scan->start+scan->length < segstart)
427         {
428                 last = scan;
429                 scan = scan->next;
430         }
431
432 //
433 // take the given range out of the block
434 //
435         oldend = scan->start + scan->length;
436         extra = oldend - (segstart+seglength);
437         //++++emsver stuff!
438         if(extra > 0xffffl)
439         {
440                 printf("MML_UseSpace: Segment spans two blocks!\n");
441                 //return;
442         }
443
444
445         if(segstart == scan->start)
446         {
447                 last->next = scan->next;                        // unlink block
448                 MM_FreeBlock(scan, mm);
449                 scan = last;
450         }
451         else
452                 scan->length = segstart-scan->start;    // shorten block
453
454         if(extra > 0)
455         {
456                 MM_GetNewBlock(mm);
457                 mm->mmnew->next = scan->next;
458                 scan->next = mm->mmnew;
459                 mm->mmnew->start = segstart+seglength;
460                 mm->mmnew->length = extra;
461                 mm->mmnew->attributes = LOCKBIT;
462         }
463
464 }
465
466 //==========================================================================
467
468 /*
469 ====================
470 =
471 = MML_ClearBlock
472 =
473 = We are out of blocks, so free a purgable block
474 =
475 ====================
476 */
477
478 void MML_ClearBlock(mminfo_t *mm)
479 {
480         mmblocktype huge *scan,huge *last;
481
482         scan = mm->mmhead->next;
483
484         while(scan)
485         {
486                 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
487                 {
488                         MM_FreePtr(scan->useptr, mm);
489                         return;
490                 }
491                 scan = scan->next;
492         }
493
494         printf("MM_ClearBlock: No purgable blocks!");
495 }
496
497
498 //==========================================================================
499
500 /*
501 ===================
502 =
503 = MM_Startup
504 =
505 = Grabs all space from turbo with malloc/farmalloc
506 = Allocates bufferseg misc buffer
507 =
508 ===================
509 */
510
511 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
512 {
513         int i;
514         dword length;//,farlen;
515         void huge       *start;
516         unsigned        segstart,seglength,endfree;
517
518         if(mm->mmstarted)
519                 MM_Shutdown(mm);
520
521         mm->mmstarted = true;
522         mm->bombonerror = true;
523 //
524 // set up the linked list (everything in the free list;
525 //
526         mm->mmhead = NULL;
527         mm->mmfree = &(mm->mmblocks[0]);
528         for(i=0;i<MAXBLOCKS-1;i++)
529         {
530                 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
531         }
532         mm->mmblocks[i].next = NULL;
533
534 //
535 // locked block of all memory until we punch out free space
536 //
537         MM_GetNewBlock(mm);
538         mm->mmhead = mm->mmnew;                         // this will allways be the first node
539         mm->mmnew->start = 0;
540         mm->mmnew->length = 0xffff;                     //todo: mm make it fucking massive as fuck!~
541         mm->mmnew->attributes = LOCKBIT;
542         mm->mmnew->next = NULL;
543         mm->mmrover = mm->mmhead;
544
545 //      farlen=_bios_memsize()*1024;
546
547 //
548 // get all available near conventional memory segments
549 //
550 //----  length=coreleft();
551         _nheapgrow();
552         length=_memavl();
553         start = (void huge *)(mm->nearheap = malloc(length));
554
555         length -= 16-(FP_OFF(start)&15);
556         length -= SAVENEARHEAP;
557         seglength = length / 16;                        // now in paragraphs
558         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
559         MML_UseSpace(segstart,seglength, mm);
560         mmi->nearheap = length;
561
562 //
563 // get all available far conventional memory segments
564 //
565 //----  length=farcoreleft();
566         _fheapgrow();
567         length=_memavl();
568         //length-=farlen;
569         start = mm->farheap = halloc(length, sizeof(length));
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;
578
579
580 //
581 // detect EMS and allocate up to 64K at page frame
582 //
583         mmi->EMSmem = 0;
584         for(i = 1;i < __argc;i++)
585         {
586                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
587                         goto emsskip;                           // param NOEMS
588         }
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())
591         {
592 //printf("EMS1\n");
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                 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
596                 if(mm->EMSVer>=0x40) MML_UseSpace(mm->EMSpageframe,((dword)mm->EMSpagesmapped)*((dword)mm->freeEMSpages), mm);
597                 else MML_UseSpace(mm->EMSpageframe,mm->EMSpagesmapped*0x400, mm);
598 //printf("EMS3\n");
599                 MM_MapEMS(mm);                                  // map in used pages
600 //printf("EMS4\n");
601                 if(mm->EMSVer>=0x40) mmi->EMSmem = ((dword)mm->EMSpagesmapped)*((dword)mm->freeEMSpages);
602                 else mmi->EMSmem = mm->EMSpagesmapped*0x4000l;
603         }
604
605 //
606 // detect XMS and get upper memory blocks
607 //
608 emsskip:
609         mmi->XMSmem = 0;
610         for(i = 1;i < __argc;i++)
611         {
612                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
613                         goto xmsskip;                           // param NOXMS
614         }
615 //      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!
616         if(MML_CheckForXMS(mm))
617         {
618 //printf("XMS!\n");
619                 MML_SetupXMS(mm, mmi);                                  // allocate as many UMBs as possible
620         }
621
622 //
623 // allocate the misc buffer
624 //
625 xmsskip:
626         mm->mmrover = mm->mmhead;               // start looking for space after low block
627
628         MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
629 }
630
631 //==========================================================================
632
633 /*
634 ====================
635 =
636 = MM_Shutdown
637 =
638 = Frees all conventional, EMS, and XMS allocated
639 =
640 ====================
641 */
642
643 void MM_Shutdown(mminfo_t *mm)
644 {
645         if(!(mm->mmstarted))
646                 return;
647
648         _ffree(mm->farheap);
649         printf("far freed\n");
650         free(mm->nearheap);
651         printf("near freed\n");
652         //hfree(mm->hugeheap);
653         //printf("huge freed\n");
654         if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
655         if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
656 }
657
658 //==========================================================================
659
660 /*
661 ====================
662 =
663 = MM_GetPtr
664 =
665 = Allocates an unlocked, unpurgable block
666 =
667 ====================
668 */
669
670 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
671 {
672         mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
673         int                     search;
674         unsigned        needed,startseg;
675
676         needed = (size+15)/16;          // convert size from bytes to paragraphs
677
678         MM_GetNewBlock(mm);                             // fill in start and next after a spot is found
679         mm->mmnew->length = needed;
680         mm->mmnew->useptr = baseptr;
681         mm->mmnew->attributes = BASEATTRIBUTES;
682
683         for(search = 0; search<3; search++)
684         {
685         //
686         // first search:        try to allocate right after the rover, then on up
687         // second search:       search from the head pointer up to the rover
688         // third search:        compress memory, then scan from start
689                 if(search == 1 && mm->mmrover == mm->mmhead)
690                         search++;
691
692                 switch(search)
693                 {
694                 case 0:
695                         lastscan = mm->mmrover;
696                         scan = mm->mmrover->next;
697                         endscan = NULL;
698                         break;
699                 case 1:
700                         lastscan = mm->mmhead;
701                         scan = mm->mmhead->next;
702                         endscan = mm->mmrover;
703                         break;
704                 case 2:
705                         MM_SortMem(mm);
706                         lastscan = mm->mmhead;
707                         scan = mm->mmhead->next;
708                         endscan = NULL;
709                         break;
710                 }
711
712                 startseg = lastscan->start + lastscan->length;
713
714                 while(scan != endscan)
715                 {
716                         if(scan->start - startseg >= needed)
717                         {
718                         //
719                         // got enough space between the end of lastscan and
720                         // the start of scan, so throw out anything in the middle
721                         // and allocate the new block
722                         //
723                                 purge = lastscan->next;
724                                 lastscan->next = mm->mmnew;
725                                 mm->mmnew->start = *(unsigned *)baseptr = startseg;
726                                 mm->mmnew->next = scan;
727                                 while(purge != scan)
728                                 {       // free the purgable block
729                                         next = purge->next;
730                                         MM_FreeBlock(purge, mm);
731                                         purge = next;           // purge another if not at scan
732                                 }
733                                 mm->mmrover = mm->mmnew;
734                                 return; // good allocation!
735                         }
736
737                         //
738                         // if this block is purge level zero or locked, skip past it
739                         //
740                         if((scan->attributes & LOCKBIT)
741                                 || !(scan->attributes & PURGEBITS) )
742                         {
743                                 lastscan = scan;
744                                 startseg = lastscan->start + lastscan->length;
745                         }
746
747
748                         scan=scan->next;                // look at next line
749                 }
750         }
751
752         if (mm->bombonerror)
753                 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
754         else
755                 mm->mmerror = true;
756 }
757
758 //==========================================================================
759
760 /*
761 ====================
762 =
763 = MM_FreePtr
764 =
765 = Allocates an unlocked, unpurgable block
766 =
767 ====================
768 */
769
770 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
771 {
772         mmblocktype huge *scan,huge *last;
773
774         last = mm->mmhead;
775         scan = last->next;
776
777         if(baseptr == mm->mmrover->useptr)      // removed the last allocated block
778                 mm->mmrover = mm->mmhead;
779
780         while(scan->useptr != baseptr && scan)
781         {
782                 last = scan;
783                 scan = scan->next;
784         }
785
786         if(!scan)
787         {
788                 printf("MM_FreePtr: Block not found!");
789                 return;
790         }
791
792         last->next = scan->next;
793
794         MM_FreeBlock(scan, mm);
795 }
796 //==========================================================================
797
798 /*
799 =====================
800 =
801 = MM_SetPurge
802 =
803 = Sets the purge level for a block (locked blocks cannot be made purgable)
804 =
805 =====================
806 */
807
808 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
809 {
810         mmblocktype huge *start;
811
812         start = mm->mmrover;
813
814         do
815         {
816                 if(mm->mmrover->useptr == baseptr)
817                         break;
818
819                 mm->mmrover = mm->mmrover->next;
820
821                 if(!mm->mmrover)
822                         mm->mmrover = mm->mmhead;
823                 else if(mm->mmrover == start)
824                 {
825                         printf("MM_SetPurge: Block not found!");
826                         return;
827                 }
828
829         } while(1);
830
831         mm->mmrover->attributes &= ~PURGEBITS;
832         mm->mmrover->attributes |= purge;
833 }
834
835 //==========================================================================
836
837 /*
838 =====================
839 =
840 = MM_SetLock
841 =
842 = Locks / unlocks the block
843 =
844 =====================
845 */
846
847 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
848 {
849         mmblocktype huge *start;
850
851         start = mm->mmrover;
852
853         do
854         {
855                 if(mm->mmrover->useptr == baseptr)
856                         break;
857
858                 mm->mmrover = mm->mmrover->next;
859
860                 if(!mm->mmrover)
861                         mm->mmrover = mm->mmhead;
862                 else if(mm->mmrover == start)
863                 {
864                         printf("MM_SetLock: Block not found!");
865                         return;
866                 }
867
868         } while(1);
869
870         mm->mmrover->attributes &= ~LOCKBIT;
871         mm->mmrover->attributes |= locked*LOCKBIT;
872 }
873
874 //==========================================================================
875
876 /*
877 =====================
878 =
879 = MM_SortMem
880 =
881 = Throws out all purgable stuff and compresses movable blocks
882 =
883 =====================
884 */
885
886 void MM_SortMem(mminfo_t *mm)
887 {
888         mmblocktype huge *scan,huge *last,huge *next;
889         unsigned        start,length,source,dest,oldborder;
890         int                     playing;
891
892         //
893         // lock down a currently playing sound
894         //
895 /*++++  playing = SD_SoundPlaying ();
896         if(playing)
897         {
898                 switch (SoundMode)
899                 {
900                 case sdm_PC:
901                         playing += STARTPCSOUNDS;
902                         break;
903                 case sdm_AdLib:
904                         playing += STARTADLIBSOUNDS;
905                         break;
906                 }
907                 MM_SetLock(&(memptr)audiosegs[playing],true);
908         }
909
910
911         SD_StopSound();*/
912 //      oldborder = bordercolor;
913 //      VW_ColorBorder (15);
914
915         if(beforesort)
916                 beforesort();
917
918         scan = mm->mmhead;
919
920         last = NULL;            // shut up compiler warning
921
922         while(scan)
923         {
924                 if(scan->attributes & LOCKBIT)
925                 {
926                 //
927                 // block is locked, so try to pile later blocks right after it
928                 //
929                         start = scan->start + scan->length;
930                 }
931                 else
932                 {
933                         if(scan->attributes & PURGEBITS)
934                         {
935                         //
936                         // throw out the purgable block
937                         //
938                                 next = scan->next;
939                                 MM_FreeBlock(scan, mm);
940                                 last->next = next;
941                                 scan = next;
942                                 continue;
943                         }
944                         else
945                         {
946                         //
947                         // push the non purgable block on top of the last moved block
948                         //
949                                 if(scan->start != start)
950                                 {
951                                         length = scan->length;
952                                         source = scan->start;
953                                         dest = start;
954                                         while(length > 0xf00)
955                                         {
956                                                 movedata(source,0,dest,0,0xf00*16);
957                                                 length -= 0xf00;
958                                                 source += 0xf00;
959                                                 dest += 0xf00;
960                                         }
961                                         movedata(source,0,dest,0,length*16);
962
963                                         scan->start = start;
964                                         *(unsigned *)scan->useptr = start;
965                                 }
966                                 start = scan->start + scan->length;
967                         }
968                 }
969
970                 last = scan;
971                 scan = scan->next;              // go to next block
972         }
973
974         mm->mmrover = mm->mmhead;
975
976         if(aftersort)
977                 aftersort();
978
979 //      VW_ColorBorder (oldborder);
980
981 /*++++  if(playing)
982                 MM_SetLock(&(memptr)audiosegs[playing],false);*/
983 }
984
985
986 //==========================================================================
987
988 //****#if 0
989 /*
990 =====================
991 =
992 = MM_ShowMemory
993 =
994 =====================
995 */
996
997 void MM_ShowMemory(mminfo_t *mm)
998 {
999         mmblocktype huge *scan;
1000         unsigned color,temp;//, i;
1001         long    end,owner;
1002         char    scratch[80],str[10];
1003
1004 //****  VW_SetDefaultColors();
1005 //****  VW_SetLineWidth(40);
1006 //++++mh        temp = bufferofs;
1007 //++++mh        bufferofs = 0;
1008 //****  VW_SetScreen (0,0);
1009
1010         scan = mm->mmhead;
1011
1012         end = -1;
1013
1014 //CA_OpenDebug ();
1015
1016         while (scan)
1017         {
1018                 if(scan->attributes & PURGEBITS)
1019                         color = 5;              // dark purple = purgable
1020                 else
1021                         color = 9;              // medium blue = non purgable
1022                 if(scan->attributes & LOCKBIT)
1023                         color = 12;             // red = locked
1024                 if(scan->start<=end)
1025                 {
1026                         printf("MM_ShowMemory: Memory block order currupted!");
1027                         return;
1028                 }
1029                 end = scan->start+scan->length-1;
1030 //++++          VW_Hlin(scan->start,(unsigned)end,0,color);
1031 //++++          VW_Plot(scan->start,0,15);
1032                 if(scan->next->start > end+1)
1033 //++++                  VW_Hlin(end+1,scan->next->start,0,0);   // black = free
1034
1035 //****#if 0
1036 printf("Location:");
1037 printf("%x\t", scan->start);
1038 strcpy (scratch,"Size:");
1039 ltoa ((dword)scan->length*16,str,10);
1040 strcat (scratch,str);
1041 strcat (scratch,"\tOwner:0x");
1042 owner = (unsigned)scan->useptr;
1043 ultoa (owner,str,16);
1044 strcat (scratch,str);
1045 strcat (scratch,"\n");
1046 //++++write (debughandle,scratch,strlen(scratch));
1047 fprintf(stdout, "%s", scratch);
1048 //****#endif
1049
1050                 scan = scan->next;
1051         }
1052
1053 //CA_CloseDebug ();
1054
1055 //++++mh        IN_Ack();
1056 //****  VW_SetLineWidth(64);
1057 //++++mh        bufferofs = temp;
1058 }
1059 //****#endif
1060
1061 //==========================================================================
1062
1063
1064 /*
1065 ======================
1066 =
1067 = MM_UnusedMemory
1068 =
1069 = Returns the total free space without purging
1070 =
1071 ======================
1072 */
1073
1074 dword MM_UnusedMemory(mminfo_t *mm)
1075 {
1076         unsigned free;
1077         mmblocktype huge *scan;
1078
1079         free = 0;
1080         scan = mm->mmhead;
1081
1082         while(scan->next)
1083         {
1084                 free += scan->next->start - (scan->start + scan->length);
1085                 scan = scan->next;
1086         }
1087
1088         return free*16l;
1089 //      return free;
1090 }
1091
1092 //==========================================================================
1093
1094
1095 /*
1096 ======================
1097 =
1098 = MM_TotalFree
1099 =
1100 = Returns the total free space with purging
1101 =
1102 ======================
1103 */
1104
1105 dword MM_TotalFree(mminfo_t *mm)
1106 {
1107         unsigned free;
1108         mmblocktype huge *scan;
1109
1110         free = 0;
1111         scan = mm->mmhead;
1112
1113         while(scan->next)
1114         {
1115                 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1116                         free += scan->length;
1117                 free += scan->next->start - (scan->start + scan->length);
1118                 scan = scan->next;
1119         }
1120
1121         return free*16l;
1122 //      return free;
1123 }
1124
1125 //==========================================================================
1126
1127 /*
1128 =====================
1129 =
1130 = MM_Report
1131 =
1132 =====================
1133 */
1134
1135 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1136 {
1137         if(MML_CheckForEMS())
1138         {
1139                 printf("EMM %x available\n", mm->EMSVer);
1140                 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1141                 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1142                 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1143         }
1144         if(MML_CheckForXMS(mm)) printf("XMSaddr=%x\n", *XMSaddr);
1145         printf("near=%lu\n", mmi->nearheap);
1146         printf("far=%lu\n", mmi->farheap);
1147         printf("EMSmem=%lu\n", mmi->EMSmem);
1148         printf("XMSmem=%lu\n", mmi->XMSmem);
1149         printf("mainmem=%lu\n", mmi->mainmem);
1150         printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1151         printf("TotalFree=%lu\n", MM_TotalFree(mm));
1152 //      printf("\n");
1153 //      printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1154 //      printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1155 }
1156
1157 //==========================================================================
1158
1159 /*
1160 =====================
1161 =
1162 = MM_EMSVer
1163 =
1164 =====================
1165
1166
1167 int MM_EMSVer(void)
1168 {
1169         int EMSver;
1170         __asm
1171         {
1172                 mov             ah,EMS_VERSION
1173                 int             EMS_INT
1174                 mov             EMSver,ax
1175         }
1176         return(EMSver);
1177 }*/
1178
1179 //==========================================================================
1180
1181 /*
1182 =====================
1183 =
1184 = MM_BombOnError
1185 =
1186 =====================
1187 */
1188
1189 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1190 {
1191         mm->bombonerror = bomb;
1192 }
1193
1194 void MM_GetNewBlock(mminfo_t *mm)
1195 {
1196         if(!mm->mmfree)
1197                 MML_ClearBlock(mm);
1198         mm->mmnew=mm->mmfree;
1199         mm->mmfree=mm->mmfree->next;
1200         /*if(!(mm->mmnew=mm->mmfree))
1201         {
1202                 printf("MM_GETNEWBLOCK: No free blocks!");
1203                 return;
1204         }
1205         mm->mmfree=mm->mmfree->next;*/
1206 }
1207
1208 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1209 {
1210         x->useptr=NULL;
1211         x->next=mm->mmfree;
1212         mm->mmfree=x;
1213 }