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