]> 4ch.mooo.com Git - 16.git/blob - src/lib/16_mm.c
huge pointers!
[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         __asm
339         {
340                 mov     ax,0x4310
341                 int     0x2f
342                 mov     [WORD PTR XMSaddr],bx
343                 mov     [WORD PTR XMSaddr+2],es         // function pointer to XMS driver
344         }
345 getmemory:
346         __asm
347         {
348                 mov     ah,XMS_ALLOCUMB
349                 mov     dx,0xffff                                       // try for largest block possible
350                 call    [DWORD PTR XMSaddr]
351                 or      ax,ax
352                 jnz     gotone
353
354                 cmp     bl,0xb0                                         // error: smaller UMB is available
355                 jne     done;
356
357                 mov     ah,XMS_ALLOCUMB
358                 call    [DWORD PTR XMSaddr]             // DX holds largest available UMB
359                 or      ax,ax
360                 jz      done                                            // another error...
361
362 gotone:
363                 mov     [base],bx
364                 mov     [size],dx
365 done:
366         }
367         MML_UseSpace(base,size, mm);
368         mmi->XMSmem += size*16;
369         mm->UMBbase[mm->numUMBs] = base;
370         mm->numUMBs++;
371         if(mm->numUMBs < MAXUMBS)
372                 goto getmemory;
373 }
374
375
376 /*
377 ======================
378 =
379 = MML_ShutdownXMS
380 =
381 ======================
382 */
383
384 void MML_ShutdownXMS(mminfo_t *mm)
385 {
386         int     i;
387         unsigned        base;
388
389         for (i=0;i<mm->numUMBs;i++)
390         {
391                 base = mm->UMBbase[i];
392                 __asm
393                 {
394                         mov     ah,XMS_FREEUMB
395                         mov     dx,[base]
396                         call    [DWORD PTR XMSaddr]
397                 }
398         }
399 }
400
401 //==========================================================================
402
403 /*
404 ======================
405 =
406 = MML_UseSpace
407 =
408 = Marks a range of paragraphs as usable by the memory manager
409 = This is used to mark space for the near heap, far heap, ems page frame,
410 = and upper memory blocks
411 =
412 ======================
413 */
414
415 void MML_UseSpace(unsigned segstart, unsigned seglength, mminfo_t *mm)
416 {
417         mmblocktype huge *scan,huge *last;
418         unsigned        oldend;
419         //++++if(mm->EMSVer)
420         long            extra;
421
422         scan = last = mm->mmhead;
423         mm->mmrover = mm->mmhead;               // reset rover to start of memory
424
425 //
426 // search for the block that contains the range of segments
427 //
428         while(scan->start+scan->length < segstart)
429         {
430                 last = scan;
431                 scan = scan->next;
432         }
433
434 //
435 // take the given range out of the block
436 //
437         oldend = scan->start + scan->length;
438         extra = oldend - (segstart+seglength);
439         if(extra < 0)
440         {
441                 printf("MML_UseSpace: Segment spans two blocks!");
442                 return;
443         }
444
445
446         if(segstart == scan->start)
447         {
448                 last->next = scan->next;                        // unlink block
449                 MM_FreeBlock(scan, mm);
450                 scan = last;
451         }
452         else
453                 scan->length = segstart-scan->start;    // shorten block
454
455         if(extra > 0)
456         {
457                 MM_GetNewBlock(mm);
458                 mm->mmnew->next = scan->next;
459                 scan->next = mm->mmnew;
460                 mm->mmnew->start = segstart+seglength;
461                 mm->mmnew->length = extra;
462                 mm->mmnew->attributes = LOCKBIT;
463         }
464
465 }
466
467 //==========================================================================
468
469 /*
470 ====================
471 =
472 = MML_ClearBlock
473 =
474 = We are out of blocks, so free a purgable block
475 =
476 ====================
477 */
478
479 void MML_ClearBlock(mminfo_t *mm)
480 {
481         mmblocktype huge *scan,huge *last;
482
483         scan = mm->mmhead->next;
484
485         while(scan)
486         {
487                 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
488                 {
489                         MM_FreePtr(scan->useptr, mm);
490                         return;
491                 }
492                 scan = scan->next;
493         }
494
495         printf("MM_ClearBlock: No purgable blocks!");
496 }
497
498
499 //==========================================================================
500
501 /*
502 ===================
503 =
504 = MM_Startup
505 =
506 = Grabs all space from turbo with malloc/farmalloc
507 = Allocates bufferseg misc buffer
508 =
509 ===================
510 */
511
512 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
513 {
514         int i;
515         dword length;
516         void huge       *start;
517         unsigned        segstart,seglength,endfree;
518
519         if(mm->mmstarted)
520                 MM_Shutdown(mm);
521
522         mm->mmstarted = true;
523         mm->bombonerror = true;
524 //
525 // set up the linked list (everything in the free list;
526 //
527         mm->mmhead = NULL;
528         mm->mmfree = &(mm->mmblocks[0]);
529         for(i=0;i<MAXBLOCKS-1;i++)
530         {
531                 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
532         }
533         mm->mmblocks[i].next = NULL;
534
535 //
536 // locked block of all memory until we punch out free space
537 //
538         MM_GetNewBlock(mm);
539         mm->mmhead = mm->mmnew;                         // this will allways be the first node
540         mm->mmnew->start = 0;
541         mm->mmnew->length = 0xffff;
542         mm->mmnew->attributes = LOCKBIT;
543         mm->mmnew->next = NULL;
544         mm->mmrover = mm->mmhead;
545
546
547 //
548 // get all available near conventional memory segments
549 //
550 //----  length=coreleft();
551         _nheapgrow();
552         length=_memavl();
553         start = (void huge *)(mm->nearheap = malloc(length));
554
555         length -= 16-(FP_OFF(start)&15);
556         length -= SAVENEARHEAP;
557         seglength = length / 16;                        // now in paragraphs
558         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
559         MML_UseSpace(segstart,seglength, mm);
560         mmi->nearheap = length;
561
562 //
563 // get all available far conventional memory segments
564 //
565 //----  length=farcoreleft();
566         _fheapgrow();
567         length=_memavl();
568         start = mm->farheap = halloc(length, 1);
569         //start = mm->farheap = _fmalloc(length);
570         length -= 16-(FP_OFF(start)&15);
571         length -= SAVEFARHEAP;
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->farheap = length;
576         mmi->mainmem = mmi->nearheap + mmi->farheap;
577
578
579 //
580 // detect EMS and allocate up to 64K at page frame
581 //
582         mmi->EMSmem = 0;
583         for(i = 1;i < __argc;i++)
584         {
585                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
586                         goto emsskip;                           // param NOEMS
587         }
588         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!
589         if(MML_CheckForEMS())
590         {
591 //printf("EMS1\n");
592                 MML_SetupEMS(mm);                                       // allocate space
593                 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!
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
669                                 ,huge *purge,huge *next;
670         int                     search;
671         unsigned        needed,startseg;
672
673         needed = (size+15)/16;          // convert size from bytes to paragraphs
674
675         MM_GetNewBlock(mm);                             // fill in start and next after a spot is found
676         mm->mmnew->length = needed;
677         mm->mmnew->useptr = baseptr;
678         mm->mmnew->attributes = BASEATTRIBUTES;
679
680         for(search = 0; search<3; search++)
681         {
682         //
683         // first search:        try to allocate right after the rover, then on up
684         // second search:       search from the head pointer up to the rover
685         // third search:        compress memory, then scan from start
686                 if(search == 1 && mm->mmrover == mm->mmhead)
687                         search++;
688
689                 switch(search)
690                 {
691                 case 0:
692                         lastscan = mm->mmrover;
693                         scan = mm->mmrover->next;
694                         endscan = NULL;
695                         break;
696                 case 1:
697                         lastscan = mm->mmhead;
698                         scan = mm->mmhead->next;
699                         endscan = mm->mmrover;
700                         break;
701                 case 2:
702                         MM_SortMem(mm);
703                         lastscan = mm->mmhead;
704                         scan = mm->mmhead->next;
705                         endscan = NULL;
706                         break;
707                 }
708
709                 startseg = lastscan->start + lastscan->length;
710
711                 while(scan != endscan)
712                 {
713                         if(scan->start - startseg >= needed)
714                         {
715                         //
716                         // got enough space between the end of lastscan and
717                         // the start of scan, so throw out anything in the middle
718                         // and allocate the new block
719                         //
720                                 purge = lastscan->next;
721                                 lastscan->next = mm->mmnew;
722                                 mm->mmnew->start = *(unsigned *)baseptr = startseg;
723                                 mm->mmnew->next = scan;
724                                 while(purge != scan)
725                                 {       // free the purgable block
726                                         next = purge->next;
727                                         MM_FreeBlock(purge, mm);
728                                         purge = next;           // purge another if not at scan
729                                 }
730                                 mm->mmrover = mm->mmnew;
731                                 return; // good allocation!
732                         }
733
734                         //
735                         // if this block is purge level zero or locked, skip past it
736                         //
737                         if((scan->attributes & LOCKBIT)
738                                 || !(scan->attributes & PURGEBITS) )
739                         {
740                                 lastscan = scan;
741                                 startseg = lastscan->start + lastscan->length;
742                         }
743
744
745                         scan=scan->next;                // look at next line
746                 }
747         }
748
749         if (mm->bombonerror)
750                 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
751         else
752                 mm->mmerror = true;
753 }
754
755 //==========================================================================
756
757 /*
758 ====================
759 =
760 = MM_FreePtr
761 =
762 = Allocates an unlocked, unpurgable block
763 =
764 ====================
765 */
766
767 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
768 {
769         mmblocktype huge *scan,huge *last;
770
771         last = mm->mmhead;
772         scan = last->next;
773
774         if(baseptr == mm->mmrover->useptr)      // removed the last allocated block
775                 mm->mmrover = mm->mmhead;
776
777         while(scan->useptr != baseptr && scan)
778         {
779                 last = scan;
780                 scan = scan->next;
781         }
782
783         if(!scan)
784         {
785                 printf("MM_FreePtr: Block not found!");
786                 return;
787         }
788
789         last->next = scan->next;
790
791         MM_FreeBlock(scan, mm);
792 }
793 //==========================================================================
794
795 /*
796 =====================
797 =
798 = MM_SetPurge
799 =
800 = Sets the purge level for a block (locked blocks cannot be made purgable)
801 =
802 =====================
803 */
804
805 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
806 {
807         mmblocktype huge *start;
808
809         start = mm->mmrover;
810
811         do
812         {
813                 if(mm->mmrover->useptr == baseptr)
814                         break;
815
816                 mm->mmrover = mm->mmrover->next;
817
818                 if(!mm->mmrover)
819                         mm->mmrover = mm->mmhead;
820                 else if(mm->mmrover == start)
821                 {
822                         printf("MM_SetPurge: Block not found!");
823                         return;
824                 }
825
826         } while(1);
827
828         mm->mmrover->attributes &= ~PURGEBITS;
829         mm->mmrover->attributes |= purge;
830 }
831
832 //==========================================================================
833
834 /*
835 =====================
836 =
837 = MM_SetLock
838 =
839 = Locks / unlocks the block
840 =
841 =====================
842 */
843
844 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
845 {
846         mmblocktype huge *start;
847
848         start = mm->mmrover;
849
850         do
851         {
852                 if(mm->mmrover->useptr == baseptr)
853                         break;
854
855                 mm->mmrover = mm->mmrover->next;
856
857                 if(!mm->mmrover)
858                         mm->mmrover = mm->mmhead;
859                 else if(mm->mmrover == start)
860                 {
861                         printf("MM_SetLock: Block not found!");
862                         return;
863                 }
864
865         } while(1);
866
867         mm->mmrover->attributes &= ~LOCKBIT;
868         mm->mmrover->attributes |= locked*LOCKBIT;
869 }
870
871 //==========================================================================
872
873 /*
874 =====================
875 =
876 = MM_SortMem
877 =
878 = Throws out all purgable stuff and compresses movable blocks
879 =
880 =====================
881 */
882
883 void MM_SortMem(mminfo_t *mm)
884 {
885         mmblocktype huge *scan,huge *last,huge *next;
886         unsigned        start,length,source,dest,oldborder;
887         int                     playing;
888
889         //
890         // lock down a currently playing sound
891         //
892 /*++++  playing = SD_SoundPlaying ();
893         if(playing)
894         {
895                 switch (SoundMode)
896                 {
897                 case sdm_PC:
898                         playing += STARTPCSOUNDS;
899                         break;
900                 case sdm_AdLib:
901                         playing += STARTADLIBSOUNDS;
902                         break;
903                 }
904                 MM_SetLock(&(memptr)audiosegs[playing],true);
905         }
906
907
908         SD_StopSound();*/
909 //      oldborder = bordercolor;
910 //      VW_ColorBorder (15);
911
912         if(beforesort)
913                 beforesort();
914
915         scan = mm->mmhead;
916
917         last = NULL;            // shut up compiler warning
918
919         while(scan)
920         {
921                 if(scan->attributes & LOCKBIT)
922                 {
923                 //
924                 // block is locked, so try to pile later blocks right after it
925                 //
926                         start = scan->start + scan->length;
927                 }
928                 else
929                 {
930                         if(scan->attributes & PURGEBITS)
931                         {
932                         //
933                         // throw out the purgable block
934                         //
935                                 next = scan->next;
936                                 MM_FreeBlock(scan, mm);
937                                 last->next = next;
938                                 scan = next;
939                                 continue;
940                         }
941                         else
942                         {
943                         //
944                         // push the non purgable block on top of the last moved block
945                         //
946                                 if(scan->start != start)
947                                 {
948                                         length = scan->length;
949                                         source = scan->start;
950                                         dest = start;
951                                         while(length > 0xf00)
952                                         {
953                                                 movedata(source,0,dest,0,0xf00*16);
954                                                 length -= 0xf00;
955                                                 source += 0xf00;
956                                                 dest += 0xf00;
957                                         }
958                                         movedata(source,0,dest,0,length*16);
959
960                                         scan->start = start;
961                                         *(unsigned *)scan->useptr = start;
962                                 }
963                                 start = scan->start + scan->length;
964                         }
965                 }
966
967                 last = scan;
968                 scan = scan->next;              // go to next block
969         }
970
971         mm->mmrover = mm->mmhead;
972
973         if(aftersort)
974                 aftersort();
975
976 //      VW_ColorBorder (oldborder);
977
978 /*++++  if(playing)
979                 MM_SetLock(&(memptr)audiosegs[playing],false);*/
980 }
981
982
983 //==========================================================================
984
985 //****#if 0
986 /*
987 =====================
988 =
989 = MM_ShowMemory
990 =
991 =====================
992 */
993
994 void MM_ShowMemory(mminfo_t *mm)
995 {
996         mmblocktype huge *scan;
997         unsigned color,temp;//, i;
998         long    end,owner;
999         char    scratch[80],str[10];
1000
1001 //****  VW_SetDefaultColors();
1002 //****  VW_SetLineWidth(40);
1003 //++++mh        temp = bufferofs;
1004 //++++mh        bufferofs = 0;
1005 //****  VW_SetScreen (0,0);
1006
1007         scan = mm->mmhead;
1008
1009         end = -1;
1010
1011 //CA_OpenDebug ();
1012
1013         while (scan)
1014         {
1015                 if(scan->attributes & PURGEBITS)
1016                         color = 5;              // dark purple = purgable
1017                 else
1018                         color = 9;              // medium blue = non purgable
1019                 if(scan->attributes & LOCKBIT)
1020                         color = 12;             // red = locked
1021                 if(scan->start<=end)
1022                 {
1023                         printf("MM_ShowMemory: Memory block order currupted!");
1024                         return;
1025                 }
1026                 end = scan->start+scan->length-1;
1027 //++++          VW_Hlin(scan->start,(unsigned)end,0,color);
1028 //++++          VW_Plot(scan->start,0,15);
1029                 if(scan->next->start > end+1)
1030 //++++                  VW_Hlin(end+1,scan->next->start,0,0);   // black = free
1031
1032 //****#if 0
1033 printf("Location:");
1034 printf("%x\t", scan->start);
1035 strcpy (scratch,"Size:");
1036 ltoa ((long)scan->length*16,str,10);
1037 strcat (scratch,str);
1038 strcat (scratch,"\tOwner:0x");
1039 owner = (unsigned)scan->useptr;
1040 ultoa (owner,str,16);
1041 strcat (scratch,str);
1042 strcat (scratch,"\n");
1043 //++++write (debughandle,scratch,strlen(scratch));
1044 fprintf(stdout, "%s", scratch);
1045 //****#endif
1046
1047                 scan = scan->next;
1048         }
1049
1050 //CA_CloseDebug ();
1051
1052 //++++mh        IN_Ack();
1053 //****  VW_SetLineWidth(64);
1054 //++++mh        bufferofs = temp;
1055 }
1056 //****#endif
1057
1058 //==========================================================================
1059
1060
1061 /*
1062 ======================
1063 =
1064 = MM_UnusedMemory
1065 =
1066 = Returns the total free space without purging
1067 =
1068 ======================
1069 */
1070
1071 dword MM_UnusedMemory(mminfo_t *mm)
1072 {
1073         unsigned free;
1074         mmblocktype huge *scan;
1075
1076         free = 0;
1077         scan = mm->mmhead;
1078
1079         while(scan->next)
1080         {
1081                 free += scan->next->start - (scan->start + scan->length);
1082                 scan = scan->next;
1083         }
1084
1085         return free*16l;
1086 //      return free;
1087 }
1088
1089 //==========================================================================
1090
1091
1092 /*
1093 ======================
1094 =
1095 = MM_TotalFree
1096 =
1097 = Returns the total free space with purging
1098 =
1099 ======================
1100 */
1101
1102 dword MM_TotalFree(mminfo_t *mm)
1103 {
1104         unsigned free;
1105         mmblocktype huge *scan;
1106
1107         free = 0;
1108         scan = mm->mmhead;
1109
1110         while(scan->next)
1111         {
1112                 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1113                         free += scan->length;
1114                 free += scan->next->start - (scan->start + scan->length);
1115                 scan = scan->next;
1116         }
1117
1118         return free*16l;
1119 //      return free;
1120 }
1121
1122 //==========================================================================
1123
1124 /*
1125 =====================
1126 =
1127 = MM_Report
1128 =
1129 =====================
1130 */
1131
1132 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1133 {
1134         if(MML_CheckForEMS())
1135         {
1136                 printf("EMM %x available\n", mm->EMSVer);
1137                 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1138                 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1139                 printf("EMSpageframe=%Fp\n", mm->EMSpageframe);
1140         }
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 }