/*
 * Memory allocation and freeing functions.
 * VM_AllocMem :
 *   Call the VM_Allocation() function to get a piece of file.
 *   Check if the file requires extension.
 *   Extend the file.
 *   Fill in a lock for the file, and return it.
 *
 * VM_FreeMem :
 *   VM_Free the file record.
 *   Dispose the lock.
 */

#include "vm.h"

struct VM_Lock *
VM_AllocMem(struct VM_Construct *VM_C, LONG Size) {
   struct VM_Lock *VM_L ;
   struct VM_FreeList *VM_N ;

   VM_L = (struct VM_Lock *) TMemAlloc( sizeof(struct VM_Lock), MEMF_PUBLIC) ;

   if (!VM_L)
      return NULL ;

   VM_N = VM_Allocate(&(VM_C->VM_FreeList),Size) ;

   if (!VM_N) {
      FreeTrackedItem(VM_L) ;
      return NULL ;
      }

   VM_L->VM_C = VM_C ;
   VM_L->VM_FL = VM_N ;
   VM_L->VM_Flags = 0 ;

   return VM_L ;
   }

ULONG
VM_FreeMem(struct VM_Lock *VM_L) {

   ULONG Err ;

   if (VM_L->VM_Flags & VM_INUSE) {
      Err = VM_UnLock(VM_L) ;
      if (Err)
         return -1 ;
      }

   if (VM_L->VM_Flags & VM_RESERVED) {
      Err = VM_FlushLock(VM_L) ;
      if (Err)
         return -1 ;
      }
    
   VM_Free(&(VM_L->VM_C->VM_FreeList),VM_L->VM_FL) ;
   FreeTrackedItem(VM_L) ;

   return 0;
   }
