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