]> 4ch.mooo.com Git - 16.git/blob - 16/exmmtest/16_mm.c
PEEEEEEEEEEEEEE
[16.git] / 16 / exmmtest / 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 "16_mm.h"
50 #pragma hdrstop
51
52 #pragma warn -pro
53 #pragma warn -use
54
55 /*#define GETNEWBLOCK {if(!(mmnew=mmfree))Quit("MM_GETNEWBLOCK: No free blocks!")\\r
56         ;mmfree=mmfree->next;}\r
57 \r
58 //#define GETNEWBLOCK {if(!mmfree)MML_ClearBlock();mmnew=mmfree;mmfree=mmfree->next;}\r
59 \r
60 #define FREEBLOCK(x) {*x->useptr=NULL;x->next=mmfree;mmfree=x;}*/
61
62 /*
63 =============================================================================
64
65                                                  GLOBAL VARIABLES
66
67 =============================================================================
68 */
69
70 void            (* beforesort) (void);
71 void            (* aftersort) (void);
72 void            (* XMSaddr) (void);             // far pointer to XMS driver
73
74 /*
75 =============================================================================
76
77                                                  LOCAL VARIABLES
78
79 =============================================================================
80 */
81
82 static  char *ParmStringsexmm[] = {"noems","noxms",""};
83
84 /*
85 ======================
86 =
87 = MML_CheckForEMS
88 =
89 = Routine from p36 of Extending DOS
90 =
91 =======================
92 */
93
94 boolean MML_CheckForEMS(void)
95 {
96         boolean emmcfems;
97         static char     emmname[] = "EMMXXXX0"; //fix by andrius4669
98 //              mov     dx,OFFSET emmname
99         __asm {
100                 //LEA   DX, emmname     //fix by andrius4669
101                 mov     dx,OFFSET emmname       //fix by andrius4669
102                 mov     ax,0x3d00
103                 int     0x21            // try to open EMMXXXX0 device
104                 jc      error
105
106                 mov     bx,ax
107                 mov     ax,0x4400
108
109                 int     0x21            // get device info
110                 jc      error
111
112                 and     dx,0x80
113                 jz      error
114
115                 mov     ax,0x4407
116
117                 int     0x21            // get status
118                 jc      error
119                 or      al,al
120                 jz      error
121
122                 mov     ah,0x3e
123                 int     0x21            // close handle
124                 jc      error
125                 //
126                 // EMS is good
127                 //
128                 mov     emmcfems,1
129                 jmp End
130         }
131                 error:
132         __asm {
133                 //
134                 // EMS is bad
135                 //
136                 mov     emmcfems,0
137         }
138                 End:
139         return(emmcfems);
140 }
141
142
143 /*
144 ======================
145 =
146 = MML_SetupEMS
147 =
148 =======================
149 */
150
151 byte MML_SetupEMS(mminfo_t *mm)
152 {
153         byte    str[160];
154         byte    err;
155         boolean errorflag=false;
156
157         unsigned int EMSVer = 0;
158         //byte  EMS_status;
159         unsigned        totalEMSpages,freeEMSpages,EMSpageframe,EMSpagesmapped,EMShandle;
160         totalEMSpages = freeEMSpages = EMSpageframe = EMSpagesmapped = 0;
161
162         __asm {
163                 mov     ah,EMS_STATUS
164                 int     EMS_INT                                         // make sure EMS hardware is present
165                 or      ah,ah
166                 //mov   [EMS_status],ah
167                 jnz     error
168
169                 mov     ah,EMS_VERSION
170                 int     EMS_INT
171                 or      ah,ah
172                 jnz     error
173                 mov     [EMSVer],ax                             //      set EMSVer
174                 cmp     al,0x32                                         // only work on ems 3.2 or greater
175                 jb      error
176
177                 mov     ah,EMS_GETFRAME
178                 int     EMS_INT                                         // find the page frame address
179                 or      ah,ah
180                 jnz     error
181                 mov     [EMSpageframe],bx
182
183                 mov     ah,EMS_GETPAGES
184                 int     EMS_INT                                         // find out how much EMS is there
185                 or      ah,ah
186                 jnz     error
187                 mov     [totalEMSpages],dx
188                 mov     [freeEMSpages],bx
189                 or      bx,bx
190                 jz      noEMS                                           // no EMS at all to allocate
191                                                                                         //EXPAND DONG!!!!
192                 cmp     [EMSVer],0x40
193                 jb      low
194                 cmp     bx,[freeEMSpages]
195                 jle     getpages
196                 mov     bx,[freeEMSpages]
197                 jmp     getpages
198         }
199
200 low:
201         __asm {
202                 cmp     bx,4
203                 jle     getpages                                        // there is only 1,2,3,or 4 pages
204                 mov     bx,4                                            // we can't use more than 4 pages
205         }
206
207 getpages:
208         __asm {
209                 mov     [EMSpagesmapped],bx
210                 mov     ah,EMS_ALLOCPAGES                       // allocate up to 64k of EMS
211                 int     EMS_INT
212                 or      ah,ah
213                 jnz     error
214                 mov     [EMShandle],dx
215                 jmp End
216         }
217 error:
218         __asm {
219                 mov     err,ah
220                 mov     errorflag,1
221                 jmp End
222         }
223 noEMS:
224 End:
225         if(errorflag==true)
226         {
227                 //err = CPURegs.h.ah;
228                 strcpy(str,"MM_SetupEMS: EMS error ");
229                 //itoa(err,str2,16);
230                 MM_EMSerr(str, err);
231                 printf("%s\n",str);
232                 return err;
233         }
234         mm->totalEMSpages=totalEMSpages;
235         mm->freeEMSpages=freeEMSpages;
236         mm->EMSpageframe=EMSpageframe;
237         mm->EMSpagesmapped=EMSpagesmapped;
238         mm->EMShandle=EMShandle;
239         mm->EMSVer=EMSVer;
240         return 0;
241 }
242
243
244 /*
245 ======================
246 =
247 = MML_ShutdownEMS
248 =
249 =======================
250 */
251
252 void MML_ShutdownEMS(mminfo_t *mm)
253 {
254         boolean errorflag=false;
255         unsigned EMShandle=mm->EMShandle;
256
257         if(!EMShandle)
258                 return;
259         __asm {
260                 mov     ah,EMS_FREEPAGES
261                 mov     dx,[EMShandle]
262                 int     EMS_INT
263                 or      ah,ah
264                 jz      ok
265                 mov     errorflag,1
266         }
267                 ok:
268         if(errorflag==true) printf("MML_ShutdownEMS: Error freeing EMS!\n");    //++++ add something
269 }
270
271 /*
272 ====================
273 =
274 = MM_MapEMS
275 =
276 = Maps the 64k of EMS used by memory manager into the page frame
277 = for general use.  This only needs to be called if you are keeping
278 = other things in EMS.
279 =
280 ====================
281 */
282
283 byte MM_MapEMS(mminfo_t *mm, mminfotype *mmi)
284 {
285         byte    str[160];
286         unsigned        EMShandle;
287         byte err;
288         boolean errorflag=false;
289         int     i;
290         EMShandle=mm->EMShandle;
291
292         for (i=0;i<4/*MAPPAGES*/;i++)
293         {
294                 __asm {
295                         mov     ah,EMS_MAPPAGE
296                         mov     bx,[i]                  // logical page
297                         mov     al,bl                   // physical page
298                         mov     dx,[EMShandle]  // handle
299                         int     EMS_INT
300                         or      ah,ah
301                         jnz     error
302                         jmp End
303                 }
304                         error:
305                 __asm {
306                         mov     err,ah
307                         mov     errorflag,1
308                 }
309                         End:
310                 if(errorflag==true)
311                 {
312                         //err = CPURegs.h.ah;
313                         strcpy(str,"MM_MapEMS: EMS error ");
314                         //itoa(err,str2,16);
315                         MM_EMSerr(str, err);
316                         printf("%s\n",str);
317                         //printf("FACK! %x\n", err);
318                         return err;
319                 }
320         }
321         mmi->EMSmem = (i)*0x4000lu;
322         return 0;
323 }
324
325 byte MM_MapXEMS(mminfo_t *mm, mminfotype *mmi)
326 {
327 //SUB EMS.MapXPages (PhysicalStart, LogicalStart, NumPages, Handle)
328
329         //Maps up to 4 logical EMS pages to physical pages in the page frame, where:
330         //PhysicalStart = Physical page first logical page is mapped to
331         //LogicalStart  = First logical page to map
332         //NumPages      = Number of pages to map (1 to 4)
333         //Handle        = EMS handle logical pages are allocated to
334
335   /*//Create a buffer containing the page information
336 //  FOR x = 0 TO NumPages - 1
337 //    MapInfo$ = MapInfo$ + MKI$(LogicalStart + x) + MKI$(PhysicalStart + x)
338 //  NEXT*/
339
340 //  Regs.ax = 0x5000                           //Map the pages in the buffer
341 //  Regs.cx = NumPages                         //to the pageframe
342 //  Regs.dx = Handle
343 //  Regs.ds = VARSEG(MapInfo$)
344 //  Regs.si = SADD(MapInfo$)
345 //  InterruptX 0x67, Regs, Regs
346 //      EMS.Error = (Regs.ax AND 0xFF00&) \ 0x100  //Store the status code
347
348 //END SUB
349         byte    str[160];
350         byte err;
351         word    EMShandle;
352         boolean errorflag=false;
353         int     i;
354         EMShandle=mm->EMShandle;
355
356         if(mm->EMSVer<0x40)
357                 return 5;
358
359         for (i=0;i<MAPPAGES;i++)
360         {
361                 __asm {
362                         mov     ah,EMS_MAPXPAGE
363                         mov     cx,[i]                  // logical page
364                         mov     al,bl                   // physical page
365                         mov     dx,[EMShandle]  // handle
366                         int     EMS_INT
367                         or      ah,ah
368                         jnz     error
369                         jmp End
370                 }
371                         error:
372                 __asm {
373                         mov     err,ah
374                         mov     errorflag,1
375                 }
376                         End:
377                 if(errorflag==true)
378                 {
379                         //err = CPURegs.h.ah;
380                         //strcpy(str,"MM_MapXEMS: EMS error 0x");
381                         strcpy(str,"MM_MapXEMS: EMS error ");
382                         //itoa(err,str2,16);
383                         MM_EMSerr(str, err);
384                         printf("%s\n",str);
385                         //printf("%s%x\n",str, err);
386                         //printf("FACK! %x\n", err);
387                         return err;
388                 }
389         }
390         mmi->EMSmem = (i)*0x4000lu;
391         return 0;
392 }
393
394 //==========================================================================
395
396 /*
397 ======================
398 =
399 = MML_CheckForXMS
400 =
401 = Check for XMM driver
402 =
403 =======================
404 */
405
406 boolean MML_CheckForXMS(mminfo_t *mm)
407 {
408         boolean errorflag=false;
409         mm->numUMBs = 0;
410
411         __asm {
412                 mov     ax,0x4300
413                 int     0x2f                            // query status of installed diver
414                 cmp     al,0x80
415                 je      good
416                 mov     errorflag,1
417         }
418                 good:
419         if(errorflag==true) return false;
420         else return true;
421 }
422
423
424 /*
425 ======================
426 =
427 = MML_SetupXMS
428 =
429 = Try to allocate all upper memory block
430 =
431 =======================
432 */
433
434 void MML_SetupXMS(mminfo_t *mm, mminfotype *mmi)
435 {
436         unsigned        base,size;
437
438 getmemory:
439         __asm {
440                 mov     ax,0x4310
441                 int     0x2f
442                 mov     [WORD PTR XMSaddr],bx
443                 mov     [WORD PTR XMSaddr+2],es         // function pointer to XMS driver
444
445                 mov     ah,XMS_ALLOCUMB
446                 mov     dx,0xffff                                       // try for largest block possible
447                 //mov     ax,dx                                         // Set available Kbytes.
448                 call    [DWORD PTR XMSaddr]
449                 or      ax,ax
450                 jnz     gotone
451
452                 cmp     bl,0xb0                                         // error: smaller UMB is available
453                 jne     done;
454
455                 mov     ah,XMS_ALLOCUMB
456                 call    [DWORD PTR XMSaddr]             // DX holds largest available UMB
457                 or      ax,ax
458                 jz      done                                            // another error...
459         }
460 gotone:
461         __asm {
462                 mov     [base],bx
463                 mov     [size],dx
464         }
465 done:
466         printf("base=%u ", base); printf("size=%u\n", size);
467         MML_UseSpace(base,size, mm);
468         mmi->XMSmem += size*16;
469         mm->UMBbase[mm->numUMBs] = base;
470         mm->numUMBs++;
471         if(mm->numUMBs < MAXUMBS)
472                 goto getmemory;
473 }
474
475
476 /*
477 ======================
478 =
479 = MML_ShutdownXMS
480 =
481 ======================
482 */
483
484 void MML_ShutdownXMS(mminfo_t *mm)
485 {
486         int     i;
487         unsigned        base;
488
489         for (i=0;i<mm->numUMBs;i++)
490         {
491                 base = mm->UMBbase[i];
492                 __asm {
493                         mov     ah,XMS_FREEUMB
494                         mov     dx,[base]
495                         call    [DWORD PTR XMSaddr]
496                 }
497         }
498 }
499
500 //==========================================================================
501
502 /*
503 ======================
504 =
505 = MML_UseSpace
506 =
507 = Marks a range of paragraphs as usable by the memory manager
508 = This is used to mark space for the near heap, far heap, ems page frame,
509 = and upper memory blocks
510 =
511 ======================
512 */
513
514 void MML_UseSpace(/*d*/word segstart, dword seglength, mminfo_t *mm)
515 {
516         mmblocktype huge *scan,huge *last;
517         word            segm;
518         dword   oldend;
519         dword           extra;
520
521         scan = last = mm->mmhead;
522         mm->mmrover = mm->mmhead;               // reset rover to start of memory
523
524 //
525 // search for the block that contains the range of segments
526 //
527         while(scan->start+scan->length < segstart)
528         {
529                 last = scan;
530                 scan = scan->next;
531         }
532
533         //find out how many blocks it spans!
534         if(seglength>0xffffu)
535         {
536 //              segm=seglength/0x4000u;
537                 segm=seglength/0xffffu;
538         }
539         else segm=1;
540
541         //++++emsver stuff!
542         if(segm>1/*extra>0xfffflu*/)
543         {
544                 /*__asm
545                 {
546                         push    ds
547                         mov     ax,ds
548                         inc             ax
549                         mov     ds,ax
550                 }*/
551
552
553 //MML_UseSpace(?segstart?, ?length?, mm);
554
555                 /*__asm
556                 {
557                         pop ds
558                 }*/
559                 //printf("MML_UseSpace: Segment spans two blocks!\n");
560         }
561
562 //
563 // take the given range out of the block
564 //
565         oldend = scan->start + scan->length;
566         extra = oldend - (segstart+seglength);
567 /*
568 printf("segm=%u ", segm);
569 printf("ex=%lu  ", extra);
570 printf("start+seglen=%lu        ", segstart+seglength);
571 printf("len=%u  ", scan->length);
572 printf("segsta=%x       ", segstart);
573 printf("seglen=%lu\n", seglength);
574 */
575 //segu:
576 //++++todo: linked list of segment!
577 //printf("segm=%lu\n", segm);
578         if(segstart == scan->start)
579         {
580                 last->next = scan->next;                        // unlink block
581                 MM_FreeBlock(scan, mm);
582                 scan = last;
583         }
584         else
585                 scan->length = segstart-scan->start;    // shorten block
586
587 //      segm--;
588
589         if(extra > 0)
590         {
591                 MM_GetNewBlock(mm);
592                 mm->mmnew->next = scan->next;
593                 scan->next = mm->mmnew;
594                 mm->mmnew->start = segstart+seglength;
595                 mm->mmnew->length = extra;
596                 mm->mmnew->attributes = LOCKBIT;
597         }//else if(segm>0) goto segu;
598
599 }
600
601 //==========================================================================
602
603 /*
604 ====================
605 =
606 = MML_ClearBlock
607 =
608 = We are out of blocks, so free a purgable block
609 =
610 ====================
611 */
612
613 void MML_ClearBlock(mminfo_t *mm)
614 {
615         mmblocktype huge *scan,huge *last;
616
617         scan = mm->mmhead->next;
618
619         while(scan)
620         {
621                 if(!(scan->attributes&LOCKBIT) && (scan->attributes&PURGEBITS))
622                 {
623                         MM_FreePtr(scan->useptr, mm);
624                         return;
625                 }
626                 scan = scan->next;
627         }
628
629         printf("MM_ClearBlock: No purgable blocks!\n");
630 }
631
632
633 //==========================================================================
634
635 /*
636 ===================
637 =
638 = MM_Startup
639 =
640 = Grabs all space from turbo with malloc/farmalloc
641 = Allocates bufferseg misc buffer
642 =
643 ===================
644 */
645
646 void MM_Startup(mminfo_t *mm, mminfotype *mmi)
647 {
648         int i;
649         dword length,seglength;
650         //dword length; word seglength;
651         void huge       *start;
652         word    segstart;//,endfree;
653
654         if(mm->mmstarted)
655                 MM_Shutdown(mm);
656
657         mm->mmstarted = true;
658         mm->bombonerror = true;
659
660 //
661 // set up the linked list (everything in the free list;
662 //
663         //printf("              linked list making!\n");
664         mm->mmhead = NULL;
665         mm->mmfree = &(mm->mmblocks[0]);
666         for(i=0;i<MAXBLOCKS-1;i++)
667         {
668                 mm->mmblocks[i].next = &(mm->mmblocks[i+1]);
669         }
670         mm->mmblocks[i].next = NULL;
671
672 //
673 // locked block of all memory until we punch out free space
674 //
675         //printf("              newblock making!\n");
676         MM_GetNewBlock(mm);
677         mm->mmhead = mm->mmnew;                         // this will allways be the first node
678         mm->mmnew->start = 0;
679         mm->mmnew->length = 0xffff;
680         mm->mmnew->attributes = LOCKBIT;
681         mm->mmnew->next = NULL;
682         mm->mmrover = mm->mmhead;
683
684 //
685 // get all available near conventional memory segments
686 //
687         length=coreleft();
688         printf("                nearheap making!\n");
689         //_heapgrow();
690         //length=_memmax();//(dword)GetFreeSize();
691         start = (void huge *)(mm->nearheap = malloc(length));
692         length -= 16-(FP_OFF(start)&15);
693         length -= SAVENEARHEAP;
694         seglength = length / 16;                        // now in paragraphs
695         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
696         MML_UseSpace(segstart,seglength, mm);
697         mmi->nearheap = length;
698         printf("start=%Fp       segstart=%x     seglen=%l       len=%l\n", start, segstart, seglength, length);
699         printf("                near heap ok!\n");
700
701 //
702 // get all available far conventional memory segments
703 //
704         length=farcoreleft();
705         //printf("              farheap making!\n");
706         //_fheapgrow();
707         //length=(dword)GetFarFreeSize();//0xffffUL*4UL;
708         //start = mm->farheap = halloc(length, 1);
709         start = mm->farheap = _fmalloc(length);
710         length -= 16-(FP_OFF(start)&15);
711         length -= SAVEFARHEAP;
712         seglength = length / 16;                        // now in paragraphs
713         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
714         MML_UseSpace(segstart,seglength, mm);
715         mmi->farheap = length;
716         printf("start=%Fp       segstart=%x     seglen=%l       len=%l\n", start, segstart, seglength, length);
717         printf("                far heap ok!\n");
718
719         mmi->mainmem = mmi->nearheap + mmi->farheap;
720
721         getch();
722
723 //
724 // detect EMS and allocate up to 64K at page frame
725 //
726 printf("                EMS1\n");
727 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!
728         mmi->EMSmem = 0;
729         for(i = 1;i < _argc;i++)
730         {
731                 if(US_CheckParm(_argv[i],ParmStringsexmm) == 0)
732                         goto emsskip;                           // param NOEMS
733         }
734 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!
735         if(MML_CheckForEMS())
736         {
737 printf("                EMS2\n");
738 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!
739                 MML_SetupEMS(mm);                                       // allocate space
740 printf("                EMS3\n");
741 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!
742                 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
743                 MML_UseSpace(mm->EMSpageframe,(MAPPAGES)*0x4000lu, mm);
744 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!
745 printf("                EMS4\n");
746                 //if(mm->EMSVer<0x40)
747                         MM_MapEMS(mm, mmi);                                     // map in used pages
748                 //else
749                         //MM_MapXEMS(mm, mmi);                                  // map in used pages
750         }
751
752 //
753 // detect XMS and get upper memory blocks
754 //
755 emsskip:
756         mmi->XMSmem = 0;
757         for(i = 1;i < _argc;i++)
758         {
759                 if(US_CheckParm(_argv[i],ParmStringsexmm) == 0)
760                         goto xmsskip;                           // param NOXMS
761         }
762 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!
763         if(MML_CheckForXMS(mm))
764         {
765 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!
766 printf("                XMS!\n");
767                 MML_SetupXMS(mm, mmi);                                  // allocate as many UMBs as possible
768         }
769
770 //
771 // allocate the misc buffer
772 //
773 xmsskip:
774         mm->mmrover = mm->mmhead;               // start looking for space after low block
775
776         MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
777 }
778
779 //==========================================================================
780
781 /*
782 ====================
783 =
784 = MM_Shutdown
785 =
786 = Frees all conventional, EMS, and XMS allocated
787 =
788 ====================
789 */
790
791 void MM_Shutdown(mminfo_t *mm)
792 {
793         if(!(mm->mmstarted))
794                 return;
795
796         _ffree(mm->farheap);    printf("                far freed\n");
797         free(mm->nearheap);     printf("                near freed\n");
798         if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("            EMS freed\n"); }
799         if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("          XMS freed\n"); }
800 }
801
802 //==========================================================================
803
804 /*
805 ====================
806 =
807 = MM_GetPtr
808 =
809 = Allocates an unlocked, unpurgable block
810 =
811 ====================
812 */
813
814 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
815 {
816         mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
817         int                     search;
818         unsigned        needed,startseg;
819
820         needed = (size+15)/16;          // convert size from bytes to paragraphs
821
822         MM_GetNewBlock(mm);                             // fill in start and next after a spot is found
823         mm->mmnew->length = needed;
824         mm->mmnew->useptr = baseptr;
825         mm->mmnew->attributes = BASEATTRIBUTES;
826
827         for(search = 0; search<3; search++)
828         {
829         //
830         // first search:        try to allocate right after the rover, then on up
831         // second search:       search from the head pointer up to the rover
832         // third search:        compress memory, then scan from start
833                 if(search == 1 && mm->mmrover == mm->mmhead)
834                         search++;
835
836                 switch(search)
837                 {
838                 case 0:
839                         lastscan = mm->mmrover;
840                         scan = mm->mmrover->next;
841                         endscan = NULL;
842                         break;
843                 case 1:
844                         lastscan = mm->mmhead;
845                         scan = mm->mmhead->next;
846                         endscan = mm->mmrover;
847                         break;
848                 case 2:
849                         MM_SortMem(mm);
850                         lastscan = mm->mmhead;
851                         scan = mm->mmhead->next;
852                         endscan = NULL;
853                         break;
854                 }
855
856                 startseg = lastscan->start + lastscan->length;
857
858                 while(scan != endscan)
859                 {
860                         if(scan->start - startseg >= needed)
861                         {
862                         //
863                         // got enough space between the end of lastscan and
864                         // the start of scan, so throw out anything in the middle
865                         // and allocate the new block
866                         //
867                                 purge = lastscan->next;
868                                 lastscan->next = mm->mmnew;
869                                 mm->mmnew->start = *(unsigned *)baseptr = startseg;
870                                 mm->mmnew->next = scan;
871                                 while(purge != scan)
872                                 {       // free the purgable block
873                                         next = purge->next;
874                                         MM_FreeBlock(purge, mm);
875                                         purge = next;           // purge another if not at scan
876                                 }
877                                 mm->mmrover = mm->mmnew;
878                                 return; // good allocation!
879                         }
880
881                         //
882                         // if this block is purge level zero or locked, skip past it
883                         //
884                         if((scan->attributes & LOCKBIT)
885                                 || !(scan->attributes & PURGEBITS) )
886                         {
887                                 lastscan = scan;
888                                 startseg = lastscan->start + lastscan->length;
889                         }
890
891
892                         scan=scan->next;                // look at next line
893                 }
894         }
895
896         if (mm->bombonerror)
897         {
898                 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
899                 exit(-5);
900         }
901         else
902                 mm->mmerror = true;
903 }
904
905 //==========================================================================
906
907 /*
908 ====================
909 =
910 = MM_FreePtr
911 =
912 = Allocates an unlocked, unpurgable block
913 =
914 ====================
915 */
916
917 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
918 {
919         mmblocktype huge *scan,huge *last;
920
921         last = mm->mmhead;
922         scan = last->next;
923
924         if(baseptr == mm->mmrover->useptr)      // removed the last allocated block
925                 mm->mmrover = mm->mmhead;
926
927         while(scan->useptr != baseptr && scan)
928         {
929                 last = scan;
930                 scan = scan->next;
931         }
932
933         if(!scan)
934         {
935                 printf("MM_FreePtr: Block not found!\n");
936                 return;
937         }
938
939         last->next = scan->next;
940
941         MM_FreeBlock(scan, mm);
942 }
943 //==========================================================================
944
945 /*
946 =====================
947 =
948 = MM_SetPurge
949 =
950 = Sets the purge level for a block (locked blocks cannot be made purgable)
951 =
952 =====================
953 */
954
955 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
956 {
957         mmblocktype huge *start;
958
959         start = mm->mmrover;
960
961         do
962         {
963                 if(mm->mmrover->useptr == baseptr)
964                         break;
965
966                 mm->mmrover = mm->mmrover->next;
967
968                 if(!mm->mmrover)
969                         mm->mmrover = mm->mmhead;
970                 else if(mm->mmrover == start)
971                 {
972                         printf("MM_SetPurge: Block not found!");
973                         return;
974                 }
975
976         } while(1);
977
978         mm->mmrover->attributes &= ~PURGEBITS;
979         mm->mmrover->attributes |= purge;
980 }
981
982 //==========================================================================
983
984 /*
985 =====================
986 =
987 = MM_SetLock
988 =
989 = Locks / unlocks the block
990 =
991 =====================
992 */
993
994 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
995 {
996         mmblocktype huge *start;
997
998         start = mm->mmrover;
999
1000         do
1001         {
1002                 if(mm->mmrover->useptr == baseptr)
1003                         break;
1004
1005                 mm->mmrover = mm->mmrover->next;
1006
1007                 if(!mm->mmrover)
1008                         mm->mmrover = mm->mmhead;
1009                 else if(mm->mmrover == start)
1010                 {
1011                         printf("MM_SetLock: Block not found!");
1012                         return;
1013                 }
1014
1015         } while(1);
1016
1017         mm->mmrover->attributes &= ~LOCKBIT;
1018         mm->mmrover->attributes |= locked*LOCKBIT;
1019 }
1020
1021 //==========================================================================
1022
1023 /*
1024 =====================
1025 =
1026 = MM_SortMem
1027 =
1028 = Throws out all purgable stuff and compresses movable blocks
1029 =
1030 =====================
1031 */
1032
1033 void MM_SortMem(mminfo_t *mm)
1034 {
1035         mmblocktype huge *scan,huge *last,huge *next;
1036         unsigned        start,length,source,dest,oldborder;
1037         int                     playing;
1038
1039         //
1040         // lock down a currently playing sound
1041         //
1042 /*++++  playing = SD_SoundPlaying ();
1043         if(playing)
1044         {
1045                 switch (SoundMode)
1046                 {
1047                 case sdm_PC:
1048                         playing += STARTPCSOUNDS;
1049                         break;
1050                 case sdm_AdLib:
1051                         playing += STARTADLIBSOUNDS;
1052                         break;
1053                 }
1054                 MM_SetLock(&(memptr)audiosegs[playing],true);
1055         }
1056
1057
1058         SD_StopSound();*/
1059 //      oldborder = bordercolor;
1060 //      VW_ColorBorder (15);
1061
1062         if(beforesort)
1063                 beforesort();
1064
1065         scan = mm->mmhead;
1066
1067         last = NULL;            // shut up compiler warning
1068
1069         while(scan)
1070         {
1071                 if(scan->attributes & LOCKBIT)
1072                 {
1073                 //
1074                 // block is locked, so try to pile later blocks right after it
1075                 //
1076                         start = scan->start + scan->length;
1077                 }
1078                 else
1079                 {
1080                         if(scan->attributes & PURGEBITS)
1081                         {
1082                         //
1083                         // throw out the purgable block
1084                         //
1085                                 next = scan->next;
1086                                 MM_FreeBlock(scan, mm);
1087                                 last->next = next;
1088                                 scan = next;
1089                                 continue;
1090                         }
1091                         else
1092                         {
1093                         //
1094                         // push the non purgable block on top of the last moved block
1095                         //
1096                                 if(scan->start != start)
1097                                 {
1098                                         length = scan->length;
1099                                         source = scan->start;
1100                                         dest = start;
1101                                         while(length > 0xf00)
1102                                         {
1103                                                 movedata(source,0,dest,0,0xf00*16);
1104                                                 length -= 0xf00;
1105                                                 source += 0xf00;
1106                                                 dest += 0xf00;
1107                                         }
1108                                         movedata(source,0,dest,0,length*16);
1109
1110                                         scan->start = start;
1111                                         *(unsigned *)scan->useptr = start;
1112                                 }
1113                                 start = scan->start + scan->length;
1114                         }
1115                 }
1116
1117                 last = scan;
1118                 scan = scan->next;              // go to next block
1119         }
1120
1121         mm->mmrover = mm->mmhead;
1122
1123         if(aftersort)
1124                 aftersort();
1125
1126 //      VW_ColorBorder (oldborder);
1127
1128 /*++++  if(playing)
1129                 MM_SetLock(&(memptr)audiosegs[playing],false);*/
1130 }
1131
1132
1133 //==========================================================================
1134
1135 //****#if 0
1136 /*
1137 =====================
1138 =
1139 = MM_ShowMemory
1140 =
1141 =====================
1142 */
1143
1144 void MM_ShowMemory(/*page_t *page, */mminfo_t *mm)
1145 {
1146         mmblocktype huge *scan;
1147         word color,temp;
1148         long    end,owner;
1149         word chx,chy;
1150         byte    scratch[160],str[16];
1151
1152 //****  VW_SetDefaultColors();
1153 //****  VW_SetLineWidth(40);
1154 //++++mh        temp = bufferofs;
1155 //++++mh        bufferofs = 0;
1156 //****  VW_SetScreen (0,0);
1157
1158         scan = mm->mmhead;
1159
1160         end = -1;
1161
1162 CA_OpenDebug ();
1163
1164         chx=0;
1165         chy=0;
1166
1167         while(scan)
1168         {
1169                 if(scan->attributes & PURGEBITS)
1170                         color = 5;              // dark purple = purgable
1171                 else
1172                         color = 9;              // medium blue = non purgable
1173                 if(scan->attributes & LOCKBIT)
1174                         color = 12;             // red = locked
1175                 if(scan->start<=end)
1176                 {
1177                         //printf(");
1178                         write(debughandle,"\nMM_ShowMemory: Memory block order currupted!\n",strlen("\nMM_ShowMemory: Memory block order currupted!\n"));
1179                         //modexprint(&page, chx, chy, 1, 0, 24, "\nMM_ShowMemory: Memory block order currupted!\n");
1180                         return;
1181                 }
1182                 end = scan->start+scan->length-1;
1183                 chy = scan->start/320;
1184                 chx = scan->start%320;
1185                                 //modexhlin(page, scan->start, (unsigned)end, chy, color);
1186                                 //for(chx=scan->start;chx+4>=(word)end;chx+=4)
1187                                 //{
1188 //++++                                  modexClearRegion(page, chx, chy, 4, 4, color);
1189                                 //}
1190
1191 //++++          VW_Hlin(scan->start,(unsigned)end,0,color);
1192
1193 //++++          VW_Plot(scan->start,0,15);
1194 //++++                          modexClearRegion(page, chx, chy, 4, 4, 15);
1195                 if(scan->next->start > end+1)
1196 //++++                  VW_Hlin(end+1,scan->next->start,0,0);   // black = free
1197                         //for(chx=scan->next->start;chx+4>=(word)end+1;chx+=4)
1198                         //{
1199 //++++                          chx+=scan->next->start;
1200 //++++                          modexClearRegion(page, chx, chy, 4, 4, 2);
1201                         //}
1202                                         //modexhlin(page, end+1,scan->next->start, chy, 0);
1203
1204 /*
1205                 end = scan->length-1;
1206                 y = scan->start/320;
1207                 x = scan->start%320;
1208                 VW_Hlin(x,x+end,y,color);
1209                 VW_Plot(x,y,15);
1210                 if (scan->next && scan->next->start > end+1)
1211                         VW_Hlin(x+end+1,x+(scan->next->start-scan->start),y,0); // black = free
1212 */
1213
1214 //****#if 0
1215 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!
1216 strcpy(scratch,"Seg:");
1217 ultoa (scan->start,str,16);
1218 strcat (scratch,str);
1219 strcat (scratch,"\tSize:");
1220 ultoa ((dword)scan->length,str,10);
1221 strcat (scratch,str);
1222 strcat (scratch,"\tOwner:0x");
1223 owner = (unsigned)scan->useptr;
1224 ultoa (owner,str,16);
1225 strcat (scratch,str);
1226 strcat (scratch,"\n");
1227 write(debughandle,scratch,strlen(scratch));
1228 //modexprint(page, chx, chy, 1, 0, 24, &scratch);
1229 //++++chy+=4;
1230 //fprintf(stdout, "%s", scratch);
1231 //****#endif
1232
1233                 scan = scan->next;
1234         }
1235
1236 CA_CloseDebug ();
1237
1238 //++++mh        IN_Ack();
1239 //****  VW_SetLineWidth(64);
1240 //++++mh        bufferofs = temp;
1241 }
1242 //****#endif
1243
1244 //==========================================================================
1245
1246 /*
1247 =====================
1248 =
1249 = MM_DumpData
1250 =
1251 =====================
1252 */
1253
1254 void MM_DumpData(mminfo_t *mm)
1255 {
1256         mmblocktype far *scan,far *best;
1257         long    lowest,oldlowest;
1258         word    owner;
1259         byte    lock,purge;
1260         FILE    *dumpfile;
1261
1262
1263         //++++free(mm->nearheap);
1264         dumpfile = fopen ("mmdump.16","w");
1265         if (!dumpfile){
1266                 printf("MM_DumpData: Couldn't open MMDUMP.16!\n");
1267                 return;
1268         }
1269
1270         lowest = -1;
1271         do
1272         {
1273                 oldlowest = lowest;
1274                 lowest = 0xffff;
1275
1276                 scan = mm->mmhead;
1277                 while (scan)
1278                 {
1279                         owner = (word)scan->useptr;
1280
1281                         if (owner && owner<lowest && owner > oldlowest)
1282                         {
1283                                 best = scan;
1284                                 lowest = owner;
1285                         }
1286
1287                         scan = scan->next;
1288                 }
1289
1290                 if (lowest != 0xffff)
1291                 {
1292                         if (best->attributes & PURGEBITS)
1293                                 purge = 'P';
1294                         else
1295                                 purge = '-';
1296                         if (best->attributes & LOCKBIT)
1297                                 lock = 'L';
1298                         else
1299                                 lock = '-';
1300                         fprintf (dumpfile,"0x%p (%c%c) = %u\n"
1301                         ,(word)lowest,lock,purge,best->length);
1302                 }
1303
1304         } while (lowest != 0xffff);
1305
1306         fclose(dumpfile);
1307         printf("MMDUMP.16 created.\n");
1308 }
1309
1310 //==========================================================================
1311
1312
1313 /*
1314 ======================
1315 =
1316 = MM_UnusedMemory
1317 =
1318 = Returns the total free space without purging
1319 =
1320 ======================
1321 */
1322
1323 dword MM_UnusedMemory(mminfo_t *mm)
1324 {
1325         dword free;
1326         mmblocktype huge *scan;
1327
1328         free = 0;
1329         scan = mm->mmhead;
1330
1331         while(scan->next)
1332         {
1333                 free += scan->next->start - (scan->start + scan->length);
1334                 scan = scan->next;
1335         }
1336
1337 //      return free*16l;
1338         return free;
1339 }
1340
1341 //==========================================================================
1342
1343
1344 /*
1345 ======================
1346 =
1347 = MM_TotalFree
1348 =
1349 = Returns the total free space with purging
1350 =
1351 ======================
1352 */
1353
1354 dword MM_TotalFree(mminfo_t *mm)
1355 {
1356         dword free;
1357         mmblocktype huge *scan;
1358
1359         free = 0;
1360         scan = mm->mmhead;
1361
1362         while(scan->next)
1363         {
1364                 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1365                         free += scan->length;
1366                 free += scan->next->start - (scan->start + scan->length);
1367                 scan = scan->next;
1368         }
1369
1370 //      return free*16l;
1371         return free;
1372 }
1373
1374 //==========================================================================
1375
1376 /*
1377 =====================
1378 =
1379 = MM_Report
1380 =
1381 =====================
1382 */
1383
1384 void MM_Report(/*page_t *page, */mminfo_t *mm, mminfotype *mmi)
1385 {
1386         if(MML_CheckForEMS())
1387         {
1388                 printf("EMM v%x.%x available\n", mm->EMSVer>>4,mm->EMSVer&0x0F);
1389                 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1390                 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1391                 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1392         }
1393         if(MML_CheckForXMS(mm)) printf("XMSaddr=%X\n", *XMSaddr);
1394         printf("near=%lu\n", mmi->nearheap);
1395         printf("far=%lu\n", mmi->farheap);
1396         printf("EMSmem=%lu\n", mmi->EMSmem);
1397         printf("XMSmem=%lu\n", mmi->XMSmem);
1398         printf("mainmem=%lu\n", mmi->mainmem);
1399         printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1400         printf("TotalFree=%lu\n", MM_TotalFree(mm));
1401         //mmi->nearheap+mmi->farheap+
1402         printf("TotalUsed=%lu\n", mmi->mainmem+mmi->EMSmem+mmi->XMSmem);//+);
1403 //      printf("\n");
1404 //      printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1405 //      printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1406 }
1407
1408 //==========================================================================
1409
1410 /*
1411 =====================
1412 =
1413 = MM_EMSerr
1414 =
1415 =====================
1416 */
1417
1418 void MM_EMSerr(byte *stri, byte err)
1419 {
1420         //Returns a text string describing the error code in EMS.Error.
1421         switch(err)
1422         {
1423                 case 0x0:
1424                         strcat(stri, "successful");
1425                 break;
1426                 case 0x80:
1427                         strcat(stri, "internal error");
1428                 break;
1429                 case 0x81:
1430                         strcat(stri, "hardware malfunction");
1431                 break;
1432                 case 0x82:
1433                         strcat(stri, "busy .. retry later");
1434                 break;
1435                 case 0x83:
1436                         strcat(stri, "invalid handle");
1437                 break;
1438                 case 0x84:
1439                         strcat(stri, "undefined function requested by application");
1440                 break;
1441                 case 0x85:
1442                         strcat(stri, "no more handles available");
1443                 break;
1444                 case 0x86:
1445                         strcat(stri, "error in save or restore of mapping context");
1446                 break;
1447                 case 0x87:
1448                         strcat(stri, "insufficient memory pages in system");
1449                 break;
1450                 case 0x88:
1451                         strcat(stri, "insufficient memory pages available");
1452                 break;
1453                 case 0x89:
1454                         strcat(stri, "zero pages requested");
1455                 break;
1456                 case 0x8A:
1457                         strcat(stri, "invalid logical page number encountered");
1458                 break;
1459                 case 0x8B:
1460                         strcat(stri, "invalid physical page number encountered");
1461                 break;
1462                 case 0x8C:
1463                         strcat(stri, "page-mapping hardware state save area is full");
1464                 break;
1465                 case 0x8D:
1466                         strcat(stri, "save of mapping context failed");
1467                 break;
1468                 case 0x8E:
1469                         strcat(stri, "restore of mapping context failed");
1470                 break;
1471                 case 0x8F:
1472                         strcat(stri, "undefined subfunction");
1473                 break;
1474                 case 0x90:
1475                         strcat(stri, "undefined attribute type");
1476                 break;
1477                 case 0x91:
1478                         strcat(stri, "feature not supported");
1479                 break;
1480                 case 0x92:
1481                         strcat(stri, "successful, but a portion of the source region has been overwritten");
1482                 break;
1483                 case 0x93:
1484                         strcat(stri, "length of source or destination region exceeds length of region allocated to either source or destination handle");
1485                 break;
1486                 case 0x94:
1487                         strcat(stri, "conventional and expanded memory regions overlap");
1488                 break;
1489                 case 0x95:
1490                         strcat(stri, "offset within logical page exceeds size of logical page");
1491                 break;
1492                 case 0x96:
1493                         strcat(stri, "region length exceeds 1 MB");
1494                 break;
1495                 case 0x97:
1496                         strcat(stri, "source and destination EMS regions have same handle and overlap");
1497                 break;
1498                 case 0x98:
1499                         strcat(stri, "memory source or destination type undefined");
1500                 break;
1501                 case 0x9A:
1502                         strcat(stri, "specified alternate map register or DMA register set not supported");
1503                 break;
1504                 case 0x9B:
1505                         strcat(stri, "all alternate map register or DMA register sets currently allocated");
1506                 break;
1507                 case 0x9C:
1508                         strcat(stri, "alternate map register or DMA register sets not supported");
1509                 break;
1510                 case 0x9D:
1511                         strcat(stri, "undefined or unallocated alternate map register or DMA register set");
1512                 break;
1513                 case 0x9E:
1514                         strcat(stri, "dedicated DMA channels not supported");
1515                 break;
1516                 case 0x9F:
1517                         strcat(stri, "specified dedicated DMA channel not supported");
1518                 break;
1519                 case 0xA0:
1520                         strcat(stri, "no such handle name");
1521                 break;
1522                 case 0xA1:
1523                         strcat(stri, "a handle found had no name, or duplicate handle name");
1524                 break;
1525                 case 0xA2:
1526                         strcat(stri, "attempted to wrap around 1M conventional address space");
1527                 break;
1528                 case 0xA3:
1529                         strcat(stri, "source array corrupted");
1530                 break;
1531                 case 0xA4:
1532                         strcat(stri, "operating system denied access");
1533                 break;
1534                 default:
1535                         strcat(stri, "undefined error");
1536         }
1537 }
1538
1539 //==========================================================================
1540
1541 /*
1542 =====================
1543 =
1544 = MM_BombOnError
1545 =
1546 =====================
1547 */
1548
1549 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1550 {
1551         mm->bombonerror = bomb;
1552 }
1553
1554 void MM_GetNewBlock(mminfo_t *mm)
1555 {
1556         if(!mm->mmfree)
1557                 MML_ClearBlock(mm);
1558         mm->mmnew=mm->mmfree;
1559         mm->mmfree=mm->mmfree->next;
1560         //if(!(mm->mmnew=mm->mmfree))
1561         //{
1562                 //printf("MM_GETNEWBLOCK: No free blocks!");
1563 //              return;
1564         //}
1565         //mm->mmfree=mm->mmfree->next;
1566 }
1567
1568 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1569 {
1570         x->useptr=NULL;
1571         x->next=mm->mmfree;
1572         mm->mmfree=x;
1573 }
1574
1575 /*void MM_seguin(void)
1576 {
1577         __asm
1578         {
1579                 push    ds
1580                 mov     ax,ds
1581                 inc             ax
1582                 mov     ds,ax
1583         }
1584 }
1585
1586 void MM_segude(void)
1587 {
1588         __asm
1589         {
1590                 pop ds
1591         }
1592 }*/
1593
1594 /*
1595 pull data from far and put it into ds var
1596 mov ax,es:si
1597 mov x,ax
1598 */
1599 /*
1600 ss stack segment
1601 sp top of stack
1602 bp bottem of stack
1603 */