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