aboutsummaryrefslogtreecommitdiffstats
path: root/src/zone.c
blob: 35d64efae7572d248241c7f48a476c6205b59bdc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * @file   zone.c
 * @brief  Zone allocation via mmap.
 */

#include "malloc_internal.h"
#include <sys/mman.h>
#include <unistd.h>

static size_t
_s_zone_size (size_t alloc_max)
{
  size_t chunk_size;
  size_t total;
  size_t page_size;

  chunk_size = ALIGN (sizeof (t_chunk)) + ALIGN (alloc_max);
  total = ALIGN (sizeof (t_zone)) + MIN_ALLOC_COUNT * chunk_size;
  page_size = (size_t)sysconf (_SC_PAGESIZE);
  return ((total + page_size - 1) & ~(page_size - 1));
}

t_zone *
zone_new (size_t alloc_max)
{
  size_t zone_size;
  t_zone *zone;
  t_chunk *chunk;

  zone_size = _s_zone_size (alloc_max);
  zone = mmap (NULL, zone_size, PROT_READ | PROT_WRITE,
               MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (zone == MAP_FAILED)
    return (NULL);
  zone->next = NULL;
  zone->size = zone_size;
  chunk = (t_chunk *)((char *)zone + ALIGN (sizeof (t_zone)));
  chunk->size = zone_size - ALIGN (sizeof (t_zone)) - ALIGN (sizeof (t_chunk));
  chunk->next = NULL;
  chunk->is_free = 1;
  return (zone);
}