Statistics
| Branch: | Revision:

iof-bird-daemon / lib / mempool.c @ 18c8241a

History | View | Annotate | Download (2.1 KB)

1
/*
2
 *        BIRD Resource Manager -- Memory Pools
3
 *
4
 *        (c) 1998 Martin Mares <mj@ucw.cz>
5
 *
6
 *        Can be freely distributed and used under the terms of the GNU GPL.
7
 */
8

    
9
#include <stdlib.h>
10
#include <string.h>
11

    
12
#include "nest/bird.h"
13
#include "lib/resource.h"
14

    
15
struct mp_chunk {
16
  struct mp_chunk *next;
17
  byte data[0];
18
};
19

    
20
struct mempool {
21
  resource r;
22
  byte *ptr, *end;
23
  struct mp_chunk *first, **plast;
24
  unsigned chunk_size, threshold, total;
25
};
26

    
27
void mp_free(resource *);
28
void mp_dump(resource *);
29

    
30
struct resclass mp_class = {
31
  "MemPool",
32
  sizeof(struct mempool),
33
  mp_free,
34
  mp_dump
35
};
36

    
37
mempool
38
*mp_new(pool *p, unsigned blk)
39
{
40
  mempool *m = ralloc(p, &mp_class);
41
  m->ptr = m->end = NULL;
42
  m->first = NULL;
43
  m->plast = &m->first;
44
  m->chunk_size = blk;
45
  m->threshold = 3*blk/4;
46
  m->total = 0;
47
  return m;
48
}
49

    
50
void *
51
mp_alloc(mempool *m, unsigned size)
52
{
53
  byte *a = (byte *) ALIGN((unsigned long) m->ptr, CPU_STRUCT_ALIGN);
54
  byte *e = a + size;
55

    
56
  if (e <= m->end)
57
    {
58
      m->ptr = e;
59
      return a;
60
    }
61
  else
62
    {
63
      struct mp_chunk *c;
64
      if (size >= m->threshold)
65
        {
66
          c = xmalloc(sizeof(struct mp_chunk) + size);
67
          m->total += size;
68
        }
69
      else
70
        {
71
          c = xmalloc(sizeof(struct mp_chunk) + m->chunk_size);
72
          m->ptr = c->data + size;
73
          m->end = c->data + m->chunk_size;
74
          m->total += m->chunk_size;
75
        }
76
      *m->plast = c;
77
      m->plast = &c->next;
78
      c->next = NULL;
79
      return c->data;
80
    }
81
}
82

    
83
void *
84
mp_allocu(mempool *m, unsigned size)
85
{
86
  byte *a = m->ptr;
87
  byte *e = a + size;
88

    
89
  if (e <= m->end)
90
    {
91
      m->ptr = e;
92
      return a;
93
    }
94
  return mp_alloc(m, size);
95
}
96

    
97
void *
98
mp_allocz(mempool *m, unsigned size)
99
{
100
  void *z = mp_alloc(m, size);
101

    
102
  bzero(z, size);
103
  return z;
104
}
105

    
106
void
107
mp_free(resource *r)
108
{
109
  mempool *m = (mempool *) r;
110
  struct mp_chunk *c, *d;
111

    
112
  for(d=m->first; d; d = c)
113
    {
114
      c = d->next;
115
      xfree(d);
116
    }
117
}
118

    
119
void
120
mp_dump(resource *r)
121
{
122
  mempool *m = (mempool *) r;
123
  struct mp_chunk *c;
124
  int cnt;
125

    
126
  for(cnt=0, c=m->first; c; c=c->next, cnt++)
127
    ;
128
  debug("(chunk=%d threshold=%d count=%d total=%d)\n",
129
        m->chunk_size,
130
        m->threshold,
131
        cnt,
132
        m->total);
133
}