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