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