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