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