Debian Codegraph @

Xpjproject/pjlib/include/pj/pool.h

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