OSDN Git Service

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