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