]> 4ch.mooo.com Git - 16.git/blob - src/lib/16_mm.c
c499ea282b804e7102c6c2810bb110cd8d315c32
[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         dword           extra;
428
429         scan = last = mm->mmhead;
430         mm->mmrover = mm->mmhead;               // reset rover to start of memory
431         scan->segm=1;
432
433 //
434 // search for the block that contains the range of segments
435 //
436         while(scan->start+scan->length < segstart)
437         {
438                 last = scan;
439                 scan = scan->next;
440         }
441
442         //find out how many blocks it span!
443         if(seglength>0xfffflu)
444         {
445                 scan->segm=seglength/0xfffflu;
446         }
447
448 //
449 // take the given range out of the block
450 //
451         oldend = scan->start + scan->length;
452         extra = oldend - (segstart+seglength);
453         //++++emsver stuff!
454         if(extra>0xfffflu)
455         {
456                 /*__asm
457                 {
458                         push    ds
459                         mov     ax,ds
460                         inc             ax
461                         mov     ds,ax
462                 }*/
463 printf("segm=%u ", scan->segm);
464 printf("ex=%lu  ", extra);
465 printf("len=%u  ", scan->length);
466 printf("segsta=%u       ", segstart);
467 printf("seglen=%lu\n", seglength);
468
469 //MML_UseSpace(?segstart?, ?length?, mm);
470
471                 /*__asm
472                 {
473                         pop ds
474                 }*/
475                 //printf("MML_UseSpace: Segment spans two blocks!\n");
476         }
477
478 //segu:
479 //++++todo: linked list of segment!
480 //printf("segm=%lu\n", segm);
481         if(segstart == scan->start)
482         {
483                 last->next = scan->next;                        // unlink block
484                 MM_FreeBlock(scan, mm);
485                 scan = last;
486         }
487         else
488                 scan->length = segstart-scan->start;    // shorten block
489
490 //      segm--;
491
492         if(extra > 0)
493         {
494                 MM_GetNewBlock(mm);
495                 mm->mmnew->next = scan->next;
496                 scan->next = mm->mmnew;
497                 mm->mmnew->start = segstart+seglength;
498                 mm->mmnew->length = extra;
499                 mm->mmnew->attributes = LOCKBIT;
500         }//else if(segm>0) goto segu;
501
502 }
503
504 //==========================================================================
505
506 /*
507 ====================
508 =
509 = MML_ClearBlock
510 =
511 = We are out of blocks, so free a purgable block
512 =
513 ====================
514 */
515
516 void MML_ClearBlock(mminfo_t *mm)
517 {
518         mmblocktype huge *scan,huge *last;
519
520         scan = mm->mmhead->next;
521
522         while(scan)
523         {
524                 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
525                 {
526                         MM_FreePtr(scan->useptr, mm);
527                         return;
528                 }
529                 scan = scan->next;
530         }
531
532         printf("MM_ClearBlock: No purgable blocks!\n");
533 }
534
535
536 //==========================================================================
537
538 /*
539 ===================
540 =
541 = MM_Startup
542 =
543 = Grabs all space from turbo with malloc/farmalloc
544 = Allocates bufferseg misc buffer
545 =
546 ===================
547 */
548
549 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
550 {
551         int i;
552         dword length;//,farlen;
553         void huge       *start;
554         unsigned        segstart,seglength,endfree;
555
556         if(mm->mmstarted)
557                 MM_Shutdown(mm);
558
559         mm->mmstarted = true;
560         mm->bombonerror = true;
561 //
562 // set up the linked list (everything in the free list;
563 //
564         mm->mmhead = NULL;
565         mm->mmfree = &(mm->mmblocks[0]);
566         for(i=0;i<MAXBLOCKS-1;i++)
567         {
568                 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
569         }
570         mm->mmblocks[i].next = NULL;
571
572 //
573 // locked block of all memory until we punch out free space
574 //
575         MM_GetNewBlock(mm);
576         mm->mmhead = mm->mmnew;                         // this will allways be the first node
577         mm->mmnew->start = 0;
578         mm->mmnew->length = 0xffff;                     //todo: mm make it fucking massive as fuck!~
579         mm->mmnew->attributes = LOCKBIT;
580         mm->mmnew->next = NULL;
581         mm->mmrover = mm->mmhead;
582
583 //      farlen=_bios_memsize()*1024;
584
585 //
586 // get all available near conventional memory segments
587 //
588 //----  length=coreleft();
589         _nheapgrow();
590         length=_memavl();
591         start = (void huge *)(mm->nearheap = malloc(length));
592
593         length -= 16-(FP_OFF(start)&15);
594         length -= SAVENEARHEAP;
595         seglength = length / 16;                        // now in paragraphs
596         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
597         MML_UseSpace(segstart,seglength, mm);
598         mmi->nearheap = length;
599
600 //
601 // get all available far conventional memory segments
602 //
603 //----  length=farcoreleft();
604         _fheapgrow();
605         length=_memavl();
606         //length-=farlen;
607         start = mm->farheap = halloc(length, sizeof(dword));
608         //start = mm->farheap = _fmalloc(length);
609         length -= 16-(FP_OFF(start)&15);
610         length -= SAVEFARHEAP;
611         seglength = length / 16;                        // now in paragraphs
612         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
613         MML_UseSpace(segstart,seglength, mm);
614         mmi->farheap = length;
615         mmi->mainmem = mmi->nearheap + mmi->farheap;
616
617
618 //
619 // detect EMS and allocate up to 64K at page frame
620 //
621         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!
622         mmi->EMSmem = 0;
623         for(i = 1;i < __argc;i++)
624         {
625                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
626                         goto emsskip;                           // param NOEMS
627         }
628         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!
629         if(MML_CheckForEMS())
630         {
631 //printf("EMS1\n");
632                 MML_SetupEMS(mm);                                       // allocate space
633                 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!
634                 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
635                 MML_UseSpace(mm->EMSpageframe,(mm->EMSpagesmapped)*0x4000lu, mm);
636 //printf("EMS3\n");
637                 MM_MapEMS(mm);                                  // map in used pages
638 //printf("EMS4\n");
639                 mmi->EMSmem = (mm->EMSpagesmapped)*0x4000lu;
640         }
641
642 //
643 // detect XMS and get upper memory blocks
644 //
645 emsskip:
646         mmi->XMSmem = 0;
647         for(i = 1;i < __argc;i++)
648         {
649                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
650                         goto xmsskip;                           // param NOXMS
651         }
652         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!
653         if(MML_CheckForXMS(mm))
654         {
655                 printf("XMS!\n");
656                 MML_SetupXMS(mm, mmi);                                  // allocate as many UMBs as possible
657         }
658
659 //
660 // allocate the misc buffer
661 //
662 xmsskip:
663         mm->mmrover = mm->mmhead;               // start looking for space after low block
664
665         MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
666 }
667
668 //==========================================================================
669
670 /*
671 ====================
672 =
673 = MM_Shutdown
674 =
675 = Frees all conventional, EMS, and XMS allocated
676 =
677 ====================
678 */
679
680 void MM_Shutdown(mminfo_t *mm)
681 {
682         if(!(mm->mmstarted))
683                 return;
684
685         _ffree(mm->farheap);
686         printf("far freed\n");
687         free(mm->nearheap);
688         printf("near freed\n");
689         //hfree(mm->hugeheap);
690         //printf("huge freed\n");
691         if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("EMS freed\n"); }
692         if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("XMS freed\n"); }
693 }
694
695 //==========================================================================
696
697 /*
698 ====================
699 =
700 = MM_GetPtr
701 =
702 = Allocates an unlocked, unpurgable block
703 =
704 ====================
705 */
706
707 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
708 {
709         mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
710         int                     search;
711         unsigned        needed,startseg;
712
713         needed = (size+15)/16;          // convert size from bytes to paragraphs
714
715         MM_GetNewBlock(mm);                             // fill in start and next after a spot is found
716         mm->mmnew->length = needed;
717         mm->mmnew->useptr = baseptr;
718         mm->mmnew->attributes = BASEATTRIBUTES;
719
720         for(search = 0; search<3; search++)
721         {
722         //
723         // first search:        try to allocate right after the rover, then on up
724         // second search:       search from the head pointer up to the rover
725         // third search:        compress memory, then scan from start
726                 if(search == 1 && mm->mmrover == mm->mmhead)
727                         search++;
728
729                 switch(search)
730                 {
731                 case 0:
732                         lastscan = mm->mmrover;
733                         scan = mm->mmrover->next;
734                         endscan = NULL;
735                         break;
736                 case 1:
737                         lastscan = mm->mmhead;
738                         scan = mm->mmhead->next;
739                         endscan = mm->mmrover;
740                         break;
741                 case 2:
742                         MM_SortMem(mm);
743                         lastscan = mm->mmhead;
744                         scan = mm->mmhead->next;
745                         endscan = NULL;
746                         break;
747                 }
748
749                 startseg = lastscan->start + lastscan->length;
750
751                 while(scan != endscan)
752                 {
753                         if(scan->start - startseg >= needed)
754                         {
755                         //
756                         // got enough space between the end of lastscan and
757                         // the start of scan, so throw out anything in the middle
758                         // and allocate the new block
759                         //
760                                 purge = lastscan->next;
761                                 lastscan->next = mm->mmnew;
762                                 mm->mmnew->start = *(unsigned *)baseptr = startseg;
763                                 mm->mmnew->next = scan;
764                                 while(purge != scan)
765                                 {       // free the purgable block
766                                         next = purge->next;
767                                         MM_FreeBlock(purge, mm);
768                                         purge = next;           // purge another if not at scan
769                                 }
770                                 mm->mmrover = mm->mmnew;
771                                 return; // good allocation!
772                         }
773
774                         //
775                         // if this block is purge level zero or locked, skip past it
776                         //
777                         if((scan->attributes & LOCKBIT)
778                                 || !(scan->attributes & PURGEBITS) )
779                         {
780                                 lastscan = scan;
781                                 startseg = lastscan->start + lastscan->length;
782                         }
783
784
785                         scan=scan->next;                // look at next line
786                 }
787         }
788
789         if (mm->bombonerror)
790                 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
791         else
792                 mm->mmerror = true;
793 }
794
795 //==========================================================================
796
797 /*
798 ====================
799 =
800 = MM_FreePtr
801 =
802 = Allocates an unlocked, unpurgable block
803 =
804 ====================
805 */
806
807 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
808 {
809         mmblocktype huge *scan,huge *last;
810
811         last = mm->mmhead;
812         scan = last->next;
813
814         if(baseptr == mm->mmrover->useptr)      // removed the last allocated block
815                 mm->mmrover = mm->mmhead;
816
817         while(scan->useptr != baseptr && scan)
818         {
819                 last = scan;
820                 scan = scan->next;
821         }
822
823         if(!scan)
824         {
825                 printf("MM_FreePtr: Block not found!");
826                 return;
827         }
828
829         last->next = scan->next;
830
831         MM_FreeBlock(scan, mm);
832 }
833 //==========================================================================
834
835 /*
836 =====================
837 =
838 = MM_SetPurge
839 =
840 = Sets the purge level for a block (locked blocks cannot be made purgable)
841 =
842 =====================
843 */
844
845 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
846 {
847         mmblocktype huge *start;
848
849         start = mm->mmrover;
850
851         do
852         {
853                 if(mm->mmrover->useptr == baseptr)
854                         break;
855
856                 mm->mmrover = mm->mmrover->next;
857
858                 if(!mm->mmrover)
859                         mm->mmrover = mm->mmhead;
860                 else if(mm->mmrover == start)
861                 {
862                         printf("MM_SetPurge: Block not found!");
863                         return;
864                 }
865
866         } while(1);
867
868         mm->mmrover->attributes &= ~PURGEBITS;
869         mm->mmrover->attributes |= purge;
870 }
871
872 //==========================================================================
873
874 /*
875 =====================
876 =
877 = MM_SetLock
878 =
879 = Locks / unlocks the block
880 =
881 =====================
882 */
883
884 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
885 {
886         mmblocktype huge *start;
887
888         start = mm->mmrover;
889
890         do
891         {
892                 if(mm->mmrover->useptr == baseptr)
893                         break;
894
895                 mm->mmrover = mm->mmrover->next;
896
897                 if(!mm->mmrover)
898                         mm->mmrover = mm->mmhead;
899                 else if(mm->mmrover == start)
900                 {
901                         printf("MM_SetLock: Block not found!");
902                         return;
903                 }
904
905         } while(1);
906
907         mm->mmrover->attributes &= ~LOCKBIT;
908         mm->mmrover->attributes |= locked*LOCKBIT;
909 }
910
911 //==========================================================================
912
913 /*
914 =====================
915 =
916 = MM_SortMem
917 =
918 = Throws out all purgable stuff and compresses movable blocks
919 =
920 =====================
921 */
922
923 void MM_SortMem(mminfo_t *mm)
924 {
925         mmblocktype huge *scan,huge *last,huge *next;
926         unsigned        start,length,source,dest,oldborder;
927         int                     playing;
928
929         //
930         // lock down a currently playing sound
931         //
932 /*++++  playing = SD_SoundPlaying ();
933         if(playing)
934         {
935                 switch (SoundMode)
936                 {
937                 case sdm_PC:
938                         playing += STARTPCSOUNDS;
939                         break;
940                 case sdm_AdLib:
941                         playing += STARTADLIBSOUNDS;
942                         break;
943                 }
944                 MM_SetLock(&(memptr)audiosegs[playing],true);
945         }
946
947
948         SD_StopSound();*/
949 //      oldborder = bordercolor;
950 //      VW_ColorBorder (15);
951
952         if(beforesort)
953                 beforesort();
954
955         scan = mm->mmhead;
956
957         last = NULL;            // shut up compiler warning
958
959         while(scan)
960         {
961                 if(scan->attributes & LOCKBIT)
962                 {
963                 //
964                 // block is locked, so try to pile later blocks right after it
965                 //
966                         start = scan->start + scan->length;
967                 }
968                 else
969                 {
970                         if(scan->attributes & PURGEBITS)
971                         {
972                         //
973                         // throw out the purgable block
974                         //
975                                 next = scan->next;
976                                 MM_FreeBlock(scan, mm);
977                                 last->next = next;
978                                 scan = next;
979                                 continue;
980                         }
981                         else
982                         {
983                         //
984                         // push the non purgable block on top of the last moved block
985                         //
986                                 if(scan->start != start)
987                                 {
988                                         length = scan->length;
989                                         source = scan->start;
990                                         dest = start;
991                                         while(length > 0xf00)
992                                         {
993                                                 movedata(source,0,dest,0,0xf00*16);
994                                                 length -= 0xf00;
995                                                 source += 0xf00;
996                                                 dest += 0xf00;
997                                         }
998                                         movedata(source,0,dest,0,length*16);
999
1000                                         scan->start = start;
1001                                         *(unsigned *)scan->useptr = start;
1002                                 }
1003                                 start = scan->start + scan->length;
1004                         }
1005                 }
1006
1007                 last = scan;
1008                 scan = scan->next;              // go to next block
1009         }
1010
1011         mm->mmrover = mm->mmhead;
1012
1013         if(aftersort)
1014                 aftersort();
1015
1016 //      VW_ColorBorder (oldborder);
1017
1018 /*++++  if(playing)
1019                 MM_SetLock(&(memptr)audiosegs[playing],false);*/
1020 }
1021
1022
1023 //==========================================================================
1024
1025 //****#if 0
1026 /*
1027 =====================
1028 =
1029 = MM_ShowMemory
1030 =
1031 =====================
1032 */
1033
1034 void MM_ShowMemory(mminfo_t *mm)
1035 {
1036         mmblocktype huge *scan;
1037         unsigned color,temp;//, i;
1038         long    end,owner;
1039         char    scratch[160],str[16];
1040
1041 //****  VW_SetDefaultColors();
1042 //****  VW_SetLineWidth(40);
1043 //++++mh        temp = bufferofs;
1044 //++++mh        bufferofs = 0;
1045 //****  VW_SetScreen (0,0);
1046
1047         scan = mm->mmhead;
1048
1049         end = -1;
1050
1051 //CA_OpenDebug ();
1052
1053         while(scan)
1054         {
1055                 if(scan->attributes & PURGEBITS)
1056                         color = 5;              // dark purple = purgable
1057                 else
1058                         color = 9;              // medium blue = non purgable
1059                 if(scan->attributes & LOCKBIT)
1060                         color = 12;             // red = locked
1061                 if(scan->start<=end)
1062                 {
1063                         printf("\nMM_ShowMemory: Memory block order currupted!\n");
1064                         return;
1065                 }
1066                 end = scan->start+scan->length-1;
1067 //++++          VW_Hlin(scan->start,(unsigned)end,0,color);
1068 //++++          VW_Plot(scan->start,0,15);
1069                 if(scan->next->start > end+1)
1070 //++++                  VW_Hlin(end+1,scan->next->start,0,0);   // black = free
1071
1072 //****#if 0
1073 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!
1074 strcpy(scratch,"Location:");
1075 ultoa (scan->start,str,16);
1076 strcat (scratch,str);
1077 strcat (scratch,"\tSize:");
1078 ltoa ((dword)scan->length*16,str,10);
1079 strcat (scratch,str);
1080 strcat (scratch,"\tOwner:0x");
1081 owner = (unsigned)scan->useptr;
1082 ultoa (owner,str,16);
1083 strcat (scratch,str);
1084 strcat (scratch,"\n");
1085 //++++write (debughandle,scratch,strlen(scratch));
1086 fprintf(stdout, "%s", scratch);
1087 //****#endif
1088
1089                 scan = scan->next;
1090         }
1091
1092 //CA_CloseDebug ();
1093
1094 //++++mh        IN_Ack();
1095 //****  VW_SetLineWidth(64);
1096 //++++mh        bufferofs = temp;
1097 }
1098 //****#endif
1099
1100 //==========================================================================
1101
1102
1103 /*
1104 ======================
1105 =
1106 = MM_UnusedMemory
1107 =
1108 = Returns the total free space without purging
1109 =
1110 ======================
1111 */
1112
1113 dword MM_UnusedMemory(mminfo_t *mm)
1114 {
1115         dword free;
1116         mmblocktype huge *scan;
1117
1118         free = 0;
1119         scan = mm->mmhead;
1120
1121         while(scan->next)
1122         {
1123                 free += scan->next->start - (scan->start + scan->length);
1124                 scan = scan->next;
1125         }
1126
1127         return free*16l;
1128 //      return free;
1129 }
1130
1131 //==========================================================================
1132
1133
1134 /*
1135 ======================
1136 =
1137 = MM_TotalFree
1138 =
1139 = Returns the total free space with purging
1140 =
1141 ======================
1142 */
1143
1144 dword MM_TotalFree(mminfo_t *mm)
1145 {
1146         dword free;
1147         mmblocktype huge *scan;
1148
1149         free = 0;
1150         scan = mm->mmhead;
1151
1152         while(scan->next)
1153         {
1154                 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1155                         free += scan->length;
1156                 free += scan->next->start - (scan->start + scan->length);
1157                 scan = scan->next;
1158         }
1159
1160         return free*16l;
1161 //      return free;
1162 }
1163
1164 //==========================================================================
1165
1166 /*
1167 =====================
1168 =
1169 = MM_Report
1170 =
1171 =====================
1172 */
1173
1174 void MM_Report(mminfo_t *mm, mminfotype *mmi)
1175 {
1176         if(MML_CheckForEMS())
1177         {
1178                 printf("EMM %x available\n", mm->EMSVer);
1179                 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1180                 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1181                 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1182         }
1183         if(MML_CheckForXMS(mm)) printf("XMSaddr=%Fp\n", *XMSaddr);
1184         printf("near=%lu\n", mmi->nearheap);
1185         printf("far=%lu\n", mmi->farheap);
1186         printf("EMSmem=%lu\n", mmi->EMSmem);
1187         printf("XMSmem=%lu\n", mmi->XMSmem);
1188         printf("mainmem=%lu\n", mmi->mainmem);
1189         printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1190         printf("TotalFree=%lu\n", MM_TotalFree(mm));
1191 //      printf("\n");
1192 //      printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1193 //      printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1194 }
1195
1196 //==========================================================================
1197
1198 /*
1199 =====================
1200 =
1201 = MM_EMSVer
1202 =
1203 =====================
1204
1205
1206 int MM_EMSVer(void)
1207 {
1208         int EMSver;
1209         __asm
1210         {
1211                 mov             ah,EMS_VERSION
1212                 int             EMS_INT
1213                 mov             EMSver,ax
1214         }
1215         return(EMSver);
1216 }*/
1217
1218 //==========================================================================
1219
1220 /*
1221 =====================
1222 =
1223 = MM_BombOnError
1224 =
1225 =====================
1226 */
1227
1228 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1229 {
1230         mm->bombonerror = bomb;
1231 }
1232
1233 void MM_GetNewBlock(mminfo_t *mm)
1234 {
1235         if(!mm->mmfree)
1236                 MML_ClearBlock(mm);
1237         mm->mmnew=mm->mmfree;
1238         mm->mmfree=mm->mmfree->next;
1239         /*if(!(mm->mmnew=mm->mmfree))
1240         {
1241                 printf("MM_GETNEWBLOCK: No free blocks!");
1242                 return;
1243         }
1244         mm->mmfree=mm->mmfree->next;*/
1245 }
1246
1247 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1248 {
1249         x->useptr=NULL;
1250         x->next=mm->mmfree;
1251         mm->mmfree=x;
1252 }
1253
1254 void MM_seguin(void)
1255 {
1256         __asm
1257         {
1258                 push    ds
1259                 mov     ax,ds
1260                 inc             ax
1261                 mov     ds,ax
1262         }
1263 }
1264
1265 void MM_segude(void)
1266 {
1267         __asm
1268         {
1269                 pop ds
1270         }
1271 }
1272
1273 /*
1274 pull data from far and put it into ds var
1275 mov ax,es:si
1276 mov x,ax
1277 */
1278 /*
1279 ss stack segment
1280 sp top of stack
1281 bp bottem of stack
1282 */