OSDN Git Service

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