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