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