pool.h 32 KB

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