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