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