vmem and hdr

The virtual memory system (vmm) is driven off the following two structures:

typedef struct vmem{
  unsigned signature;
  unsigned dirty;
  unsigned ele_size;
  unsigned ele_per_blk;
  long num_ele;
  unsigned cblock;
  char *buf;
} vmem;

typedef struct hdr {
  int active;
  int nrefs;
  unsigned nblocks;
  unsigned offset;
  union { struct hdr *h; //if hdr is in freelist (active=0)
        struct vmem *v;  //virt. mem. element (active = 1)
  } next;
} hdr;

It helps to think of the virtual memory file as a long array of unsigned chars. The hdr structure points to a region in the file. The region may be used or free for use. The used regions of the file are referenced by a vmem structure. The unused regions are kept in a circular linked list of headers. These structures are described in Kernighan and Ritchie. The elements of the hdr structure are:

active
An indicator that the header points to a vmem (1) or is in the freelist (0). It is used for error trapping and debugging.
nrefs
Indicator for the number of matrices using this hdr. See the chapter on the stack for how this variable is used.
nblocks
number of blocks pointed to by the hdr
offset
the offset in the virtual file of the first block pointed to.
next
The next header in the freelist, or the vmem being pointed to
The hdr is analogous to a pointer returned by malloc() of freed by free().

The vmem structure contains the information for an active hdr. The vmm file is organized in blocks of size BLK_SIZE. 3.2 The elements of the vmem are:

signature
an indicator that the matrix has not been corrupted by heap overwrites. It is 0x5a5a when active, and set to zero when it is freed. This leaves a zero on the heap in case the freed pointer is referenced.
dirty
An indicator that an element in the page buffer has been changed. If this flag is set, then write the buffer out to disk before reading in a new page.
ele_size
size in bytes of an element being stored
ele_per_block
number of elements per block
num_ele
number of elements pointed to
cblock
block currently in buffer
buf
a pointer to the page buffer.

The function vmalloc() creates a hdr and a vmem. The function vfree() frees the vmem and places the hdr in the freelist. Freed space in the file is coalesced with neighboring free blocks.