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