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