/* initr.c (emx+gcc) -- Copyright (c) 1996 by Eberhard Mattes */

#include <stdlib.h>
#include <stddef.h>
#include <umalloc.h>
#include <sys/builtin.h>        /* For <sys/fmutex.h> */
#include <sys/fmutex.h>         /* For <sys/rmutex.h> */
#include <sys/rmutex.h>
#include <sys/smutex.h>
#include <sys/uflags.h>
#include <emx/umalloc.h>
#include <emx/thread.h>

/* This is the default regular heap. */

Heap_t _um_regular_heap;


void _um_init_default_regular_heap (void)
{
  _UM_MT_DECL
  void *memory;
  Heap_t h;
  static _smutex lock;

  _smutex_request (&lock);

  /* Create the regular heap if it hasn't been created by another
     thread between the check of _UM_DEFAULT_REGULAR_HEAP by our
     caller and obtaining the semaphore. */

  if (_UM_DEFAULT_REGULAR_HEAP == NULL)
    {
      if (_um_regular_heap == NULL)
        {
          _uflags (_UF_SBRK_MODEL, _UF_SBRK_ARBITRARY);
          memory = _sbrk (_INITIAL_DEFAULT_HEAP_SIZE);
          if (memory == (void *)-1)
            abort ();
          h = _ucreate2 (memory, _INITIAL_DEFAULT_HEAP_SIZE,
                         !_BLOCK_CLEAN, _HEAP_REGULAR,
                         _um_default_alloc, _um_default_release,
                         _um_default_expand, _um_default_shrink);
          if (h == NULL)
            abort ();
          if (_uopen (h) != 0)
            abort ();
          _um_regular_heap = h;
        }

      _UM_DEFAULT_REGULAR_HEAP = _um_regular_heap;
    }

  _smutex_release (&lock);
}
