2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
13 \defgroup MemPoolsAPI Memory Management (Memory Pool Allocator)
17 * MemPools are a pooled memory allocator running on top of malloc(). It's
18 * purpose is to reduce memory fragmentation and provide detailed statistics
19 * on memory consumption.
22 * Preferably all memory allocations in Squid should be done using MemPools
23 * or one of the types built on top of it (i.e. cbdata).
25 \note Usually it is better to use cbdata types as these gives you additional
26 * safeguards in references and typechecking. However, for high usage pools where
27 * the cbdata functionality of cbdata is not required directly using a MemPool
28 * might be the way to go.
31 #include "mem/Meter.h"
36 #include <gnumalloc.h>
50 /// \ingroup MemPoolsAPI
51 #define toMB(size) ( ((double) size) / ((double)(1024*1024)) )
52 /// \ingroup MemPoolsAPI
53 #define toKB(size) ( (size + 1024 - 1) / 1024 )
55 /// \ingroup MemPoolsAPI
56 #define MEM_PAGE_SIZE 4096
57 /// \ingroup MemPoolsAPI
58 #define MEM_MIN_FREE 32
59 /// \ingroup MemPoolsAPI
60 #define MEM_MAX_FREE 65535 /* unsigned short is max number of items per chunk */
62 class MemImplementingAllocator
;
65 /// \ingroup MemPoolsAPI
66 /// \todo Kill this typedef for C++
67 typedef struct _MemPoolGlobalStats MemPoolGlobalStats
;
69 /// \ingroup MemPoolsAPI
73 MemImplementingAllocator
*pool
;
74 MemPoolIterator
* next
;
79 * Object to track per-pool cumulative counters
84 mgb_t() : count(0), bytes(0) {}
91 * Object to track per-pool memory usage (alloc = inuse+idle)
103 /** history Allocations */
107 /** account Saved Allocations */
110 /** account Free calls */
114 class MemImplementingAllocator
;
116 /// \ingroup MemPoolsAPI
120 static MemPools
&GetInstance();
125 \param label Name for the pool. Displayed in stats.
126 \param obj_size Size of elements in MemPool.
128 MemImplementingAllocator
* create(const char *label
, size_t obj_size
);
131 * Sets upper limit in bytes to amount of free ram kept in pools. This is
132 * not strict upper limit, but a hint. When MemPools are over this limit,
133 * totally free chunks are immediately considered for release. Otherwise
134 * only chunks that have not been referenced for a long time are checked.
136 void setIdleLimit(ssize_t new_idle_limit
);
137 ssize_t
idleLimit() const;
141 * Main cleanup handler. For MemPools to stay within upper idle limits,
142 * this function needs to be called periodically, preferrably at some
143 * constant rate, eg. from Squid event. It looks through all pools and
144 * chunks, cleans up internal states and checks for releasable chunks.
147 * Between the calls to this function objects are placed onto internal
148 * cache instead of returning to their home chunks, mainly for speedup
149 * purpose. During that time state of chunk is not known, it is not
150 * known whether chunk is free or in use. This call returns all objects
151 * to their chunks and restores consistency.
154 * Should be called relatively often, as it sorts chunks in suitable
155 * order as to reduce free memory fragmentation and increase chunk
157 * Suitable frequency for cleanup is in range of few tens of seconds to
158 * few minutes, depending of memory activity.
160 \todo DOCS: Re-write this shorter!
162 \param maxage Release all totally idle chunks that
163 * have not been referenced for maxage seconds.
165 void clean(time_t maxage
);
167 void setDefaultPoolChunking(bool const &);
168 MemImplementingAllocator
*pools
;
169 ssize_t mem_idle_limit
;
171 bool defaultIsChunked
;
176 * a pool is a [growing] space for objects of the same size
181 MemAllocator (char const *aLabel
);
182 virtual ~MemAllocator() {}
185 \param stats Object to be filled with statistical data about pool.
186 \retval Number of objects in use, ie. allocated.
188 virtual int getStats(MemPoolStats
* stats
, int accumulate
= 0) = 0;
190 virtual MemPoolMeter
const &getMeter() const = 0;
193 * Allocate one element from the pool
195 virtual void *alloc() = 0;
198 * Free a element allocated by MemAllocator::alloc()
200 virtual void freeOne(void *) = 0;
202 virtual char const *objectType() const;
203 virtual size_t objectSize() const = 0;
204 virtual int getInUseCount() = 0;
205 void zeroBlocks(bool doIt
) {doZero
= doIt
;}
209 * Allows you tune chunk size of pooling. Objects are allocated in chunks
210 * instead of individually. This conserves memory, reduces fragmentation.
211 * Because of that memory can be freed also only in chunks. Therefore
212 * there is tradeoff between memory conservation due to chunking and free
213 * memory fragmentation.
215 \note As a general guideline, increase chunk size only for pools that keep
216 * very many items for relatively long time.
218 virtual void setChunkSize(size_t) {}
221 \param minSize Minimum size needed to be allocated.
222 \retval n Smallest size divisible by sizeof(void*)
224 static size_t RoundedSize(size_t minSize
);
227 /** Whether to zero memory on initial allocation and on return to the pool.
229 * We do this on some pools because many object constructors are/were incomplete
230 * and we are afraid some code may use the object after free.
231 * These probems are becoming less common, so when possible set this to false.
239 /// \ingroup MemPoolsAPI
240 class MemImplementingAllocator
: public MemAllocator
243 MemImplementingAllocator(char const *aLabel
, size_t aSize
);
244 virtual ~MemImplementingAllocator();
245 virtual MemPoolMeter
const &getMeter() const;
246 virtual MemPoolMeter
&getMeter();
247 virtual void flushMetersFull();
248 virtual void flushMeters();
251 * Allocate one element from the pool
253 virtual void *alloc();
256 * Free a element allocated by MemImplementingAllocator::alloc()
258 virtual void freeOne(void *);
260 virtual bool idleTrigger(int shift
) const = 0;
261 virtual void clean(time_t maxage
) = 0;
262 virtual size_t objectSize() const;
263 virtual int getInUseCount() = 0;
265 virtual void *allocate() = 0;
266 virtual void deallocate(void *, bool aggressive
) = 0;
270 MemImplementingAllocator
*next
;
278 /// \ingroup MemPoolsAPI
301 /// \ingroup MemPoolsAPI
302 /// \todo Classify and add constructor/destructor to initialize properly.
303 struct _MemPoolGlobalStats
{
304 MemPoolMeter
*TheMeter
;
308 int tot_pools_mempid
;
310 int tot_chunks_alloc
;
311 int tot_chunks_inuse
;
312 int tot_chunks_partial
;
320 ssize_t mem_idle_limit
;
323 /// \ingroup MemPoolsAPI
324 #define memPoolCreate MemPools::GetInstance().create
329 * Initialise iteration through all of the pools.
330 \retval Iterator for use by memPoolIterateNext() and memPoolIterateDone()
332 extern MemPoolIterator
* memPoolIterate(void);
336 * Get next pool pointer, until getting NULL pointer.
338 extern MemImplementingAllocator
* memPoolIterateNext(MemPoolIterator
* iter
);
342 * Should be called after finished with iterating through all pools.
344 extern void memPoolIterateDone(MemPoolIterator
** iter
);
348 \todo Stats API - not sured how to refactor yet
350 * Fills MemPoolGlobalStats with statistical data about overall
351 * usage for all pools.
353 \retval Number of pools that have at least one object in use.
354 * Ie. number of dirty pools.
356 extern int memPoolGetGlobalStats(MemPoolGlobalStats
* stats
);
358 /// \ingroup MemPoolsAPI
359 extern int memPoolsTotalAllocated(void);
361 #endif /* _MEM_POOL_H_ */