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