Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / core / malloc.c
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., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  */
19
20 FILE_LICENCE ( GPL2_OR_LATER );
21
22 #include <stddef.h>
23 #include <stdint.h>
24 #include <string.h>
25 #include <strings.h>
26 #include <ipxe/io.h>
27 #include <ipxe/list.h>
28 #include <ipxe/init.h>
29 #include <ipxe/refcnt.h>
30 #include <ipxe/malloc.h>
31 #include <valgrind/memcheck.h>
32
33 /** @file
34  *
35  * Dynamic memory allocation
36  *
37  */
38
39 /** A free block of memory */
40 struct memory_block {
41         /** Size of this block */
42         size_t size;
43         /** Padding
44          *
45          * This padding exists to cover the "count" field of a
46          * reference counter, in the common case where a reference
47          * counter is the first element of a dynamically-allocated
48          * object.  It avoids clobbering the "count" field as soon as
49          * the memory is freed, and so allows for the possibility of
50          * detecting reference counting errors.
51          */
52         char pad[ offsetof ( struct refcnt, count ) +
53                   sizeof ( ( ( struct refcnt * ) NULL )->count ) ];
54         /** List of free blocks */
55         struct list_head list;
56 };
57
58 #define MIN_MEMBLOCK_SIZE \
59         ( ( size_t ) ( 1 << ( fls ( sizeof ( struct memory_block ) - 1 ) ) ) )
60
61 /** A block of allocated memory complete with size information */
62 struct autosized_block {
63         /** Size of this block */
64         size_t size;
65         /** Remaining data */
66         char data[0];
67 };
68
69 /**
70  * Address for zero-length memory blocks
71  *
72  * @c malloc(0) or @c realloc(ptr,0) will return the special value @c
73  * NOWHERE.  Calling @c free(NOWHERE) will have no effect.
74  *
75  * This is consistent with the ANSI C standards, which state that
76  * "either NULL or a pointer suitable to be passed to free()" must be
77  * returned in these cases.  Using a special non-NULL value means that
78  * the caller can take a NULL return value to indicate failure,
79  * without first having to check for a requested size of zero.
80  *
81  * Code outside of malloc.c do not ever need to refer to the actual
82  * value of @c NOWHERE; this is an internal definition.
83  */
84 #define NOWHERE ( ( void * ) ~( ( intptr_t ) 0 ) )
85
86 /** List of free memory blocks */
87 static LIST_HEAD ( free_blocks );
88
89 /** Total amount of free memory */
90 size_t freemem;
91
92 /**
93  * Heap size
94  *
95  * Currently fixed at 512kB.
96  */
97 #define HEAP_SIZE ( 512 * 1024 )
98
99 /** The heap itself */
100 static char heap[HEAP_SIZE] __attribute__ (( aligned ( __alignof__(void *) )));
101
102 /**
103  * Mark all blocks in free list as defined
104  *
105  */
106 static inline void valgrind_make_blocks_defined ( void ) {
107         struct memory_block *block;
108
109         if ( RUNNING_ON_VALGRIND <= 0 )
110                 return;
111
112         /* Traverse free block list, marking each block structure as
113          * defined.  Some contortions are necessary to avoid errors
114          * from list_check().
115          */
116
117         /* Mark block list itself as defined */
118         VALGRIND_MAKE_MEM_DEFINED ( &free_blocks, sizeof ( free_blocks ) );
119
120         /* Mark areas accessed by list_check() as defined */
121         VALGRIND_MAKE_MEM_DEFINED ( &free_blocks.prev->next,
122                                     sizeof ( free_blocks.prev->next ) );
123         VALGRIND_MAKE_MEM_DEFINED ( free_blocks.next,
124                                     sizeof ( *free_blocks.next ) );
125         VALGRIND_MAKE_MEM_DEFINED ( &free_blocks.next->next->prev,
126                                     sizeof ( free_blocks.next->next->prev ) );
127
128         /* Mark each block in list as defined */
129         list_for_each_entry ( block, &free_blocks, list ) {
130
131                 /* Mark block as defined */
132                 VALGRIND_MAKE_MEM_DEFINED ( block, sizeof ( *block ) );
133
134                 /* Mark areas accessed by list_check() as defined */
135                 VALGRIND_MAKE_MEM_DEFINED ( block->list.next,
136                                             sizeof ( *block->list.next ) );
137                 VALGRIND_MAKE_MEM_DEFINED ( &block->list.next->next->prev,
138                                       sizeof ( block->list.next->next->prev ) );
139         }
140 }
141
142 /**
143  * Mark all blocks in free list as inaccessible
144  *
145  */
146 static inline void valgrind_make_blocks_noaccess ( void ) {
147         struct memory_block *block;
148         struct memory_block *prev = NULL;
149
150         if ( RUNNING_ON_VALGRIND <= 0 )
151                 return;
152
153         /* Traverse free block list, marking each block structure as
154          * inaccessible.  Some contortions are necessary to avoid
155          * errors from list_check().
156          */
157
158         /* Mark each block in list as inaccessible */
159         list_for_each_entry ( block, &free_blocks, list ) {
160
161                 /* Mark previous block (if any) as inaccessible. (Current
162                  * block will be accessed by list_check().)
163                  */
164                 if ( prev )
165                         VALGRIND_MAKE_MEM_NOACCESS ( prev, sizeof ( *prev ) );
166                 prev = block;
167
168                 /* At the end of the list, list_check() will end up
169                  * accessing the first list item.  Temporarily mark
170                  * this area as defined.
171                  */
172                 VALGRIND_MAKE_MEM_DEFINED ( &free_blocks.next->prev,
173                                             sizeof ( free_blocks.next->prev ) );
174         }
175         /* Mark last block (if any) as inaccessible */
176         if ( prev )
177                 VALGRIND_MAKE_MEM_NOACCESS ( prev, sizeof ( *prev ) );
178
179         /* Mark as inaccessible the area that was temporarily marked
180          * as defined to avoid errors from list_check().
181          */
182         VALGRIND_MAKE_MEM_NOACCESS ( &free_blocks.next->prev,
183                                      sizeof ( free_blocks.next->prev ) );
184
185         /* Mark block list itself as inaccessible */
186         VALGRIND_MAKE_MEM_NOACCESS ( &free_blocks, sizeof ( free_blocks ) );
187 }
188
189 /**
190  * Check integrity of the blocks in the free list
191  *
192  */
193 static inline void check_blocks ( void ) {
194         struct memory_block *block;
195         struct memory_block *prev = NULL;
196
197         if ( ! ASSERTING )
198                 return;
199
200         list_for_each_entry ( block, &free_blocks, list ) {
201
202                 /* Check that list structure is intact */
203                 list_check ( &block->list );
204
205                 /* Check that block size is not too small */
206                 assert ( block->size >= sizeof ( *block ) );
207                 assert ( block->size >= MIN_MEMBLOCK_SIZE );
208
209                 /* Check that block does not wrap beyond end of address space */
210                 assert ( ( ( void * ) block + block->size ) >
211                          ( ( void * ) block ) );
212
213                 /* Check that blocks remain in ascending order, and
214                  * that adjacent blocks have been merged.
215                  */
216                 if ( prev ) {
217                         assert ( ( ( void * ) block ) > ( ( void * ) prev ) );
218                         assert ( ( ( void * ) block ) >
219                                  ( ( ( void * ) prev ) + prev->size ) );
220                 }
221                 prev = block;
222         }
223 }
224
225 /**
226  * Discard some cached data
227  *
228  * @ret discarded       Number of cached items discarded
229  */
230 static unsigned int discard_cache ( void ) {
231         struct cache_discarder *discarder;
232         unsigned int discarded;
233
234         for_each_table_entry ( discarder, CACHE_DISCARDERS ) {
235                 discarded = discarder->discard();
236                 if ( discarded )
237                         return discarded;
238         }
239         return 0;
240 }
241
242 /**
243  * Discard all cached data
244  *
245  */
246 static void discard_all_cache ( void ) {
247         unsigned int discarded;
248
249         do {
250                 discarded = discard_cache();
251         } while ( discarded );
252 }
253
254 /**
255  * Allocate a memory block
256  *
257  * @v size              Requested size
258  * @v align             Physical alignment
259  * @v offset            Offset from physical alignment
260  * @ret ptr             Memory block, or NULL
261  *
262  * Allocates a memory block @b physically aligned as requested.  No
263  * guarantees are provided for the alignment of the virtual address.
264  *
265  * @c align must be a power of two.  @c size may not be zero.
266  */
267 void * alloc_memblock ( size_t size, size_t align, size_t offset ) {
268         struct memory_block *block;
269         size_t align_mask;
270         size_t pre_size;
271         ssize_t post_size;
272         struct memory_block *pre;
273         struct memory_block *post;
274         struct memory_block *ptr;
275
276         /* Sanity checks */
277         assert ( size != 0 );
278         assert ( ( align == 0 ) || ( ( align & ( align - 1 ) ) == 0 ) );
279
280         valgrind_make_blocks_defined();
281         check_blocks();
282
283         /* Round up size to multiple of MIN_MEMBLOCK_SIZE and
284          * calculate alignment mask.
285          */
286         size = ( size + MIN_MEMBLOCK_SIZE - 1 ) & ~( MIN_MEMBLOCK_SIZE - 1 );
287         align_mask = ( align - 1 ) | ( MIN_MEMBLOCK_SIZE - 1 );
288
289         DBGC2 ( &heap, "Allocating %#zx (aligned %#zx+%zx)\n",
290                 size, align, offset );
291         while ( 1 ) {
292                 /* Search through blocks for the first one with enough space */
293                 list_for_each_entry ( block, &free_blocks, list ) {
294                         pre_size = ( ( offset - virt_to_phys ( block ) )
295                                      & align_mask );
296                         post_size = ( block->size - pre_size - size );
297                         if ( post_size >= 0 ) {
298                                 /* Split block into pre-block, block, and
299                                  * post-block.  After this split, the "pre"
300                                  * block is the one currently linked into the
301                                  * free list.
302                                  */
303                                 pre   = block;
304                                 block = ( ( ( void * ) pre   ) + pre_size );
305                                 post  = ( ( ( void * ) block ) + size     );
306                                 DBGC2 ( &heap, "[%p,%p) -> [%p,%p) + [%p,%p)\n",
307                                         pre, ( ( ( void * ) pre ) + pre->size ),
308                                         pre, block, post,
309                                         ( ( ( void * ) pre ) + pre->size ) );
310                                 /* If there is a "post" block, add it in to
311                                  * the free list.  Leak it if it is too small
312                                  * (which can happen only at the very end of
313                                  * the heap).
314                                  */
315                                 if ( (size_t) post_size >= MIN_MEMBLOCK_SIZE ) {
316                                         VALGRIND_MAKE_MEM_DEFINED ( post,
317                                                              sizeof ( *post ) );
318                                         post->size = post_size;
319                                         list_add ( &post->list, &pre->list );
320                                 }
321                                 /* Shrink "pre" block, leaving the main block
322                                  * isolated and no longer part of the free
323                                  * list.
324                                  */
325                                 pre->size = pre_size;
326                                 /* If there is no "pre" block, remove it from
327                                  * the list.  Also remove it (i.e. leak it) if
328                                  * it is too small, which can happen only at
329                                  * the very start of the heap.
330                                  */
331                                 if ( pre_size < MIN_MEMBLOCK_SIZE )
332                                         list_del ( &pre->list );
333                                 /* Update total free memory */
334                                 freemem -= size;
335                                 /* Return allocated block */
336                                 DBGC2 ( &heap, "Allocated [%p,%p)\n", block,
337                                         ( ( ( void * ) block ) + size ) );
338                                 ptr = block;
339                                 goto done;
340                         }
341                 }
342
343                 /* Try discarding some cached data to free up memory */
344                 if ( ! discard_cache() ) {
345                         /* Nothing available to discard */
346                         DBGC ( &heap, "Failed to allocate %#zx (aligned "
347                                "%#zx)\n", size, align );
348                         ptr = NULL;
349                         goto done;
350                 }
351         }
352
353  done:
354         check_blocks();
355         valgrind_make_blocks_noaccess();
356         return ptr;
357 }
358
359 /**
360  * Free a memory block
361  *
362  * @v ptr               Memory allocated by alloc_memblock(), or NULL
363  * @v size              Size of the memory
364  *
365  * If @c ptr is NULL, no action is taken.
366  */
367 void free_memblock ( void *ptr, size_t size ) {
368         struct memory_block *freeing;
369         struct memory_block *block;
370         struct memory_block *tmp;
371         ssize_t gap_before;
372         ssize_t gap_after = -1;
373
374         /* Allow for ptr==NULL */
375         if ( ! ptr )
376                 return;
377
378         valgrind_make_blocks_defined();
379         check_blocks();
380
381         /* Round up size to match actual size that alloc_memblock()
382          * would have used.
383          */
384         assert ( size != 0 );
385         size = ( size + MIN_MEMBLOCK_SIZE - 1 ) & ~( MIN_MEMBLOCK_SIZE - 1 );
386         freeing = ptr;
387         VALGRIND_MAKE_MEM_DEFINED ( freeing, sizeof ( *freeing ) );
388         DBGC2 ( &heap, "Freeing [%p,%p)\n",
389                 freeing, ( ( ( void * ) freeing ) + size ) );
390
391         /* Check that this block does not overlap the free list */
392         if ( ASSERTING ) {
393                 list_for_each_entry ( block, &free_blocks, list ) {
394                         if ( ( ( ( void * ) block ) <
395                                ( ( void * ) freeing + size ) ) &&
396                              ( ( void * ) freeing <
397                                ( ( void * ) block + block->size ) ) ) {
398                                 assert ( 0 );
399                                 DBGC ( &heap, "Double free of [%p,%p) "
400                                        "overlapping [%p,%p) detected from %p\n",
401                                        freeing,
402                                        ( ( ( void * ) freeing ) + size ), block,
403                                        ( ( void * ) block + block->size ),
404                                        __builtin_return_address ( 0 ) );
405                         }
406                 }
407         }
408
409         /* Insert/merge into free list */
410         freeing->size = size;
411         list_for_each_entry_safe ( block, tmp, &free_blocks, list ) {
412                 /* Calculate gaps before and after the "freeing" block */
413                 gap_before = ( ( ( void * ) freeing ) - 
414                                ( ( ( void * ) block ) + block->size ) );
415                 gap_after = ( ( ( void * ) block ) - 
416                               ( ( ( void * ) freeing ) + freeing->size ) );
417                 /* Merge with immediately preceding block, if possible */
418                 if ( gap_before == 0 ) {
419                         DBGC2 ( &heap, "[%p,%p) + [%p,%p) -> [%p,%p)\n", block,
420                                 ( ( ( void * ) block ) + block->size ), freeing,
421                                 ( ( ( void * ) freeing ) + freeing->size ),
422                                 block,
423                                 ( ( ( void * ) freeing ) + freeing->size ) );
424                         block->size += size;
425                         list_del ( &block->list );
426                         freeing = block;
427                 }
428                 /* Stop processing as soon as we reach a following block */
429                 if ( gap_after >= 0 )
430                         break;
431         }
432
433         /* Insert before the immediately following block.  If
434          * possible, merge the following block into the "freeing"
435          * block.
436          */
437         DBGC2 ( &heap, "[%p,%p)\n",
438                 freeing, ( ( ( void * ) freeing ) + freeing->size ) );
439         list_add_tail ( &freeing->list, &block->list );
440         if ( gap_after == 0 ) {
441                 DBGC2 ( &heap, "[%p,%p) + [%p,%p) -> [%p,%p)\n", freeing,
442                         ( ( ( void * ) freeing ) + freeing->size ), block,
443                         ( ( ( void * ) block ) + block->size ), freeing,
444                         ( ( ( void * ) block ) + block->size ) );
445                 freeing->size += block->size;
446                 list_del ( &block->list );
447         }
448
449         /* Update free memory counter */
450         freemem += size;
451
452         check_blocks();
453         valgrind_make_blocks_noaccess();
454 }
455
456 /**
457  * Reallocate memory
458  *
459  * @v old_ptr           Memory previously allocated by malloc(), or NULL
460  * @v new_size          Requested size
461  * @ret new_ptr         Allocated memory, or NULL
462  *
463  * Allocates memory with no particular alignment requirement.  @c
464  * new_ptr will be aligned to at least a multiple of sizeof(void*).
465  * If @c old_ptr is non-NULL, then the contents of the newly allocated
466  * memory will be the same as the contents of the previously allocated
467  * memory, up to the minimum of the old and new sizes.  The old memory
468  * will be freed.
469  *
470  * If allocation fails the previously allocated block is left
471  * untouched and NULL is returned.
472  *
473  * Calling realloc() with a new size of zero is a valid way to free a
474  * memory block.
475  */
476 void * realloc ( void *old_ptr, size_t new_size ) {
477         struct autosized_block *old_block;
478         struct autosized_block *new_block;
479         size_t old_total_size;
480         size_t new_total_size;
481         size_t old_size;
482         void *new_ptr = NOWHERE;
483
484         /* Allocate new memory if necessary.  If allocation fails,
485          * return without touching the old block.
486          */
487         if ( new_size ) {
488                 new_total_size = ( new_size +
489                                    offsetof ( struct autosized_block, data ) );
490                 new_block = alloc_memblock ( new_total_size, 1, 0 );
491                 if ( ! new_block )
492                         return NULL;
493                 VALGRIND_MAKE_MEM_UNDEFINED ( new_block, offsetof ( struct autosized_block, data ) );
494                 new_block->size = new_total_size;
495                 VALGRIND_MAKE_MEM_NOACCESS ( new_block, offsetof ( struct autosized_block, data ) );
496                 new_ptr = &new_block->data;
497                 VALGRIND_MALLOCLIKE_BLOCK ( new_ptr, new_size, 0, 0 );
498         }
499         
500         /* Copy across relevant part of the old data region (if any),
501          * then free it.  Note that at this point either (a) new_ptr
502          * is valid, or (b) new_size is 0; either way, the memcpy() is
503          * valid.
504          */
505         if ( old_ptr && ( old_ptr != NOWHERE ) ) {
506                 old_block = container_of ( old_ptr, struct autosized_block,
507                                            data );
508                 VALGRIND_MAKE_MEM_DEFINED ( old_block, offsetof ( struct autosized_block, data ) );
509                 old_total_size = old_block->size;
510                 assert ( old_total_size != 0 );
511                 old_size = ( old_total_size -
512                              offsetof ( struct autosized_block, data ) );
513                 memcpy ( new_ptr, old_ptr,
514                          ( ( old_size < new_size ) ? old_size : new_size ) );
515                 free_memblock ( old_block, old_total_size );
516                 VALGRIND_MAKE_MEM_NOACCESS ( old_block, offsetof ( struct autosized_block, data ) );
517                 VALGRIND_FREELIKE_BLOCK ( old_ptr, 0 );
518         }
519
520         if ( ASSERTED ) {
521                 DBGC ( &heap, "Possible memory corruption detected from %p\n",
522                        __builtin_return_address ( 0 ) );
523         }
524         return new_ptr;
525 }
526
527 /**
528  * Allocate memory
529  *
530  * @v size              Requested size
531  * @ret ptr             Memory, or NULL
532  *
533  * Allocates memory with no particular alignment requirement.  @c ptr
534  * will be aligned to at least a multiple of sizeof(void*).
535  */
536 void * malloc ( size_t size ) {
537         void *ptr;
538
539         ptr = realloc ( NULL, size );
540         if ( ASSERTED ) {
541                 DBGC ( &heap, "Possible memory corruption detected from %p\n",
542                        __builtin_return_address ( 0 ) );
543         }
544         return ptr;
545 }
546
547 /**
548  * Free memory
549  *
550  * @v ptr               Memory allocated by malloc(), or NULL
551  *
552  * Memory allocated with malloc_dma() cannot be freed with free(); it
553  * must be freed with free_dma() instead.
554  *
555  * If @c ptr is NULL, no action is taken.
556  */
557 void free ( void *ptr ) {
558
559         realloc ( ptr, 0 );
560         if ( ASSERTED ) {
561                 DBGC ( &heap, "Possible memory corruption detected from %p\n",
562                        __builtin_return_address ( 0 ) );
563         }
564 }
565
566 /**
567  * Allocate cleared memory
568  *
569  * @v size              Requested size
570  * @ret ptr             Allocated memory
571  *
572  * Allocate memory as per malloc(), and zero it.
573  *
574  * This function name is non-standard, but pretty intuitive.
575  * zalloc(size) is always equivalent to calloc(1,size)
576  */
577 void * zalloc ( size_t size ) {
578         void *data;
579
580         data = malloc ( size );
581         if ( data )
582                 memset ( data, 0, size );
583         if ( ASSERTED ) {
584                 DBGC ( &heap, "Possible memory corruption detected from %p\n",
585                        __builtin_return_address ( 0 ) );
586         }
587         return data;
588 }
589
590 /**
591  * Add memory to allocation pool
592  *
593  * @v start             Start address
594  * @v end               End address
595  *
596  * Adds a block of memory [start,end) to the allocation pool.  This is
597  * a one-way operation; there is no way to reclaim this memory.
598  *
599  * @c start must be aligned to at least a multiple of sizeof(void*).
600  */
601 void mpopulate ( void *start, size_t len ) {
602         /* Prevent free_memblock() from rounding up len beyond the end
603          * of what we were actually given...
604          */
605         free_memblock ( start, ( len & ~( MIN_MEMBLOCK_SIZE - 1 ) ) );
606 }
607
608 /**
609  * Initialise the heap
610  *
611  */
612 static void init_heap ( void ) {
613         VALGRIND_MAKE_MEM_NOACCESS ( heap, sizeof ( heap ) );
614         mpopulate ( heap, sizeof ( heap ) );
615 }
616
617 /** Memory allocator initialisation function */
618 struct init_fn heap_init_fn __init_fn ( INIT_EARLY ) = {
619         .initialise = init_heap,
620 };
621
622 /**
623  * Discard all cached data on shutdown
624  *
625  */
626 static void shutdown_cache ( int booting __unused ) {
627         discard_all_cache();
628 }
629
630 /** Memory allocator shutdown function */
631 struct startup_fn heap_startup_fn __startup_fn ( STARTUP_EARLY ) = {
632         .shutdown = shutdown_cache,
633 };
634
635 #if 0
636 #include <stdio.h>
637 /**
638  * Dump free block list
639  *
640  */
641 void mdumpfree ( void ) {
642         struct memory_block *block;
643
644         printf ( "Free block list:\n" );
645         list_for_each_entry ( block, &free_blocks, list ) {
646                 printf ( "[%p,%p] (size %#zx)\n", block,
647                          ( ( ( void * ) block ) + block->size ), block->size );
648         }
649 }
650 #endif