Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /*
  2. * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 2 of the
  7. * License, or any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. */
  18. FILE_LICENCE ( GPL2_OR_LATER );
  19. #include <stddef.h>
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include <strings.h>
  23. #include <ipxe/io.h>
  24. #include <ipxe/list.h>
  25. #include <ipxe/init.h>
  26. #include <ipxe/refcnt.h>
  27. #include <ipxe/malloc.h>
  28. #include <valgrind/memcheck.h>
  29. /** @file
  30. *
  31. * Dynamic memory allocation
  32. *
  33. */
  34. /** A free block of memory */
  35. struct memory_block {
  36. /** Size of this block */
  37. size_t size;
  38. /** Padding
  39. *
  40. * This padding exists to cover the "count" field of a
  41. * reference counter, in the common case where a reference
  42. * counter is the first element of a dynamically-allocated
  43. * object. It avoids clobbering the "count" field as soon as
  44. * the memory is freed, and so allows for the possibility of
  45. * detecting reference counting errors.
  46. */
  47. char pad[ offsetof ( struct refcnt, count ) +
  48. sizeof ( ( ( struct refcnt * ) NULL )->count ) ];
  49. /** List of free blocks */
  50. struct list_head list;
  51. };
  52. #define MIN_MEMBLOCK_SIZE \
  53. ( ( size_t ) ( 1 << ( fls ( sizeof ( struct memory_block ) - 1 ) ) ) )
  54. /** A block of allocated memory complete with size information */
  55. struct autosized_block {
  56. /** Size of this block */
  57. size_t size;
  58. /** Remaining data */
  59. char data[0];
  60. };
  61. /**
  62. * Address for zero-length memory blocks
  63. *
  64. * @c malloc(0) or @c realloc(ptr,0) will return the special value @c
  65. * NOWHERE. Calling @c free(NOWHERE) will have no effect.
  66. *
  67. * This is consistent with the ANSI C standards, which state that
  68. * "either NULL or a pointer suitable to be passed to free()" must be
  69. * returned in these cases. Using a special non-NULL value means that
  70. * the caller can take a NULL return value to indicate failure,
  71. * without first having to check for a requested size of zero.
  72. *
  73. * Code outside of malloc.c do not ever need to refer to the actual
  74. * value of @c NOWHERE; this is an internal definition.
  75. */
  76. #define NOWHERE ( ( void * ) ~( ( intptr_t ) 0 ) )
  77. /** List of free memory blocks */
  78. static LIST_HEAD ( free_blocks );
  79. /** Total amount of free memory */
  80. size_t freemem;
  81. /**
  82. * Heap size
  83. *
  84. * Currently fixed at 128kB.
  85. */
  86. #define HEAP_SIZE ( 128 * 1024 )
  87. /** The heap itself */
  88. static char heap[HEAP_SIZE] __attribute__ (( aligned ( __alignof__(void *) )));
  89. /**
  90. * Mark all blocks in free list as defined
  91. *
  92. */
  93. static inline void valgrind_make_blocks_defined ( void ) {
  94. struct memory_block *block;
  95. if ( RUNNING_ON_VALGRIND > 0 ) {
  96. VALGRIND_MAKE_MEM_DEFINED ( &free_blocks,
  97. sizeof ( free_blocks ) );
  98. list_for_each_entry ( block, &free_blocks, list )
  99. VALGRIND_MAKE_MEM_DEFINED ( block, sizeof ( *block ) );
  100. }
  101. }
  102. /**
  103. * Mark all blocks in free list as inaccessible
  104. *
  105. */
  106. static inline void valgrind_make_blocks_noaccess ( void ) {
  107. struct memory_block *block;
  108. struct memory_block *tmp;
  109. if ( RUNNING_ON_VALGRIND > 0 ) {
  110. list_for_each_entry_safe ( block, tmp, &free_blocks, list )
  111. VALGRIND_MAKE_MEM_NOACCESS ( block, sizeof ( *block ) );
  112. VALGRIND_MAKE_MEM_NOACCESS ( &free_blocks,
  113. sizeof ( free_blocks ) );
  114. }
  115. }
  116. /**
  117. * Discard some cached data
  118. *
  119. * @ret discarded Number of cached items discarded
  120. */
  121. static unsigned int discard_cache ( void ) {
  122. struct cache_discarder *discarder;
  123. unsigned int discarded = 0;
  124. for_each_table_entry ( discarder, CACHE_DISCARDERS ) {
  125. discarded += discarder->discard();
  126. }
  127. return discarded;
  128. }
  129. /**
  130. * Allocate a memory block
  131. *
  132. * @v size Requested size
  133. * @v align Physical alignment
  134. * @ret ptr Memory block, or NULL
  135. *
  136. * Allocates a memory block @b physically aligned as requested. No
  137. * guarantees are provided for the alignment of the virtual address.
  138. *
  139. * @c align must be a power of two. @c size may not be zero.
  140. */
  141. void * alloc_memblock ( size_t size, size_t align ) {
  142. struct memory_block *block;
  143. size_t align_mask;
  144. size_t pre_size;
  145. ssize_t post_size;
  146. struct memory_block *pre;
  147. struct memory_block *post;
  148. struct memory_block *ptr;
  149. valgrind_make_blocks_defined();
  150. /* Round up size to multiple of MIN_MEMBLOCK_SIZE and
  151. * calculate alignment mask.
  152. */
  153. size = ( size + MIN_MEMBLOCK_SIZE - 1 ) & ~( MIN_MEMBLOCK_SIZE - 1 );
  154. align_mask = ( align - 1 ) | ( MIN_MEMBLOCK_SIZE - 1 );
  155. DBG ( "Allocating %#zx (aligned %#zx)\n", size, align );
  156. while ( 1 ) {
  157. /* Search through blocks for the first one with enough space */
  158. list_for_each_entry ( block, &free_blocks, list ) {
  159. pre_size = ( - virt_to_phys ( block ) ) & align_mask;
  160. post_size = block->size - pre_size - size;
  161. if ( post_size >= 0 ) {
  162. /* Split block into pre-block, block, and
  163. * post-block. After this split, the "pre"
  164. * block is the one currently linked into the
  165. * free list.
  166. */
  167. pre = block;
  168. block = ( ( ( void * ) pre ) + pre_size );
  169. post = ( ( ( void * ) block ) + size );
  170. DBG ( "[%p,%p) -> [%p,%p) + [%p,%p)\n", pre,
  171. ( ( ( void * ) pre ) + pre->size ),
  172. pre, block, post,
  173. ( ( ( void * ) pre ) + pre->size ) );
  174. /* If there is a "post" block, add it in to
  175. * the free list. Leak it if it is too small
  176. * (which can happen only at the very end of
  177. * the heap).
  178. */
  179. if ( (size_t) post_size >= MIN_MEMBLOCK_SIZE ) {
  180. VALGRIND_MAKE_MEM_DEFINED ( post,
  181. sizeof ( *post ) );
  182. post->size = post_size;
  183. list_add ( &post->list, &pre->list );
  184. }
  185. /* Shrink "pre" block, leaving the main block
  186. * isolated and no longer part of the free
  187. * list.
  188. */
  189. pre->size = pre_size;
  190. /* If there is no "pre" block, remove it from
  191. * the list. Also remove it (i.e. leak it) if
  192. * it is too small, which can happen only at
  193. * the very start of the heap.
  194. */
  195. if ( pre_size < MIN_MEMBLOCK_SIZE )
  196. list_del ( &pre->list );
  197. /* Update total free memory */
  198. freemem -= size;
  199. /* Return allocated block */
  200. DBG ( "Allocated [%p,%p)\n", block,
  201. ( ( ( void * ) block ) + size ) );
  202. ptr = block;
  203. goto done;
  204. }
  205. }
  206. /* Try discarding some cached data to free up memory */
  207. if ( ! discard_cache() ) {
  208. /* Nothing available to discard */
  209. DBG ( "Failed to allocate %#zx (aligned %#zx)\n",
  210. size, align );
  211. ptr = NULL;
  212. goto done;
  213. }
  214. }
  215. done:
  216. valgrind_make_blocks_noaccess();
  217. return ptr;
  218. }
  219. /**
  220. * Free a memory block
  221. *
  222. * @v ptr Memory allocated by alloc_memblock(), or NULL
  223. * @v size Size of the memory
  224. *
  225. * If @c ptr is NULL, no action is taken.
  226. */
  227. void free_memblock ( void *ptr, size_t size ) {
  228. struct memory_block *freeing;
  229. struct memory_block *block;
  230. struct memory_block *tmp;
  231. ssize_t gap_before;
  232. ssize_t gap_after = -1;
  233. /* Allow for ptr==NULL */
  234. if ( ! ptr )
  235. return;
  236. valgrind_make_blocks_defined();
  237. /* Round up size to match actual size that alloc_memblock()
  238. * would have used.
  239. */
  240. size = ( size + MIN_MEMBLOCK_SIZE - 1 ) & ~( MIN_MEMBLOCK_SIZE - 1 );
  241. freeing = ptr;
  242. VALGRIND_MAKE_MEM_DEFINED ( freeing, sizeof ( *freeing ) );
  243. freeing->size = size;
  244. DBG ( "Freeing [%p,%p)\n", freeing, ( ( ( void * ) freeing ) + size ));
  245. /* Insert/merge into free list */
  246. list_for_each_entry_safe ( block, tmp, &free_blocks, list ) {
  247. /* Calculate gaps before and after the "freeing" block */
  248. gap_before = ( ( ( void * ) freeing ) -
  249. ( ( ( void * ) block ) + block->size ) );
  250. gap_after = ( ( ( void * ) block ) -
  251. ( ( ( void * ) freeing ) + freeing->size ) );
  252. /* Merge with immediately preceding block, if possible */
  253. if ( gap_before == 0 ) {
  254. DBG ( "[%p,%p) + [%p,%p) -> [%p,%p)\n", block,
  255. ( ( ( void * ) block ) + block->size ), freeing,
  256. ( ( ( void * ) freeing ) + freeing->size ),block,
  257. ( ( ( void * ) freeing ) + freeing->size ) );
  258. block->size += size;
  259. list_del ( &block->list );
  260. freeing = block;
  261. }
  262. /* Stop processing as soon as we reach a following block */
  263. if ( gap_after >= 0 )
  264. break;
  265. }
  266. /* Insert before the immediately following block. If
  267. * possible, merge the following block into the "freeing"
  268. * block.
  269. */
  270. DBG ( "[%p,%p)\n", freeing, ( ( ( void * ) freeing ) + freeing->size));
  271. list_add_tail ( &freeing->list, &block->list );
  272. if ( gap_after == 0 ) {
  273. DBG ( "[%p,%p) + [%p,%p) -> [%p,%p)\n", freeing,
  274. ( ( ( void * ) freeing ) + freeing->size ), block,
  275. ( ( ( void * ) block ) + block->size ), freeing,
  276. ( ( ( void * ) block ) + block->size ) );
  277. freeing->size += block->size;
  278. list_del ( &block->list );
  279. }
  280. /* Update free memory counter */
  281. freemem += size;
  282. valgrind_make_blocks_noaccess();
  283. }
  284. /**
  285. * Reallocate memory
  286. *
  287. * @v old_ptr Memory previously allocated by malloc(), or NULL
  288. * @v new_size Requested size
  289. * @ret new_ptr Allocated memory, or NULL
  290. *
  291. * Allocates memory with no particular alignment requirement. @c
  292. * new_ptr will be aligned to at least a multiple of sizeof(void*).
  293. * If @c old_ptr is non-NULL, then the contents of the newly allocated
  294. * memory will be the same as the contents of the previously allocated
  295. * memory, up to the minimum of the old and new sizes. The old memory
  296. * will be freed.
  297. *
  298. * If allocation fails the previously allocated block is left
  299. * untouched and NULL is returned.
  300. *
  301. * Calling realloc() with a new size of zero is a valid way to free a
  302. * memory block.
  303. */
  304. void * realloc ( void *old_ptr, size_t new_size ) {
  305. struct autosized_block *old_block;
  306. struct autosized_block *new_block;
  307. size_t old_total_size;
  308. size_t new_total_size;
  309. size_t old_size;
  310. void *new_ptr = NOWHERE;
  311. /* Allocate new memory if necessary. If allocation fails,
  312. * return without touching the old block.
  313. */
  314. if ( new_size ) {
  315. new_total_size = ( new_size +
  316. offsetof ( struct autosized_block, data ) );
  317. new_block = alloc_memblock ( new_total_size, 1 );
  318. if ( ! new_block )
  319. return NULL;
  320. VALGRIND_MAKE_MEM_UNDEFINED ( new_block, offsetof ( struct autosized_block, data ) );
  321. new_block->size = new_total_size;
  322. VALGRIND_MAKE_MEM_NOACCESS ( new_block, offsetof ( struct autosized_block, data ) );
  323. new_ptr = &new_block->data;
  324. VALGRIND_MALLOCLIKE_BLOCK ( new_ptr, new_size, 0, 0 );
  325. }
  326. /* Copy across relevant part of the old data region (if any),
  327. * then free it. Note that at this point either (a) new_ptr
  328. * is valid, or (b) new_size is 0; either way, the memcpy() is
  329. * valid.
  330. */
  331. if ( old_ptr && ( old_ptr != NOWHERE ) ) {
  332. old_block = container_of ( old_ptr, struct autosized_block,
  333. data );
  334. VALGRIND_MAKE_MEM_DEFINED ( old_block, offsetof ( struct autosized_block, data ) );
  335. old_total_size = old_block->size;
  336. old_size = ( old_total_size -
  337. offsetof ( struct autosized_block, data ) );
  338. memcpy ( new_ptr, old_ptr,
  339. ( ( old_size < new_size ) ? old_size : new_size ) );
  340. free_memblock ( old_block, old_total_size );
  341. VALGRIND_MAKE_MEM_NOACCESS ( old_block, offsetof ( struct autosized_block, data ) );
  342. VALGRIND_FREELIKE_BLOCK ( old_ptr, 0 );
  343. }
  344. return new_ptr;
  345. }
  346. /**
  347. * Allocate memory
  348. *
  349. * @v size Requested size
  350. * @ret ptr Memory, or NULL
  351. *
  352. * Allocates memory with no particular alignment requirement. @c ptr
  353. * will be aligned to at least a multiple of sizeof(void*).
  354. */
  355. void * malloc ( size_t size ) {
  356. return realloc ( NULL, size );
  357. }
  358. /**
  359. * Free memory
  360. *
  361. * @v ptr Memory allocated by malloc(), or NULL
  362. *
  363. * Memory allocated with malloc_dma() cannot be freed with free(); it
  364. * must be freed with free_dma() instead.
  365. *
  366. * If @c ptr is NULL, no action is taken.
  367. */
  368. void free ( void *ptr ) {
  369. realloc ( ptr, 0 );
  370. }
  371. /**
  372. * Allocate cleared memory
  373. *
  374. * @v size Requested size
  375. * @ret ptr Allocated memory
  376. *
  377. * Allocate memory as per malloc(), and zero it.
  378. *
  379. * This function name is non-standard, but pretty intuitive.
  380. * zalloc(size) is always equivalent to calloc(1,size)
  381. */
  382. void * zalloc ( size_t size ) {
  383. void *data;
  384. data = malloc ( size );
  385. if ( data )
  386. memset ( data, 0, size );
  387. return data;
  388. }
  389. /**
  390. * Add memory to allocation pool
  391. *
  392. * @v start Start address
  393. * @v end End address
  394. *
  395. * Adds a block of memory [start,end) to the allocation pool. This is
  396. * a one-way operation; there is no way to reclaim this memory.
  397. *
  398. * @c start must be aligned to at least a multiple of sizeof(void*).
  399. */
  400. void mpopulate ( void *start, size_t len ) {
  401. /* Prevent free_memblock() from rounding up len beyond the end
  402. * of what we were actually given...
  403. */
  404. free_memblock ( start, ( len & ~( MIN_MEMBLOCK_SIZE - 1 ) ) );
  405. }
  406. /**
  407. * Initialise the heap
  408. *
  409. */
  410. static void init_heap ( void ) {
  411. VALGRIND_MAKE_MEM_NOACCESS ( heap, sizeof ( heap ) );
  412. mpopulate ( heap, sizeof ( heap ) );
  413. }
  414. /** Memory allocator initialisation function */
  415. struct init_fn heap_init_fn __init_fn ( INIT_EARLY ) = {
  416. .initialise = init_heap,
  417. };
  418. #if 0
  419. #include <stdio.h>
  420. /**
  421. * Dump free block list
  422. *
  423. */
  424. void mdumpfree ( void ) {
  425. struct memory_block *block;
  426. printf ( "Free block list:\n" );
  427. list_for_each_entry ( block, &free_blocks, list ) {
  428. printf ( "[%p,%p] (size %#zx)\n", block,
  429. ( ( ( void * ) block ) + block->size ), block->size );
  430. }
  431. }
  432. #endif