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