+ if (ret == (void *)-1) {
+ if (errno == ENOMEM ||
+ (errno == EINVAL && sizeof(void*)==4 && size >= 0xc0000000)) {
+ // If we request more than 3Gig, then we get EINVAL
+ // instead of ENOMEM (at least on Linux).
+ errorBelch("out of memory (requested %lu bytes)", size);
+ stg_exit(EXIT_FAILURE);
+ } else {
+ barf("getMBlock: mmap: %s", strerror(errno));
+ }
+ }
+
+ return ret;
+}
+
+// Implements the general case: allocate a chunk of memory of 'size'
+// mblocks.
+
+static void *
+gen_map_mblocks (lnat size)
+{
+ int slop;
+ StgWord8 *ret;
+
+ // Try to map a larger block, and take the aligned portion from
+ // it (unmap the rest).
+ size += MBLOCK_SIZE;
+ ret = my_mmap(0, size);
+
+ // unmap the slop bits around the chunk we allocated
+ slop = (W_)ret & MBLOCK_MASK;
+
+ if (munmap(ret, MBLOCK_SIZE - slop) == -1) {
+ barf("gen_map_mblocks: munmap failed");
+ }
+ if (slop > 0 && munmap(ret+size-slop, slop) == -1) {
+ barf("gen_map_mblocks: munmap failed");
+ }
+
+ // ToDo: if we happened to get an aligned block, then don't
+ // unmap the excess, just use it. For this to work, you
+ // need to keep in mind the following:
+ // * Calling my_mmap() with an 'addr' arg pointing to
+ // already my_mmap()ed space is OK and won't fail.
+ // * If my_mmap() can't satisfy the request at the
+ // given 'next_request' address in getMBlocks(), that
+ // you unmap the extra mblock mmap()ed here (or simply
+ // satisfy yourself that the slop introduced isn't worth
+ // salvaging.)
+ //
+
+ // next time, try after the block we just got.
+ ret += MBLOCK_SIZE - slop;
+ return ret;
+}
+
+void *
+osGetMBlocks(nat n)
+{
+ caddr_t ret;
+ lnat size = MBLOCK_SIZE * (lnat)n;
+ map_rec* rec;
+
+ if (next_request == 0) {
+ // use gen_map_mblocks the first time.
+ ret = gen_map_mblocks(size);
+ } else {
+ ret = my_mmap(next_request, size);
+
+ if (((W_)ret & MBLOCK_MASK) != 0) {
+ // misaligned block!
+#if 0 // defined(DEBUG)
+ errorBelch("warning: getMBlock: misaligned block %p returned when allocating %d megablock(s) at %p", ret, n, next_request);
+#endif
+
+ // unmap this block...
+ if (munmap(ret, size) == -1) {
+ barf("getMBlock: munmap failed");
+ }
+ // and do it the hard way
+ ret = gen_map_mblocks(size);
+ }
+ }
+ rec = (map_rec*)stgMallocBytes(sizeof(map_rec),"OSMem: osGetMBlocks");
+ rec->size = size;
+ rec->base = ret;
+ rec->next = mmap_rec;
+ mmap_rec = rec;
+ // Next time, we'll try to allocate right after the block we just got.
+ // ToDo: check that we haven't already grabbed the memory at next_request
+ next_request = ret + size;
+
+ return ret;
+}
+
+void osFreeAllMBlocks(void)
+{
+ map_rec* tmp = mmap_rec;
+ map_rec* next = NULL;
+
+ for(; tmp!=NULL;) {
+ if(munmap(tmp->base,tmp->size))
+ barf("osFreeAllMBlocks: munmap failed!");
+
+ next = tmp->next;
+ stgFree(tmp);
+ tmp = next;
+ }
+}
+