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