]> 4ch.mooo.com Git - 16.git/blob - src/lib/16_mm.c
ok working on extention
[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, unsigned seglength, mminfo_t *mm)
414 {
415         mmblocktype huge *scan,huge *last;
416         unsigned        oldend;
417         //++++if(mm->EMSVer)
418         long            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 < 0)
439         {
440                 printf("MML_UseSpace: Segment spans two blocks!");
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;
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
546 //
547 // get all available near conventional memory segments
548 //
549 //----  length=coreleft();
550         _nheapgrow();
551         length=_memavl();
552         start = (void huge *)(mm->nearheap = malloc(length));
553
554         length -= 16-(FP_OFF(start)&15);
555         length -= SAVENEARHEAP;
556         seglength = length / 16;                        // now in paragraphs
557         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
558         MML_UseSpace(segstart,seglength, mm);
559         mmi->nearheap = length;
560
561 //
562 // get all available far conventional memory segments
563 //
564 //----  length=farcoreleft();
565         _fheapgrow();
566         length=_memavl();
567         start = mm->farheap = halloc(length, 1);
568         //start = mm->farheap = _fmalloc(length);
569         length -= 16-(FP_OFF(start)&15);
570         length -= SAVEFARHEAP;
571         seglength = length / 16;                        // now in paragraphs
572         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
573         MML_UseSpace(segstart,seglength, mm);
574         mmi->farheap = length;
575         mmi->mainmem = mmi->nearheap + mmi->farheap;
576
577
578 //
579 // detect EMS and allocate up to 64K at page frame
580 //
581         mmi->EMSmem = 0;
582         for(i = 1;i < __argc;i++)
583         {
584                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
585                         goto emsskip;                           // param NOEMS
586         }
587         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!
588         if(MML_CheckForEMS())
589         {
590 //printf("EMS1\n");
591                 MML_SetupEMS(mm);                                       // allocate space
592                 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!
593                 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
594                 MML_UseSpace(mm->EMSpageframe,mm->EMSpagesmapped*0x400, mm);
595 //printf("EMS3\n");
596                 MM_MapEMS(mm);                                  // map in used pages
597 //printf("EMS4\n");
598                 mmi->EMSmem = mm->EMSpagesmapped*0x4000l;
599         }
600
601 //
602 // detect XMS and get upper memory blocks
603 //
604 emsskip:
605         mmi->XMSmem = 0;
606         for(i = 1;i < __argc;i++)
607         {
608                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
609                         goto xmsskip;                           // param NOXMS
610         }
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         if(MML_CheckForXMS(mm))
613         {
614 //printf("XMS!\n");
615                 MML_SetupXMS(mm, mmi);                                  // allocate as many UMBs as possible
616         }
617
618 //
619 // allocate the misc buffer
620 //
621 xmsskip:
622         mm->mmrover = mm->mmhead;               // start looking for space after low block
623
624         MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
625 }
626
627 //==========================================================================
628
629 /*
630 ====================
631 =
632 = MM_Shutdown
633 =
634 = Frees all conventional, EMS, and XMS allocated
635 =
636 ====================
637 */
638
639 void MM_Shutdown(mminfo_t *mm)
640 {
641         if(!(mm->mmstarted))
642                 return;
643
644         _ffree(mm->farheap);
645         printf("far freed\n");
646         free(mm->nearheap);
647         printf("near freed\n");
648         //hfree(mm->hugeheap);
649         //printf("huge freed\n");
650         if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
651         if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
652 }
653
654 //==========================================================================
655
656 /*
657 ====================
658 =
659 = MM_GetPtr
660 =
661 = Allocates an unlocked, unpurgable block
662 =
663 ====================
664 */
665
666 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
667 {
668         mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
669         int                     search;
670         unsigned        needed,startseg;
671
672         needed = (size+15)/16;          // convert size from bytes to paragraphs
673
674         MM_GetNewBlock(mm);                             // fill in start and next after a spot is found
675         mm->mmnew->length = needed;
676         mm->mmnew->useptr = baseptr;
677         mm->mmnew->attributes = BASEATTRIBUTES;
678
679         for(search = 0; search<3; search++)
680         {
681         //
682         // first search:        try to allocate right after the rover, then on up
683         // second search:       search from the head pointer up to the rover
684         // third search:        compress memory, then scan from start
685                 if(search == 1 && mm->mmrover == mm->mmhead)
686                         search++;
687
688                 switch(search)
689                 {
690                 case 0:
691                         lastscan = mm->mmrover;
692                         scan = mm->mmrover->next;
693                         endscan = NULL;
694                         break;
695                 case 1:
696                         lastscan = mm->mmhead;
697                         scan = mm->mmhead->next;
698                         endscan = mm->mmrover;
699                         break;
700                 case 2:
701                         MM_SortMem(mm);
702                         lastscan = mm->mmhead;
703                         scan = mm->mmhead->next;
704                         endscan = NULL;
705                         break;
706                 }
707
708                 startseg = lastscan->start + lastscan->length;
709
710                 while(scan != endscan)
711                 {
712                         if(scan->start - startseg >= needed)
713                         {
714                         //
715                         // got enough space between the end of lastscan and
716                         // the start of scan, so throw out anything in the middle
717                         // and allocate the new block
718                         //
719                                 purge = lastscan->next;
720                                 lastscan->next = mm->mmnew;
721                                 mm->mmnew->start = *(unsigned *)baseptr = startseg;
722                                 mm->mmnew->next = scan;
723                                 while(purge != scan)
724                                 {       // free the purgable block
725                                         next = purge->next;
726                                         MM_FreeBlock(purge, mm);
727                                         purge = next;           // purge another if not at scan
728                                 }
729                                 mm->mmrover = mm->mmnew;
730                                 return; // good allocation!
731                         }
732
733                         //
734                         // if this block is purge level zero or locked, skip past it
735                         //
736                         if((scan->attributes & LOCKBIT)
737                                 || !(scan->attributes & PURGEBITS) )
738                         {
739                                 lastscan = scan;
740                                 startseg = lastscan->start + lastscan->length;
741                         }
742
743
744                         scan=scan->next;                // look at next line
745                 }
746         }
747
748         if (mm->bombonerror)
749                 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
750         else
751                 mm->mmerror = true;
752 }
753
754 //==========================================================================
755
756 /*
757 ====================
758 =
759 = MM_FreePtr
760 =
761 = Allocates an unlocked, unpurgable block
762 =
763 ====================
764 */
765
766 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
767 {
768         mmblocktype huge *scan,huge *last;
769
770         last = mm->mmhead;
771         scan = last->next;
772
773         if(baseptr == mm->mmrover->useptr)      // removed the last allocated block
774                 mm->mmrover = mm->mmhead;
775
776         while(scan->useptr != baseptr && scan)
777         {
778                 last = scan;
779                 scan = scan->next;
780         }
781
782         if(!scan)
783         {
784                 printf("MM_FreePtr: Block not found!");
785                 return;
786         }
787
788         last->next = scan->next;
789
790         MM_FreeBlock(scan, mm);
791 }
792 //==========================================================================
793
794 /*
795 =====================
796 =
797 = MM_SetPurge
798 =
799 = Sets the purge level for a block (locked blocks cannot be made purgable)
800 =
801 =====================
802 */
803
804 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
805 {
806         mmblocktype huge *start;
807
808         start = mm->mmrover;
809
810         do
811         {
812                 if(mm->mmrover->useptr == baseptr)
813                         break;
814
815                 mm->mmrover = mm->mmrover->next;
816
817                 if(!mm->mmrover)
818                         mm->mmrover = mm->mmhead;
819                 else if(mm->mmrover == start)
820                 {
821                         printf("MM_SetPurge: Block not found!");
822                         return;
823                 }
824
825         } while(1);
826
827         mm->mmrover->attributes &= ~PURGEBITS;
828         mm->mmrover->attributes |= purge;
829 }
830
831 //==========================================================================
832
833 /*
834 =====================
835 =
836 = MM_SetLock
837 =
838 = Locks / unlocks the block
839 =
840 =====================
841 */
842
843 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
844 {
845         mmblocktype huge *start;
846
847         start = mm->mmrover;
848
849         do
850         {
851                 if(mm->mmrover->useptr == baseptr)
852                         break;
853
854                 mm->mmrover = mm->mmrover->next;
855
856                 if(!mm->mmrover)
857                         mm->mmrover = mm->mmhead;
858                 else if(mm->mmrover == start)
859                 {
860                         printf("MM_SetLock: Block not found!");
861                         return;
862                 }
863
864         } while(1);
865
866         mm->mmrover->attributes &= ~LOCKBIT;
867         mm->mmrover->attributes |= locked*LOCKBIT;
868 }
869
870 //==========================================================================
871
872 /*
873 =====================
874 =
875 = MM_SortMem
876 =
877 = Throws out all purgable stuff and compresses movable blocks
878 =
879 =====================
880 */
881
882 void MM_SortMem(mminfo_t *mm)
883 {
884         mmblocktype huge *scan,huge *last,huge *next;
885         unsigned        start,length,source,dest,oldborder;
886         int                     playing;
887
888         //
889         // lock down a currently playing sound
890         //
891 /*++++  playing = SD_SoundPlaying ();
892         if(playing)
893         {
894                 switch (SoundMode)
895                 {
896                 case sdm_PC:
897                         playing += STARTPCSOUNDS;
898                         break;
899                 case sdm_AdLib:
900                         playing += STARTADLIBSOUNDS;
901                         break;
902                 }
903                 MM_SetLock(&(memptr)audiosegs[playing],true);
904         }
905
906
907         SD_StopSound();*/
908 //      oldborder = bordercolor;
909 //      VW_ColorBorder (15);
910
911         if(beforesort)
912                 beforesort();
913
914         scan = mm->mmhead;
915
916         last = NULL;            // shut up compiler warning
917
918         while(scan)
919         {
920                 if(scan->attributes & LOCKBIT)
921                 {
922                 //
923                 // block is locked, so try to pile later blocks right after it
924                 //
925                         start = scan->start + scan->length;
926                 }
927                 else
928                 {
929                         if(scan->attributes & PURGEBITS)
930                         {
931                         //
932                         // throw out the purgable block
933                         //
934                                 next = scan->next;
935                                 MM_FreeBlock(scan, mm);
936                                 last->next = next;
937                                 scan = next;
938                                 continue;
939                         }
940                         else
941                         {
942                         //
943                         // push the non purgable block on top of the last moved block
944                         //
945                                 if(scan->start != start)
946                                 {
947                                         length = scan->length;
948                                         source = scan->start;
949                                         dest = start;
950                                         while(length > 0xf00)
951                                         {
952                                                 movedata(source,0,dest,0,0xf00*16);
953                                                 length -= 0xf00;
954                                                 source += 0xf00;
955                                                 dest += 0xf00;
956                                         }
957                                         movedata(source,0,dest,0,length*16);
958
959                                         scan->start = start;
960                                         *(unsigned *)scan->useptr = start;
961                                 }
962                                 start = scan->start + scan->length;
963                         }
964                 }
965
966                 last = scan;
967                 scan = scan->next;              // go to next block
968         }
969
970         mm->mmrover = mm->mmhead;
971
972         if(aftersort)
973                 aftersort();
974
975 //      VW_ColorBorder (oldborder);
976
977 /*++++  if(playing)
978                 MM_SetLock(&(memptr)audiosegs[playing],false);*/
979 }
980
981
982 //==========================================================================
983
984 //****#if 0
985 /*
986 =====================
987 =
988 = MM_ShowMemory
989 =
990 =====================
991 */
992
993 void MM_ShowMemory(mminfo_t *mm)
994 {
995         mmblocktype huge *scan;
996         unsigned color,temp;//, i;
997         long    end,owner;
998         char    scratch[80],str[10];
999
1000 //****  VW_SetDefaultColors();
1001 //****  VW_SetLineWidth(40);
1002 //++++mh        temp = bufferofs;
1003 //++++mh        bufferofs = 0;
1004 //****  VW_SetScreen (0,0);
1005
1006         scan = mm->mmhead;
1007
1008         end = -1;
1009
1010 //CA_OpenDebug ();
1011
1012         while (scan)
1013         {
1014                 if(scan->attributes & PURGEBITS)
1015                         color = 5;              // dark purple = purgable
1016                 else
1017                         color = 9;              // medium blue = non purgable
1018                 if(scan->attributes & LOCKBIT)
1019                         color = 12;             // red = locked
1020                 if(scan->start<=end)
1021                 {
1022                         printf("MM_ShowMemory: Memory block order currupted!");
1023                         return;
1024                 }
1025                 end = scan->start+scan->length-1;
1026 //++++          VW_Hlin(scan->start,(unsigned)end,0,color);
1027 //++++          VW_Plot(scan->start,0,15);
1028                 if(scan->next->start > end+1)
1029 //++++                  VW_Hlin(end+1,scan->next->start,0,0);   // black = free
1030
1031 //****#if 0
1032 printf("Location:");
1033 printf("%x\t", scan->start);
1034 strcpy (scratch,"Size:");
1035 ltoa ((dword)scan->length*16,str,10);
1036 strcat (scratch,str);
1037 strcat (scratch,"\tOwner:0x");
1038 owner = (unsigned)scan->useptr;
1039 ultoa (owner,str,16);
1040 strcat (scratch,str);
1041 strcat (scratch,"\n");
1042 //++++write (debughandle,scratch,strlen(scratch));
1043 fprintf(stdout, "%s", scratch);
1044 //****#endif
1045
1046                 scan = scan->next;
1047         }
1048
1049 //CA_CloseDebug ();
1050
1051 //++++mh        IN_Ack();
1052 //****  VW_SetLineWidth(64);
1053 //++++mh        bufferofs = temp;
1054 }
1055 //****#endif
1056
1057 //==========================================================================
1058
1059
1060 /*
1061 ======================
1062 =
1063 = MM_UnusedMemory
1064 =
1065 = Returns the total free space without purging
1066 =
1067 ======================
1068 */
1069
1070 dword MM_UnusedMemory(mminfo_t *mm)
1071 {
1072         unsigned free;
1073         mmblocktype huge *scan;
1074
1075         free = 0;
1076         scan = mm->mmhead;
1077
1078         while(scan->next)
1079         {
1080                 free += scan->next->start - (scan->start + scan->length);
1081                 scan = scan->next;
1082         }
1083
1084         return free*16l;
1085 //      return free;
1086 }
1087
1088 //==========================================================================
1089
1090
1091 /*
1092 ======================
1093 =
1094 = MM_TotalFree
1095 =
1096 = Returns the total free space with purging
1097 =
1098 ======================
1099 */
1100
1101 dword MM_TotalFree(mminfo_t *mm)
1102 {
1103         unsigned free;
1104         mmblocktype huge *scan;
1105
1106         free = 0;
1107         scan = mm->mmhead;
1108
1109         while(scan->next)
1110         {
1111                 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1112                         free += scan->length;
1113                 free += scan->next->start - (scan->start + scan->length);
1114                 scan = scan->next;
1115         }
1116
1117         return free*16l;
1118 //      return free;
1119 }
1120
1121 //==========================================================================
1122
1123 /*
1124 =====================
1125 =
1126 = MM_Report
1127 =
1128 =====================
1129 */
1130
1131 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1132 {
1133         if(MML_CheckForEMS())
1134         {
1135                 printf("EMM %x available\n", mm->EMSVer);
1136                 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1137                 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1138                 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1139         }
1140         if(MML_CheckForXMS(mm)) printf("XMSaddr=%x\n", *XMSaddr);
1141         printf("near=%lu\n", mmi->nearheap);
1142         printf("far=%lu\n", mmi->farheap);
1143         printf("EMSmem=%lu\n", mmi->EMSmem);
1144         printf("XMSmem=%lu\n", mmi->XMSmem);
1145         printf("mainmem=%lu\n", mmi->mainmem);
1146         printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1147         printf("TotalFree=%lu\n", MM_TotalFree(mm));
1148 //      printf("\n");
1149 //      printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1150 //      printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1151 }
1152
1153 //==========================================================================
1154
1155 /*
1156 =====================
1157 =
1158 = MM_EMSVer
1159 =
1160 =====================
1161
1162
1163 int MM_EMSVer(void)
1164 {
1165         int EMSver;
1166         __asm
1167         {
1168                 mov             ah,EMS_VERSION
1169                 int             EMS_INT
1170                 mov             EMSver,ax
1171         }
1172         return(EMSver);
1173 }*/
1174
1175 //==========================================================================
1176
1177 /*
1178 =====================
1179 =
1180 = MM_BombOnError
1181 =
1182 =====================
1183 */
1184
1185 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1186 {
1187         mm->bombonerror = bomb;
1188 }
1189
1190 void MM_GetNewBlock(mminfo_t *mm)
1191 {
1192         if(!mm->mmfree)
1193                 MML_ClearBlock(mm);
1194         mm->mmnew=mm->mmfree;
1195         mm->mmfree=mm->mmfree->next;
1196         /*if(!(mm->mmnew=mm->mmfree))
1197         {
1198                 printf("MM_GETNEWBLOCK: No free blocks!");
1199                 return;
1200         }
1201         mm->mmfree=mm->mmfree->next;*/
1202 }
1203
1204 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1205 {
1206         x->useptr=NULL;
1207         x->next=mm->mmfree;
1208         mm->mmfree=x;
1209 }