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