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