]> 4ch.mooo.com Git - 16.git/blob - src/lib/16_mm.c
3aecccb56acde39e7bc0c96b699f2444cd5aa07a
[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         _nheapgrow();
677         length=(dword)_coreleft();//(dword)_memmax();//(dword)GetFreeSize();
678         start = (void huge *)(mm->nearheap = _nmalloc(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         //heapdump();
687         //getch();
688
689 //
690 // get all available far conventional memory segments
691 //
692 //----  length=farcoreleft();
693         printf("                farheap making!\n");
694         _fheapgrow();
695         length=(dword)_farcoreleft();//(dword)GetFarFreeSize();//0xffffUL*4UL;
696         //start = mm->farheap = halloc(length, 1);
697         start = mm->farheap = _fmalloc(length);
698         length -= 16-(FP_OFF(start)&15);
699         length -= SAVEFARHEAP;
700         seglength = length / 16;                        // now in paragraphs
701         segstart = FP_SEG(start)+(FP_OFF(start)+15)/16;
702         MML_UseSpace(segstart,seglength, mm);
703         mmi->farheap = length;
704         printf("start=%FP       segstart=%X     seglen=%lu      len=%lu\n", start, segstart, seglength, length);
705         heapdump();
706
707         mmi->mainmem = mmi->nearheap + mmi->farheap;
708
709         getch();
710
711 //
712 // detect EMS and allocate up to 64K at page frame
713 //
714 printf("                EMS1\n");
715 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!
716         mmi->EMSmem = 0;
717         for(i = 1;i < __argc;i++)
718         {
719                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
720                         goto emsskip;                           // param NOEMS
721         }
722 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!
723         if(MML_CheckForEMS())
724         {
725 printf("                EMS2\n");
726 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!
727                 MML_SetupEMS(mm);                                       // allocate space
728 printf("                EMS3\n");
729 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!
730                 //TODO: EMS4! AND EMS 3.2 MASSIVE DATA HANDLMENT!
731                 MML_UseSpace(mm->EMSpageframe,(MAPPAGES)*0x4000lu, mm);
732 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!
733 printf("                EMS4\n");
734                 //if(mm->EMSVer<0x40)
735                         MM_MapEMS(mm, mmi);                                     // map in used pages
736                 //else
737                         //MM_MapXEMS(mm, mmi);                                  // map in used pages
738         }
739
740 //
741 // detect XMS and get upper memory blocks
742 //
743 emsskip:
744         mmi->XMSmem = 0;
745         for(i = 1;i < __argc;i++)
746         {
747                 if(US_CheckParm(__argv[i],ParmStringsexmm) == 0)
748                         goto xmsskip;                           // param NOXMS
749         }
750 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!
751         if(MML_CheckForXMS(mm))
752         {
753 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!
754 printf("                XMS!\n");
755                 //MML_SetupXMS(mm, mmi);                                        // allocate as many UMBs as possible
756         }
757
758 //
759 // allocate the misc buffer
760 //
761 xmsskip:
762         mm->mmrover = mm->mmhead;               // start looking for space after low block
763
764         MM_GetPtr(&(mm->bufferseg),BUFFERSIZE, mm, mmi);
765 }
766
767 //==========================================================================
768
769 /*
770 ====================
771 =
772 = MM_Shutdown
773 =
774 = Frees all conventional, EMS, and XMS allocated
775 =
776 ====================
777 */
778
779 void MM_Shutdown(mminfo_t *mm)
780 {
781         if(!(mm->mmstarted))
782                 return;
783
784         _ffree(mm->farheap);    printf("                far freed\n");
785         _nfree(mm->nearheap);   printf("                near freed\n");
786         if(MML_CheckForEMS()){ MML_ShutdownEMS(mm); printf("            EMS freed\n"); }
787         if(MML_CheckForXMS(mm)){ MML_ShutdownXMS(mm); printf("          XMS freed\n"); }
788 }
789
790 //==========================================================================
791
792 /*
793 ====================
794 =
795 = MM_GetPtr
796 =
797 = Allocates an unlocked, unpurgable block
798 =
799 ====================
800 */
801
802 void MM_GetPtr(memptr *baseptr,dword size, mminfo_t *mm, mminfotype *mmi)
803 {
804         mmblocktype huge *scan,huge *lastscan,huge *endscan,huge *purge,huge *next;
805         int                     search;
806         unsigned        needed,startseg;
807
808         needed = (size+15)/16;          // convert size from bytes to paragraphs
809
810         MM_GetNewBlock(mm);                             // fill in start and next after a spot is found
811         mm->mmnew->length = needed;
812         mm->mmnew->useptr = baseptr;
813         mm->mmnew->attributes = BASEATTRIBUTES;
814
815         for(search = 0; search<3; search++)
816         {
817         //
818         // first search:        try to allocate right after the rover, then on up
819         // second search:       search from the head pointer up to the rover
820         // third search:        compress memory, then scan from start
821                 if(search == 1 && mm->mmrover == mm->mmhead)
822                         search++;
823
824                 switch(search)
825                 {
826                 case 0:
827                         lastscan = mm->mmrover;
828                         scan = mm->mmrover->next;
829                         endscan = NULL;
830                         break;
831                 case 1:
832                         lastscan = mm->mmhead;
833                         scan = mm->mmhead->next;
834                         endscan = mm->mmrover;
835                         break;
836                 case 2:
837                         MM_SortMem(mm);
838                         lastscan = mm->mmhead;
839                         scan = mm->mmhead->next;
840                         endscan = NULL;
841                         break;
842                 }
843
844                 startseg = lastscan->start + lastscan->length;
845
846                 while(scan != endscan)
847                 {
848                         if(scan->start - startseg >= needed)
849                         {
850                         //
851                         // got enough space between the end of lastscan and
852                         // the start of scan, so throw out anything in the middle
853                         // and allocate the new block
854                         //
855                                 purge = lastscan->next;
856                                 lastscan->next = mm->mmnew;
857                                 mm->mmnew->start = *(unsigned *)baseptr = startseg;
858                                 mm->mmnew->next = scan;
859                                 while(purge != scan)
860                                 {       // free the purgable block
861                                         next = purge->next;
862                                         MM_FreeBlock(purge, mm);
863                                         purge = next;           // purge another if not at scan
864                                 }
865                                 mm->mmrover = mm->mmnew;
866                                 return; // good allocation!
867                         }
868
869                         //
870                         // if this block is purge level zero or locked, skip past it
871                         //
872                         if((scan->attributes & LOCKBIT)
873                                 || !(scan->attributes & PURGEBITS) )
874                         {
875                                 lastscan = scan;
876                                 startseg = lastscan->start + lastscan->length;
877                         }
878
879
880                         scan=scan->next;                // look at next line
881                 }
882         }
883
884         if (mm->bombonerror)
885         {
886                 printf(OUT_OF_MEM_MSG,(size-mmi->nearheap));
887                 exit(-1);
888         }
889         else
890                 mm->mmerror = true;
891 }
892
893 //==========================================================================
894
895 /*
896 ====================
897 =
898 = MM_FreePtr
899 =
900 = Allocates an unlocked, unpurgable block
901 =
902 ====================
903 */
904
905 void MM_FreePtr(memptr *baseptr, mminfo_t *mm)
906 {
907         mmblocktype huge *scan,huge *last;
908
909         last = mm->mmhead;
910         scan = last->next;
911
912         if(baseptr == mm->mmrover->useptr)      // removed the last allocated block
913                 mm->mmrover = mm->mmhead;
914
915         while(scan->useptr != baseptr && scan)
916         {
917                 last = scan;
918                 scan = scan->next;
919         }
920
921         if(!scan)
922         {
923                 printf("MM_FreePtr: Block not found!\n");
924                 return;
925         }
926
927         last->next = scan->next;
928
929         MM_FreeBlock(scan, mm);
930 }
931 //==========================================================================
932
933 /*
934 =====================
935 =
936 = MM_SetPurge
937 =
938 = Sets the purge level for a block (locked blocks cannot be made purgable)
939 =
940 =====================
941 */
942
943 void MM_SetPurge(memptr *baseptr, int purge, mminfo_t *mm)
944 {
945         mmblocktype huge *start;
946
947         start = mm->mmrover;
948
949         do
950         {
951                 if(mm->mmrover->useptr == baseptr)
952                         break;
953
954                 mm->mmrover = mm->mmrover->next;
955
956                 if(!mm->mmrover)
957                         mm->mmrover = mm->mmhead;
958                 else if(mm->mmrover == start)
959                 {
960                         printf("MM_SetPurge: Block not found!");
961                         return;
962                 }
963
964         } while(1);
965
966         mm->mmrover->attributes &= ~PURGEBITS;
967         mm->mmrover->attributes |= purge;
968 }
969
970 //==========================================================================
971
972 /*
973 =====================
974 =
975 = MM_SetLock
976 =
977 = Locks / unlocks the block
978 =
979 =====================
980 */
981
982 void MM_SetLock(memptr *baseptr, boolean locked, mminfo_t *mm)
983 {
984         mmblocktype huge *start;
985
986         start = mm->mmrover;
987
988         do
989         {
990                 if(mm->mmrover->useptr == baseptr)
991                         break;
992
993                 mm->mmrover = mm->mmrover->next;
994
995                 if(!mm->mmrover)
996                         mm->mmrover = mm->mmhead;
997                 else if(mm->mmrover == start)
998                 {
999                         printf("MM_SetLock: Block not found!");
1000                         return;
1001                 }
1002
1003         } while(1);
1004
1005         mm->mmrover->attributes &= ~LOCKBIT;
1006         mm->mmrover->attributes |= locked*LOCKBIT;
1007 }
1008
1009 //==========================================================================
1010
1011 /*
1012 =====================
1013 =
1014 = MM_SortMem
1015 =
1016 = Throws out all purgable stuff and compresses movable blocks
1017 =
1018 =====================
1019 */
1020
1021 void MM_SortMem(mminfo_t *mm)
1022 {
1023         mmblocktype huge *scan,huge *last,huge *next;
1024         unsigned        start,length,source,dest,oldborder;
1025         int                     playing;
1026
1027         //
1028         // lock down a currently playing sound
1029         //
1030 /*++++  playing = SD_SoundPlaying ();
1031         if(playing)
1032         {
1033                 switch (SoundMode)
1034                 {
1035                 case sdm_PC:
1036                         playing += STARTPCSOUNDS;
1037                         break;
1038                 case sdm_AdLib:
1039                         playing += STARTADLIBSOUNDS;
1040                         break;
1041                 }
1042                 MM_SetLock(&(memptr)audiosegs[playing],true);
1043         }
1044
1045
1046         SD_StopSound();*/
1047 //      oldborder = bordercolor;
1048 //      VW_ColorBorder (15);
1049
1050         if(beforesort)
1051                 beforesort();
1052
1053         scan = mm->mmhead;
1054
1055         last = NULL;            // shut up compiler warning
1056
1057         while(scan)
1058         {
1059                 if(scan->attributes & LOCKBIT)
1060                 {
1061                 //
1062                 // block is locked, so try to pile later blocks right after it
1063                 //
1064                         start = scan->start + scan->length;
1065                 }
1066                 else
1067                 {
1068                         if(scan->attributes & PURGEBITS)
1069                         {
1070                         //
1071                         // throw out the purgable block
1072                         //
1073                                 next = scan->next;
1074                                 MM_FreeBlock(scan, mm);
1075                                 last->next = next;
1076                                 scan = next;
1077                                 continue;
1078                         }
1079                         else
1080                         {
1081                         //
1082                         // push the non purgable block on top of the last moved block
1083                         //
1084                                 if(scan->start != start)
1085                                 {
1086                                         length = scan->length;
1087                                         source = scan->start;
1088                                         dest = start;
1089                                         while(length > 0xf00)
1090                                         {
1091                                                 movedata(source,0,dest,0,0xf00*16);
1092                                                 length -= 0xf00;
1093                                                 source += 0xf00;
1094                                                 dest += 0xf00;
1095                                         }
1096                                         movedata(source,0,dest,0,length*16);
1097
1098                                         scan->start = start;
1099                                         *(unsigned *)scan->useptr = start;
1100                                 }
1101                                 start = scan->start + scan->length;
1102                         }
1103                 }
1104
1105                 last = scan;
1106                 scan = scan->next;              // go to next block
1107         }
1108
1109         mm->mmrover = mm->mmhead;
1110
1111         if(aftersort)
1112                 aftersort();
1113
1114 //      VW_ColorBorder (oldborder);
1115
1116 /*++++  if(playing)
1117                 MM_SetLock(&(memptr)audiosegs[playing],false);*/
1118 }
1119
1120
1121 //==========================================================================
1122
1123 //****#if 0
1124 /*
1125 =====================
1126 =
1127 = MM_ShowMemory
1128 =
1129 =====================
1130 */
1131
1132 void MM_ShowMemory(/*page_t *page, */mminfo_t *mm)
1133 {
1134         mmblocktype huge *scan;
1135         word color,temp;
1136         long    end,owner;
1137         word chx,chy;
1138         byte    scratch[160],str[16];
1139
1140 //****  VW_SetDefaultColors();
1141 //****  VW_SetLineWidth(40);
1142 //++++mh        temp = bufferofs;
1143 //++++mh        bufferofs = 0;
1144 //****  VW_SetScreen (0,0);
1145
1146         scan = mm->mmhead;
1147
1148         end = -1;
1149
1150 CA_OpenDebug ();
1151
1152         chx=0;
1153         chy=0;
1154
1155         while(scan)
1156         {
1157                 if(scan->attributes & PURGEBITS)
1158                         color = 5;              // dark purple = purgable
1159                 else
1160                         color = 9;              // medium blue = non purgable
1161                 if(scan->attributes & LOCKBIT)
1162                         color = 12;             // red = locked
1163                 if(scan->start<=end)
1164                 {
1165                         //printf(");
1166                         write(debughandle,"\nMM_ShowMemory: Memory block order currupted!\n",strlen("\nMM_ShowMemory: Memory block order currupted!\n"));
1167                         //modexprint(&page, chx, chy, 1, 0, 24, "\nMM_ShowMemory: Memory block order currupted!\n");
1168                         return;
1169                 }
1170                 end = scan->start+scan->length-1;
1171                 chy = scan->start/320;
1172                 chx = scan->start%320;
1173                                 //modexhlin(page, scan->start, (unsigned)end, chy, color);
1174                                 //for(chx=scan->start;chx+4>=(word)end;chx+=4)
1175                                 //{
1176 //++++                                  modexClearRegion(page, chx, chy, 4, 4, color);
1177                                 //}
1178
1179 //++++          VW_Hlin(scan->start,(unsigned)end,0,color);
1180
1181 //++++          VW_Plot(scan->start,0,15);
1182 //++++                          modexClearRegion(page, chx, chy, 4, 4, 15);
1183                 if(scan->next->start > end+1)
1184 //++++                  VW_Hlin(end+1,scan->next->start,0,0);   // black = free
1185                         //for(chx=scan->next->start;chx+4>=(word)end+1;chx+=4)
1186                         //{
1187 //++++                          chx+=scan->next->start;
1188 //++++                          modexClearRegion(page, chx, chy, 4, 4, 2);
1189                         //}
1190                                         //modexhlin(page, end+1,scan->next->start, chy, 0);
1191
1192 /*
1193                 end = scan->length-1;
1194                 y = scan->start/320;
1195                 x = scan->start%320;
1196                 VW_Hlin(x,x+end,y,color);
1197                 VW_Plot(x,y,15);
1198                 if (scan->next && scan->next->start > end+1)
1199                         VW_Hlin(x+end+1,x+(scan->next->start-scan->start),y,0); // black = free
1200 */
1201
1202 //****#if 0
1203 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!
1204 strcpy(scratch,"Seg:");
1205 ultoa (scan->start,str,16);
1206 strcat (scratch,str);
1207 strcat (scratch,"\tSize:");
1208 ultoa ((dword)scan->length,str,10);
1209 strcat (scratch,str);
1210 strcat (scratch,"\tOwner:0x");
1211 owner = (unsigned)scan->useptr;
1212 ultoa (owner,str,16);
1213 strcat (scratch,str);
1214 strcat (scratch,"\n");
1215 write(debughandle,scratch,strlen(scratch));
1216 //modexprint(page, chx, chy, 1, 0, 24, &scratch);
1217 //++++chy+=4;
1218 //fprintf(stdout, "%s", scratch);
1219 //****#endif
1220
1221                 scan = scan->next;
1222         }
1223
1224 CA_CloseDebug ();
1225
1226 //++++mh        IN_Ack();
1227 //****  VW_SetLineWidth(64);
1228 //++++mh        bufferofs = temp;
1229 }
1230 //****#endif
1231
1232 //==========================================================================
1233
1234 /*
1235 =====================
1236 =
1237 = MM_DumpData
1238 =
1239 =====================
1240 */
1241
1242 void MM_DumpData(mminfo_t *mm)
1243 {
1244         mmblocktype far *scan,far *best;
1245         long    lowest,oldlowest;
1246         word    owner;
1247         byte    lock,purge;
1248         FILE    *dumpfile;
1249
1250
1251         //++++free(mm->nearheap);
1252         dumpfile = fopen ("mmdump.16","w");
1253         if (!dumpfile){
1254                 printf("MM_DumpData: Couldn't open MMDUMP.16!\n");
1255                 return;
1256         }
1257
1258         lowest = -1;
1259         do
1260         {
1261                 oldlowest = lowest;
1262                 lowest = 0xffff;
1263
1264                 scan = mm->mmhead;
1265                 while (scan)
1266                 {
1267                         owner = (word)scan->useptr;
1268
1269                         if (owner && owner<lowest && owner > oldlowest)
1270                         {
1271                                 best = scan;
1272                                 lowest = owner;
1273                         }
1274
1275                         scan = scan->next;
1276                 }
1277
1278                 if (lowest != 0xffff)
1279                 {
1280                         if (best->attributes & PURGEBITS)
1281                                 purge = 'P';
1282                         else
1283                                 purge = '-';
1284                         if (best->attributes & LOCKBIT)
1285                                 lock = 'L';
1286                         else
1287                                 lock = '-';
1288                         fprintf (dumpfile,"0x%p (%c%c) = %u\n"
1289                         ,(word)lowest,lock,purge,best->length);
1290                 }
1291
1292         } while (lowest != 0xffff);
1293
1294         fclose(dumpfile);
1295         printf("MMDUMP.16 created.\n");
1296 }
1297
1298 //==========================================================================
1299
1300
1301 /*
1302 ======================
1303 =
1304 = MM_UnusedMemory
1305 =
1306 = Returns the total free space without purging
1307 =
1308 ======================
1309 */
1310
1311 dword MM_UnusedMemory(mminfo_t *mm)
1312 {
1313         dword free;
1314         mmblocktype huge *scan;
1315
1316         free = 0;
1317         scan = mm->mmhead;
1318
1319         while(scan->next)
1320         {
1321                 free += scan->next->start - (scan->start + scan->length);
1322                 scan = scan->next;
1323         }
1324
1325 //      return free*16l;
1326         return free;
1327 }
1328
1329 //==========================================================================
1330
1331
1332 /*
1333 ======================
1334 =
1335 = MM_TotalFree
1336 =
1337 = Returns the total free space with purging
1338 =
1339 ======================
1340 */
1341
1342 dword MM_TotalFree(mminfo_t *mm)
1343 {
1344         dword free;
1345         mmblocktype huge *scan;
1346
1347         free = 0;
1348         scan = mm->mmhead;
1349
1350         while(scan->next)
1351         {
1352                 if((scan->attributes&PURGEBITS) && !(scan->attributes&LOCKBIT))
1353                         free += scan->length;
1354                 free += scan->next->start - (scan->start + scan->length);
1355                 scan = scan->next;
1356         }
1357
1358 //      return free*16l;
1359         return free;
1360 }
1361
1362 //==========================================================================
1363
1364 /*
1365 =====================
1366 =
1367 = MM_Report
1368 =
1369 =====================
1370 */
1371
1372 void MM_Report(/*page_t *page, */mminfo_t *mm, mminfotype *mmi)
1373 {
1374         if(MML_CheckForEMS())
1375         {
1376                 printf("EMM v%x.%x available\n", mm->EMSVer>>4,mm->EMSVer&0x0F);
1377                 printf("totalEMSpages=%u\n", mm->totalEMSpages);
1378                 printf("freeEMSpages=%u\n", mm->freeEMSpages);
1379                 printf("EMSpageframe=%x\n", mm->EMSpageframe);
1380         }
1381         if(MML_CheckForXMS(mm)) printf("XMSaddr=%X\n", *XMSaddr);
1382         printf("near=%lu\n", mmi->nearheap);
1383         printf("far=%lu\n", mmi->farheap);
1384         printf("EMSmem=%lu\n", mmi->EMSmem);
1385         printf("XMSmem=%lu\n", mmi->XMSmem);
1386         printf("mainmem=%lu\n", mmi->mainmem);
1387         printf("UnusedMemory=%lu\n", MM_UnusedMemory(mm));
1388         printf("TotalFree=%lu\n", MM_TotalFree(mm));
1389         //mmi->nearheap+mmi->farheap+
1390         printf("TotalUsed=%lu\n", mmi->mainmem+mmi->EMSmem+mmi->XMSmem);//+);
1391 //      printf("\n");
1392 //      printf("UnusedMemory=%lu kb\n", MM_UnusedMemory()/10248);
1393 //      printf("TotalFree=%lu kb\n", MM_TotalFree()/10248);
1394 }
1395
1396 //==========================================================================
1397
1398 /*
1399 =====================
1400 =
1401 = MM_EMSerr
1402 =
1403 =====================
1404 */
1405
1406 void MM_EMSerr(byte *stri, byte err)
1407 {
1408         //Returns a text string describing the error code in EMS.Error.
1409         switch(err)
1410         {
1411                 case 0x0:
1412                         strcat(stri, "successful");
1413                 break;
1414                 case 0x80:
1415                         strcat(stri, "internal error");
1416                 break;
1417                 case 0x81:
1418                         strcat(stri, "hardware malfunction");
1419                 break;
1420                 case 0x82:
1421                         strcat(stri, "busy .. retry later");
1422                 break;
1423                 case 0x83:
1424                         strcat(stri, "invalid handle");
1425                 break;
1426                 case 0x84:
1427                         strcat(stri, "undefined function requested by application");
1428                 break;
1429                 case 0x85:
1430                         strcat(stri, "no more handles available");
1431                 break;
1432                 case 0x86:
1433                         strcat(stri, "error in save or restore of mapping context");
1434                 break;
1435                 case 0x87:
1436                         strcat(stri, "insufficient memory pages in system");
1437                 break;
1438                 case 0x88:
1439                         strcat(stri, "insufficient memory pages available");
1440                 break;
1441                 case 0x89:
1442                         strcat(stri, "zero pages requested");
1443                 break;
1444                 case 0x8A:
1445                         strcat(stri, "invalid logical page number encountered");
1446                 break;
1447                 case 0x8B:
1448                         strcat(stri, "invalid physical page number encountered");
1449                 break;
1450                 case 0x8C:
1451                         strcat(stri, "page-mapping hardware state save area is full");
1452                 break;
1453                 case 0x8D:
1454                         strcat(stri, "save of mapping context failed");
1455                 break;
1456                 case 0x8E:
1457                         strcat(stri, "restore of mapping context failed");
1458                 break;
1459                 case 0x8F:
1460                         strcat(stri, "undefined subfunction");
1461                 break;
1462                 case 0x90:
1463                         strcat(stri, "undefined attribute type");
1464                 break;
1465                 case 0x91:
1466                         strcat(stri, "feature not supported");
1467                 break;
1468                 case 0x92:
1469                         strcat(stri, "successful, but a portion of the source region has been overwritten");
1470                 break;
1471                 case 0x93:
1472                         strcat(stri, "length of source or destination region exceeds length of region allocated to either source or destination handle");
1473                 break;
1474                 case 0x94:
1475                         strcat(stri, "conventional and expanded memory regions overlap");
1476                 break;
1477                 case 0x95:
1478                         strcat(stri, "offset within logical page exceeds size of logical page");
1479                 break;
1480                 case 0x96:
1481                         strcat(stri, "region length exceeds 1 MB");
1482                 break;
1483                 case 0x97:
1484                         strcat(stri, "source and destination EMS regions have same handle and overlap");
1485                 break;
1486                 case 0x98:
1487                         strcat(stri, "memory source or destination type undefined");
1488                 break;
1489                 case 0x9A:
1490                         strcat(stri, "specified alternate map register or DMA register set not supported");
1491                 break;
1492                 case 0x9B:
1493                         strcat(stri, "all alternate map register or DMA register sets currently allocated");
1494                 break;
1495                 case 0x9C:
1496                         strcat(stri, "alternate map register or DMA register sets not supported");
1497                 break;
1498                 case 0x9D:
1499                         strcat(stri, "undefined or unallocated alternate map register or DMA register set");
1500                 break;
1501                 case 0x9E:
1502                         strcat(stri, "dedicated DMA channels not supported");
1503                 break;
1504                 case 0x9F:
1505                         strcat(stri, "specified dedicated DMA channel not supported");
1506                 break;
1507                 case 0xA0:
1508                         strcat(stri, "no such handle name");
1509                 break;
1510                 case 0xA1:
1511                         strcat(stri, "a handle found had no name, or duplicate handle name");
1512                 break;
1513                 case 0xA2:
1514                         strcat(stri, "attempted to wrap around 1M conventional address space");
1515                 break;
1516                 case 0xA3:
1517                         strcat(stri, "source array corrupted");
1518                 break;
1519                 case 0xA4:
1520                         strcat(stri, "operating system denied access");
1521                 break;
1522                 default:
1523                         strcat(stri, "undefined error");
1524         }
1525 }
1526
1527 //==========================================================================
1528
1529 /*
1530 =====================
1531 =
1532 = MM_BombOnError
1533 =
1534 =====================
1535 */
1536
1537 void MM_BombOnError(boolean bomb, mminfo_t *mm)
1538 {
1539         mm->bombonerror = bomb;
1540 }
1541
1542 void MM_GetNewBlock(mminfo_t *mm)
1543 {
1544         if(!mm->mmfree)
1545                 MML_ClearBlock(mm);
1546         mm->mmnew=mm->mmfree;
1547         mm->mmfree=mm->mmfree->next;
1548         /*if(!(mm->mmnew=mm->mmfree))
1549         {
1550                 printf("MM_GETNEWBLOCK: No free blocks!");
1551                 return;
1552         }
1553         mm->mmfree=mm->mmfree->next;*/
1554 }
1555
1556 void MM_FreeBlock(mmblocktype *x, mminfo_t *mm)
1557 {
1558         x->useptr=NULL;
1559         x->next=mm->mmfree;
1560         mm->mmfree=x;
1561 }
1562
1563 void MM_seguin(void)
1564 {
1565         __asm {
1566                 push    ds
1567                 mov     ax,ds
1568                 inc             ax
1569                 mov     ds,ax
1570         }
1571 }
1572
1573 void MM_segude(void)
1574 {
1575         __asm {
1576                 pop ds
1577         }
1578 }
1579
1580 /*
1581 pull data from far and put it into ds var
1582 mov ax,es:si
1583 mov x,ax
1584 */
1585 /*
1586 ss stack segment
1587 sp top of stack
1588 bp bottem of stack
1589 */