blob: f35bb037233247ef720c74722df522f1fca060a5 [file] [log] [blame]
Alexandre Lision8af73cb2013-12-10 14:11:20 -05001/* $Id: pool.h 4537 2013-06-19 06:47:43Z riza $ */
Tristan Matthews0a329cc2013-07-17 13:20:14 -04002/*
3 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
4 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21#include <pj/list.h>
22
23/* See if we use pool's alternate API.
24 * The alternate API is used e.g. to implement pool debugging.
25 */
26#if PJ_HAS_POOL_ALT_API
27# include <pj/pool_alt.h>
28#endif
29
30
31#ifndef __PJ_POOL_H__
32#define __PJ_POOL_H__
33
34/**
35 * @file pool.h
36 * @brief Memory Pool.
37 */
38
39PJ_BEGIN_DECL
40
41/**
42 * @defgroup PJ_POOL_GROUP Fast Memory Pool
43 * @brief
44 * Memory pools allow dynamic memory allocation comparable to malloc or the
45 * new in operator C++. Those implementations are not desirable for very
46 * high performance applications or real-time systems, because of the
47 * performance bottlenecks and it suffers from fragmentation issue.
48 *
49 * \section PJ_POOL_INTRO_SEC PJLIB's Memory Pool
50 * \subsection PJ_POOL_ADVANTAGE_SUBSEC Advantages
51 *
52 * PJLIB's pool has many advantages over traditional malloc/new operator and
53 * over other memory pool implementations, because:
54 * - unlike other memory pool implementation, it allows allocation of
55 * memory chunks of different sizes,
56 * - it's very very fast.
57 * \n
58 * Memory chunk allocation is not only an O(1)
59 * operation, but it's also very simple (just
60 * few pointer arithmetic operations) and it doesn't require locking
61 * any mutex,
62 * - it's memory efficient.
63 * \n
64 * Pool doesn't keep track individual memory chunks allocated by
65 * applications, so there is no additional overhead needed for each
66 * memory allocation (other than possible additional of few bytes, up to
67 * PJ_POOL_ALIGNMENT-1, for aligning the memory).
68 * But see the @ref PJ_POOL_CAVEATS_SUBSEC below.
69 * - it prevents memory leaks.
70 * \n
71 * Memory pool inherently has garbage collection functionality. In fact,
72 * there is no need to free the chunks allocated from the memory pool.
73 * All chunks previously allocated from the pool will be freed once the
74 * pool itself is destroyed. This would prevent memory leaks that haunt
75 * programmers for decades, and it provides additional performance
76 * advantage over traditional malloc/new operator.
77 *
78 * Even more, PJLIB's memory pool provides some additional usability and
79 * flexibility for applications:
80 * - memory leaks are easily traceable, since memory pool is assigned name,
81 * and application can inspect what pools currently active in the system.
82 * - by design, memory allocation from a pool is not thread safe. We assumed
83 * that a pool will be owned by a higher level object, and thread safety
84 * should be handled by that object. This enables very fast pool operations
85 * and prevents unnecessary locking operations,
86 * - by default, the memory pool API behaves more like C++ new operator,
87 * in that it will throw PJ_NO_MEMORY_EXCEPTION exception (see
88 * @ref PJ_EXCEPT) when memory chunk allocation fails. This enables failure
89 * handling to be done on more high level function (instead of checking
90 * the result of pj_pool_alloc() everytime). If application doesn't like
91 * this, the default behavior can be changed on global basis by supplying
92 * different policy to the pool factory.
93 * - any memory allocation backend allocator/deallocator may be used. By
94 * default, the policy uses malloc() and free() to manage the pool's block,
95 * but application may use different strategy, for example to allocate
96 * memory blocks from a globally static memory location.
97 *
98 *
99 * \subsection PJ_POOL_PERFORMANCE_SUBSEC Performance
100 *
101 * The result of PJLIB's memory design and careful implementation is a
102 * memory allocation strategy that can speed-up the memory allocations
103 * and deallocations by up to <b>30 times</b> compared to standard
104 * malloc()/free() (more than 150 million allocations per second on a
105 * P4/3.0GHz Linux machine).
106 *
107 * (Note: your mileage may vary, of course. You can see how much PJLIB's
108 * pool improves the performance over malloc()/free() in your target
109 * system by running pjlib-test application).
110 *
111 *
112 * \subsection PJ_POOL_CAVEATS_SUBSEC Caveats
113 *
114 * There are some caveats though!
115 *
116 * When creating pool, PJLIB requires applications to specify the initial
117 * pool size, and as soon as the pool is created, PJLIB allocates memory
118 * from the system by that size. Application designers MUST choose the
119 * initial pool size carefully, since choosing too big value will result in
120 * wasting system's memory.
121 *
122 * But the pool can grow. Application designer can specify how the
123 * pool will grow in size, by specifying the size increment when creating
124 * the pool.
125 *
126 * The pool, however, <b>cannot</b> shrink! Since there is <b>no</b>
127 * function to deallocate memory chunks, there is no way for the pool to
128 * release back unused memory to the system.
129 * Application designers must be aware that constant memory allocations
130 * from pool that has infinite life-time may cause the memory usage of
131 * the application to grow over time.
132 *
133 *
134 * \section PJ_POOL_USING_SEC Using Memory Pool
135 *
136 * This section describes how to use PJLIB's memory pool framework.
137 * As we hope the readers will witness, PJLIB's memory pool API is quite
138 * straightforward.
139 *
140 * \subsection PJ_POOL_USING_F Create Pool Factory
141 * First, application needs to initialize a pool factory (this normally
142 * only needs to be done once in one application). PJLIB provides
143 * a pool factory implementation called caching pool (see @ref
144 * PJ_CACHING_POOL), and it is initialized by calling #pj_caching_pool_init().
145 *
146 * \subsection PJ_POOL_USING_P Create The Pool
147 * Then application creates the pool object itself with #pj_pool_create(),
148 * specifying among other thing the pool factory where the pool should
149 * be created from, the pool name, initial size, and increment/expansion
150 * size.
151 *
152 * \subsection PJ_POOL_USING_M Allocate Memory as Required
153 * Then whenever application needs to allocate dynamic memory, it would
154 * call #pj_pool_alloc(), #pj_pool_calloc(), or #pj_pool_zalloc() to
155 * allocate memory chunks from the pool.
156 *
157 * \subsection PJ_POOL_USING_DP Destroy the Pool
158 * When application has finished with the pool, it should call
159 * #pj_pool_release() to release the pool object back to the factory.
160 * Depending on the types of the factory, this may release the memory back
161 * to the operating system.
162 *
163 * \subsection PJ_POOL_USING_Dc Destroy the Pool Factory
164 * And finally, before application quites, it should deinitialize the
165 * pool factory, to make sure that all memory blocks allocated by the
166 * factory are released back to the operating system. After this, of
167 * course no more memory pool allocation can be requested.
168 *
169 * \subsection PJ_POOL_USING_EX Example
170 * Below is a sample complete program that utilizes PJLIB's memory pool.
171 *
172 * \code
173
174 #include <pjlib.h>
175
176 #define THIS_FILE "pool_sample.c"
177
178 static void my_perror(const char *title, pj_status_t status)
179 {
180 char errmsg[PJ_ERR_MSG_SIZE];
181
182 pj_strerror(status, errmsg, sizeof(errmsg));
183 PJ_LOG(1,(THIS_FILE, "%s: %s [status=%d]", title, errmsg, status));
184 }
185
186 static void pool_demo_1(pj_pool_factory *pfactory)
187 {
188 unsigned i;
189 pj_pool_t *pool;
190
191 // Must create pool before we can allocate anything
192 pool = pj_pool_create(pfactory, // the factory
193 "pool1", // pool's name
194 4000, // initial size
195 4000, // increment size
196 NULL); // use default callback.
197 if (pool == NULL) {
198 my_perror("Error creating pool", PJ_ENOMEM);
199 return;
200 }
201
202 // Demo: allocate some memory chunks
203 for (i=0; i<1000; ++i) {
204 void *p;
205
206 p = pj_pool_alloc(pool, (pj_rand()+1) % 512);
207
208 // Do something with p
209 ...
210
211 // Look! No need to free p!!
212 }
213
214 // Done with silly demo, must free pool to release all memory.
215 pj_pool_release(pool);
216 }
217
218 int main()
219 {
220 pj_caching_pool cp;
221 pj_status_t status;
222
223 // Must init PJLIB before anything else
224 status = pj_init();
225 if (status != PJ_SUCCESS) {
226 my_perror("Error initializing PJLIB", status);
227 return 1;
228 }
229
230 // Create the pool factory, in this case, a caching pool,
231 // using default pool policy.
232 pj_caching_pool_init(&cp, NULL, 1024*1024 );
233
234 // Do a demo
235 pool_demo_1(&cp.factory);
236
237 // Done with demos, destroy caching pool before exiting app.
238 pj_caching_pool_destroy(&cp);
239
240 return 0;
241 }
242
243 \endcode
244 *
245 * More information about pool factory, the pool object, and caching pool
246 * can be found on the Module Links below.
247 */
248
249
250/**
251 * @defgroup PJ_POOL Memory Pool Object
252 * @ingroup PJ_POOL_GROUP
253 * @brief
254 * The memory pool is an opaque object created by pool factory.
255 * Application uses this object to request a memory chunk, by calling
256 * #pj_pool_alloc(), #pj_pool_calloc(), or #pj_pool_zalloc().
257 * When the application has finished using
258 * the pool, it must call #pj_pool_release() to free all the chunks previously
259 * allocated and release the pool back to the factory.
260 *
261 * A memory pool is initialized with an initial amount of memory, which is
262 * called a block. Pool can be configured to dynamically allocate more memory
263 * blocks when it runs out of memory.
264 *
265 * The pool doesn't keep track of individual memory allocations
266 * by user, and the user doesn't have to free these indidual allocations. This
267 * makes memory allocation simple and very fast. All the memory allocated from
268 * the pool will be destroyed when the pool itself is destroyed.
269 *
270 * \section PJ_POOL_THREADING_SEC More on Threading Policies
271 * - By design, memory allocation from a pool is not thread safe. We assumed
272 * that a pool will be owned by an object, and thread safety should be
273 * handled by that object. Thus these functions are not thread safe:
274 * - #pj_pool_alloc,
275 * - #pj_pool_calloc,
276 * - and other pool statistic functions.
277 * - Threading in the pool factory is decided by the policy set for the
278 * factory when it was created.
279 *
280 * \section PJ_POOL_EXAMPLES_SEC Examples
281 *
282 * For some sample codes on how to use the pool, please see:
283 * - @ref page_pjlib_pool_test
284 *
285 * @{
286 */
287
288/**
289 * The type for function to receive callback from the pool when it is unable
290 * to allocate memory. The elegant way to handle this condition is to throw
291 * exception, and this is what is expected by most of this library
292 * components.
293 */
294typedef void pj_pool_callback(pj_pool_t *pool, pj_size_t size);
295
296/**
297 * This class, which is used internally by the pool, describes a single
298 * block of memory from which user memory allocations will be allocated from.
299 */
300typedef struct pj_pool_block
301{
302 PJ_DECL_LIST_MEMBER(struct pj_pool_block); /**< List's prev and next. */
303 unsigned char *buf; /**< Start of buffer. */
304 unsigned char *cur; /**< Current alloc ptr. */
305 unsigned char *end; /**< End of buffer. */
306} pj_pool_block;
307
308
309/**
310 * This structure describes the memory pool. Only implementors of pool factory
311 * need to care about the contents of this structure.
312 */
313struct pj_pool_t
314{
315 PJ_DECL_LIST_MEMBER(struct pj_pool_t); /**< Standard list elements. */
316
317 /** Pool name */
318 char obj_name[PJ_MAX_OBJ_NAME];
319
320 /** Pool factory. */
321 pj_pool_factory *factory;
322
323 /** Data put by factory */
324 void *factory_data;
325
326 /** Current capacity allocated by the pool. */
327 pj_size_t capacity;
328
329 /** Size of memory block to be allocated when the pool runs out of memory */
330 pj_size_t increment_size;
331
332 /** List of memory blocks allcoated by the pool. */
333 pj_pool_block block_list;
334
335 /** The callback to be called when the pool is unable to allocate memory. */
336 pj_pool_callback *callback;
337
338};
339
340
341/**
342 * Guidance on how much memory required for initial pool administrative data.
343 */
344#define PJ_POOL_SIZE (sizeof(struct pj_pool_t))
345
346/**
347 * Pool memory alignment (must be power of 2).
348 */
349#ifndef PJ_POOL_ALIGNMENT
350# define PJ_POOL_ALIGNMENT 4
351#endif
352
353/**
354 * Create a new pool from the pool factory. This wrapper will call create_pool
355 * member of the pool factory.
356 *
357 * @param factory The pool factory.
358 * @param name The name to be assigned to the pool. The name should
359 * not be longer than PJ_MAX_OBJ_NAME (32 chars), or
360 * otherwise it will be truncated.
361 * @param initial_size The size of initial memory blocks taken by the pool.
362 * Note that the pool will take 68+20 bytes for
363 * administrative area from this block.
364 * @param increment_size the size of each additional blocks to be allocated
365 * when the pool is running out of memory. If user
366 * requests memory which is larger than this size, then
367 * an error occurs.
368 * Note that each time a pool allocates additional block,
369 * it needs PJ_POOL_SIZE more to store some
370 * administrative info.
371 * @param callback Callback to be called when error occurs in the pool.
372 * If this value is NULL, then the callback from pool
373 * factory policy will be used.
374 * Note that when an error occurs during pool creation,
375 * the callback itself is not called. Instead, NULL
376 * will be returned.
377 *
378 * @return The memory pool, or NULL.
379 */
380PJ_IDECL(pj_pool_t*) pj_pool_create(pj_pool_factory *factory,
381 const char *name,
382 pj_size_t initial_size,
383 pj_size_t increment_size,
384 pj_pool_callback *callback);
385
386/**
387 * Release the pool back to pool factory.
388 *
389 * @param pool Memory pool.
390 */
391PJ_IDECL(void) pj_pool_release( pj_pool_t *pool );
392
393/**
394 * Get pool object name.
395 *
396 * @param pool the pool.
397 *
398 * @return pool name as NULL terminated string.
399 */
400PJ_IDECL(const char *) pj_pool_getobjname( const pj_pool_t *pool );
401
402/**
403 * Reset the pool to its state when it was initialized.
404 * This means that if additional blocks have been allocated during runtime,
405 * then they will be freed. Only the original block allocated during
406 * initialization is retained. This function will also reset the internal
407 * counters, such as pool capacity and used size.
408 *
409 * @param pool the pool.
410 */
411PJ_DECL(void) pj_pool_reset( pj_pool_t *pool );
412
413
414/**
415 * Get the pool capacity, that is, the system storage that have been allocated
416 * by the pool, and have been used/will be used to allocate user requests.
417 * There's no guarantee that the returned value represent a single
418 * contiguous block, because the capacity may be spread in several blocks.
419 *
420 * @param pool the pool.
421 *
422 * @return the capacity.
423 */
424PJ_IDECL(pj_size_t) pj_pool_get_capacity( pj_pool_t *pool );
425
426/**
427 * Get the total size of user allocation request.
428 *
429 * @param pool the pool.
430 *
431 * @return the total size.
432 */
433PJ_IDECL(pj_size_t) pj_pool_get_used_size( pj_pool_t *pool );
434
435/**
436 * Allocate storage with the specified size from the pool.
437 * If there's no storage available in the pool, then the pool can allocate more
438 * blocks if the increment size is larger than the requested size.
439 *
440 * @param pool the pool.
441 * @param size the requested size.
442 *
443 * @return pointer to the allocated memory.
444 *
445 * @see PJ_POOL_ALLOC_T
446 */
447PJ_IDECL(void*) pj_pool_alloc( pj_pool_t *pool, pj_size_t size);
448
449/**
450 * Allocate storage from the pool, and initialize it to zero.
451 * This function behaves like pj_pool_alloc(), except that the storage will
452 * be initialized to zero.
453 *
454 * @param pool the pool.
455 * @param count the number of elements in the array.
456 * @param elem the size of individual element.
457 *
458 * @return pointer to the allocated memory.
459 */
460PJ_IDECL(void*) pj_pool_calloc( pj_pool_t *pool, pj_size_t count,
461 pj_size_t elem);
462
463
464/**
465 * Allocate storage from the pool and initialize it to zero.
466 *
467 * @param pool The pool.
468 * @param size The size to be allocated.
469 *
470 * @return Pointer to the allocated memory.
471 *
472 * @see PJ_POOL_ZALLOC_T
473 */
474PJ_INLINE(void*) pj_pool_zalloc(pj_pool_t *pool, pj_size_t size)
475{
476 return pj_pool_calloc(pool, 1, size);
477}
478
479
480/**
481 * This macro allocates memory from the pool and returns the instance of
482 * the specified type. It provides a stricker type safety than pj_pool_alloc()
483 * since the return value of this macro will be type-casted to the specified
484 * type.
485 *
486 * @param pool The pool
487 * @param type The type of object to be allocated
488 *
489 * @return Memory buffer of the specified type.
490 */
491#define PJ_POOL_ALLOC_T(pool,type) \
492 ((type*)pj_pool_alloc(pool, sizeof(type)))
493
494/**
495 * This macro allocates memory from the pool, zeroes the buffer, and
496 * returns the instance of the specified type. It provides a stricker type
497 * safety than pj_pool_zalloc() since the return value of this macro will be
498 * type-casted to the specified type.
499 *
500 * @param pool The pool
501 * @param type The type of object to be allocated
502 *
503 * @return Memory buffer of the specified type.
504 */
505#define PJ_POOL_ZALLOC_T(pool,type) \
506 ((type*)pj_pool_zalloc(pool, sizeof(type)))
507
508/*
509 * Internal functions
510 */
511PJ_IDECL(void*) pj_pool_alloc_from_block(pj_pool_block *block, pj_size_t size);
512PJ_DECL(void*) pj_pool_allocate_find(pj_pool_t *pool, pj_size_t size);
513
514
515
516/**
517 * @} // PJ_POOL
518 */
519
520/* **************************************************************************/
521/**
522 * @defgroup PJ_POOL_FACTORY Pool Factory and Policy
523 * @ingroup PJ_POOL_GROUP
524 * @brief
525 * A pool object must be created through a factory. A factory not only provides
526 * generic interface functions to create and release pool, but also provides
527 * strategy to manage the life time of pools. One sample implementation,
528 * \a pj_caching_pool, can be set to keep the pools released by application for
529 * future use as long as the total memory is below the limit.
530 *
531 * The pool factory interface declared in PJLIB is designed to be extensible.
532 * Application can define its own strategy by creating it's own pool factory
533 * implementation, and this strategy can be used even by existing library
534 * without recompilation.
535 *
536 * \section PJ_POOL_FACTORY_ITF Pool Factory Interface
537 * The pool factory defines the following interface:
538 * - \a policy: the memory pool factory policy.
539 * - \a create_pool(): create a new memory pool.
540 * - \a release_pool(): release memory pool back to factory.
541 *
542 * \section PJ_POOL_FACTORY_POL Pool Factory Policy.
543 *
544 * A pool factory only defines functions to create and release pool and how
545 * to manage pools, but the rest of the functionalities are controlled by
546 * policy. A pool policy defines:
547 * - how memory block is allocated and deallocated (the default implementation
548 * allocates and deallocate memory by calling malloc() and free()).
549 * - callback to be called when memory allocation inside a pool fails (the
550 * default implementation will throw PJ_NO_MEMORY_EXCEPTION exception).
551 * - concurrency when creating and releasing pool from/to the factory.
552 *
553 * A pool factory can be given different policy during creation to make
554 * it behave differently. For example, caching pool factory can be configured
555 * to allocate and deallocate from a static/contiguous/preallocated memory
556 * instead of using malloc()/free().
557 *
558 * What strategy/factory and what policy to use is not defined by PJLIB, but
559 * instead is left to application to make use whichever is most efficient for
560 * itself.
561 *
562 * The pool factory policy controls the behaviour of memory factories, and
563 * defines the following interface:
564 * - \a block_alloc(): allocate memory block from backend memory mgmt/system.
565 * - \a block_free(): free memory block back to backend memory mgmt/system.
566 * @{
567 */
568
569/* We unfortunately don't have support for factory policy options as now,
570 so we keep this commented at the moment.
571enum PJ_POOL_FACTORY_OPTION
572{
573 PJ_POOL_FACTORY_SERIALIZE = 1
574};
575*/
576
577/**
578 * This structure declares pool factory interface.
579 */
580typedef struct pj_pool_factory_policy
581{
582 /**
583 * Allocate memory block (for use by pool). This function is called
584 * by memory pool to allocate memory block.
585 *
586 * @param factory Pool factory.
587 * @param size The size of memory block to allocate.
588 *
589 * @return Memory block.
590 */
591 void* (*block_alloc)(pj_pool_factory *factory, pj_size_t size);
592
593 /**
594 * Free memory block.
595 *
596 * @param factory Pool factory.
597 * @param mem Memory block previously allocated by block_alloc().
598 * @param size The size of memory block.
599 */
600 void (*block_free)(pj_pool_factory *factory, void *mem, pj_size_t size);
601
602 /**
603 * Default callback to be called when memory allocation fails.
604 */
605 pj_pool_callback *callback;
606
607 /**
608 * Option flags.
609 */
610 unsigned flags;
611
612} pj_pool_factory_policy;
613
614/**
615 * \def PJ_NO_MEMORY_EXCEPTION
616 * This constant denotes the exception number that will be thrown by default
617 * memory factory policy when memory allocation fails.
618 *
619 * @see pj_NO_MEMORY_EXCEPTION()
620 */
621PJ_DECL_DATA(int) PJ_NO_MEMORY_EXCEPTION;
622
623/**
624 * Get #PJ_NO_MEMORY_EXCEPTION constant.
625 */
626PJ_DECL(int) pj_NO_MEMORY_EXCEPTION(void);
627
628/**
629 * This global variable points to default memory pool factory policy.
630 * The behaviour of the default policy is:
631 * - block allocation and deallocation use malloc() and free().
632 * - callback will raise PJ_NO_MEMORY_EXCEPTION exception.
633 * - access to pool factory is not serialized (i.e. not thread safe).
634 *
635 * @see pj_pool_factory_get_default_policy
636 */
637PJ_DECL_DATA(pj_pool_factory_policy) pj_pool_factory_default_policy;
638
639
640/**
641 * Get the default pool factory policy.
642 *
643 * @return the pool policy.
644 */
645PJ_DECL(const pj_pool_factory_policy*) pj_pool_factory_get_default_policy(void);
646
647
648/**
649 * This structure contains the declaration for pool factory interface.
650 */
651struct pj_pool_factory
652{
653 /**
654 * Memory pool policy.
655 */
656 pj_pool_factory_policy policy;
657
658 /**
659 * Create a new pool from the pool factory.
660 *
661 * @param factory The pool factory.
662 * @param name the name to be assigned to the pool. The name should
663 * not be longer than PJ_MAX_OBJ_NAME (32 chars), or
664 * otherwise it will be truncated.
665 * @param initial_size the size of initial memory blocks taken by the pool.
666 * Note that the pool will take 68+20 bytes for
667 * administrative area from this block.
668 * @param increment_size the size of each additional blocks to be allocated
669 * when the pool is running out of memory. If user
670 * requests memory which is larger than this size, then
671 * an error occurs.
672 * Note that each time a pool allocates additional block,
673 * it needs 20 bytes (equal to sizeof(pj_pool_block)) to
674 * store some administrative info.
675 * @param callback Cllback to be called when error occurs in the pool.
676 * Note that when an error occurs during pool creation,
677 * the callback itself is not called. Instead, NULL
678 * will be returned.
679 *
680 * @return the memory pool, or NULL.
681 */
682 pj_pool_t* (*create_pool)( pj_pool_factory *factory,
683 const char *name,
684 pj_size_t initial_size,
685 pj_size_t increment_size,
686 pj_pool_callback *callback);
687
688 /**
689 * Release the pool to the pool factory.
690 *
691 * @param factory The pool factory.
692 * @param pool The pool to be released.
693 */
694 void (*release_pool)( pj_pool_factory *factory, pj_pool_t *pool );
695
696 /**
697 * Dump pool status to log.
698 *
699 * @param factory The pool factory.
700 */
701 void (*dump_status)( pj_pool_factory *factory, pj_bool_t detail );
702
703 /**
704 * This is optional callback to be called by allocation policy when
705 * it allocates a new memory block. The factory may use this callback
706 * for example to keep track of the total number of memory blocks
707 * currently allocated by applications.
708 *
709 * @param factory The pool factory.
710 * @param size Size requested by application.
711 *
712 * @return MUST return PJ_TRUE, otherwise the block
713 * allocation is cancelled.
714 */
715 pj_bool_t (*on_block_alloc)(pj_pool_factory *factory, pj_size_t size);
716
717 /**
718 * This is optional callback to be called by allocation policy when
719 * it frees memory block. The factory may use this callback
720 * for example to keep track of the total number of memory blocks
721 * currently allocated by applications.
722 *
723 * @param factory The pool factory.
724 * @param size Size freed.
725 */
726 void (*on_block_free)(pj_pool_factory *factory, pj_size_t size);
727
728};
729
730/**
731 * This function is intended to be used by pool factory implementors.
732 * @param factory Pool factory.
733 * @param name Pool name.
734 * @param initial_size Initial size.
735 * @param increment_size Increment size.
736 * @param callback Callback.
737 * @return The pool object, or NULL.
738 */
739PJ_DECL(pj_pool_t*) pj_pool_create_int( pj_pool_factory *factory,
740 const char *name,
741 pj_size_t initial_size,
742 pj_size_t increment_size,
743 pj_pool_callback *callback);
744
745/**
746 * This function is intended to be used by pool factory implementors.
747 * @param pool The pool.
748 * @param name Pool name.
749 * @param increment_size Increment size.
750 * @param callback Callback function.
751 */
752PJ_DECL(void) pj_pool_init_int( pj_pool_t *pool,
753 const char *name,
754 pj_size_t increment_size,
755 pj_pool_callback *callback);
756
757/**
758 * This function is intended to be used by pool factory implementors.
759 * @param pool The memory pool.
760 */
761PJ_DECL(void) pj_pool_destroy_int( pj_pool_t *pool );
762
763
764/**
765 * Dump pool factory state.
766 * @param pf The pool factory.
767 * @param detail Detail state required.
768 */
769PJ_INLINE(void) pj_pool_factory_dump( pj_pool_factory *pf,
770 pj_bool_t detail )
771{
772 (*pf->dump_status)(pf, detail);
773}
774
775/**
776 * @} // PJ_POOL_FACTORY
777 */
778
779/* **************************************************************************/
780
781/**
782 * @defgroup PJ_CACHING_POOL Caching Pool Factory
783 * @ingroup PJ_POOL_GROUP
784 * @brief
785 * Caching pool is one sample implementation of pool factory where the
786 * factory can reuse memory to create a pool. Application defines what the
787 * maximum memory the factory can hold, and when a pool is released the
788 * factory decides whether to destroy the pool or to keep it for future use.
789 * If the total amount of memory in the internal cache is still within the
790 * limit, the factory will keep the pool in the internal cache, otherwise the
791 * pool will be destroyed, thus releasing the memory back to the system.
792 *
793 * @{
794 */
795
796/**
797 * Number of unique sizes, to be used as index to the free list.
798 * Each pool in the free list is organized by it's size.
799 */
800#define PJ_CACHING_POOL_ARRAY_SIZE 16
801
802/**
803 * Declaration for caching pool. Application doesn't normally need to
804 * care about the contents of this struct, it is only provided here because
805 * application need to define an instance of this struct (we can not allocate
806 * the struct from a pool since there is no pool factory yet!).
807 */
808struct pj_caching_pool
809{
810 /** Pool factory interface, must be declared first. */
811 pj_pool_factory factory;
812
813 /** Current factory's capacity, i.e. number of bytes that are allocated
814 * and available for application in this factory. The factory's
815 * capacity represents the size of all pools kept by this factory
816 * in it's free list, which will be returned to application when it
817 * requests to create a new pool.
818 */
819 pj_size_t capacity;
820
821 /** Maximum size that can be held by this factory. Once the capacity
822 * has exceeded @a max_capacity, further #pj_pool_release() will
823 * flush the pool. If the capacity is still below the @a max_capacity,
824 * #pj_pool_release() will save the pool to the factory's free list.
825 */
826 pj_size_t max_capacity;
827
828 /**
829 * Number of pools currently held by applications. This number gets
830 * incremented everytime #pj_pool_create() is called, and gets
831 * decremented when #pj_pool_release() is called.
832 */
833 pj_size_t used_count;
834
835 /**
836 * Total size of memory currently used by application.
837 */
838 pj_size_t used_size;
839
840 /**
841 * The maximum size of memory used by application throughout the life
842 * of the caching pool.
843 */
844 pj_size_t peak_used_size;
845
846 /**
847 * Lists of pools in the cache, indexed by pool size.
848 */
849 pj_list free_list[PJ_CACHING_POOL_ARRAY_SIZE];
850
851 /**
852 * List of pools currently allocated by applications.
853 */
854 pj_list used_list;
855
856 /**
857 * Internal pool.
858 */
859 char pool_buf[256 * (sizeof(size_t) / 4)];
860
861 /**
862 * Mutex.
863 */
864 pj_lock_t *lock;
865};
866
867
868
869/**
870 * Initialize caching pool.
871 *
872 * @param ch_pool The caching pool factory to be initialized.
873 * @param policy Pool factory policy.
874 * @param max_capacity The total capacity to be retained in the cache. When
875 * the pool is returned to the cache, it will be kept in
876 * recycling list if the total capacity of pools in this
877 * list plus the capacity of the pool is still below this
878 * value.
879 */
880PJ_DECL(void) pj_caching_pool_init( pj_caching_pool *ch_pool,
881 const pj_pool_factory_policy *policy,
882 pj_size_t max_capacity);
883
884
885/**
886 * Destroy caching pool, and release all the pools in the recycling list.
887 *
888 * @param ch_pool The caching pool.
889 */
890PJ_DECL(void) pj_caching_pool_destroy( pj_caching_pool *ch_pool );
891
892/**
893 * @} // PJ_CACHING_POOL
894 */
895
896# if PJ_FUNCTIONS_ARE_INLINED
897# include "pool_i.h"
898# endif
899
900PJ_END_DECL
901
902#endif /* __PJ_POOL_H__ */
903