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