malloc.c

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License as
00006  * published by the Free Software Foundation; either version 2 of the
00007  * License, or any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful, but
00010  * WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  * General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
00017  */
00018 
00019 FILE_LICENCE ( GPL2_OR_LATER );
00020 
00021 #include <stddef.h>
00022 #include <stdint.h>
00023 #include <string.h>
00024 #include <strings.h>
00025 #include <gpxe/io.h>
00026 #include <gpxe/list.h>
00027 #include <gpxe/init.h>
00028 #include <gpxe/malloc.h>
00029 
00030 /** @file
00031  *
00032  * Dynamic memory allocation
00033  *
00034  */
00035 
00036 /** A free block of memory */
00037 struct memory_block {
00038         /** List of free blocks */
00039         struct list_head list;
00040         /** Size of this block */
00041         size_t size;
00042 };
00043 
00044 #define MIN_MEMBLOCK_SIZE \
00045         ( ( size_t ) ( 1 << ( fls ( sizeof ( struct memory_block ) - 1 ) ) ) )
00046 
00047 /** A block of allocated memory complete with size information */
00048 struct autosized_block {
00049         /** Size of this block */
00050         size_t size;
00051         /** Remaining data */
00052         char data[0];
00053 };
00054 
00055 /**
00056  * Address for zero-length memory blocks
00057  *
00058  * @c malloc(0) or @c realloc(ptr,0) will return the special value @c
00059  * NOWHERE.  Calling @c free(NOWHERE) will have no effect.
00060  *
00061  * This is consistent with the ANSI C standards, which state that
00062  * "either NULL or a pointer suitable to be passed to free()" must be
00063  * returned in these cases.  Using a special non-NULL value means that
00064  * the caller can take a NULL return value to indicate failure,
00065  * without first having to check for a requested size of zero.
00066  *
00067  * Code outside of malloc.c do not ever need to refer to the actual
00068  * value of @c NOWHERE; this is an internal definition.
00069  */
00070 #define NOWHERE ( ( void * ) ~( ( intptr_t ) 0 ) )
00071 
00072 /** List of free memory blocks */
00073 static LIST_HEAD ( free_blocks );
00074 
00075 /** Total amount of free memory */
00076 size_t freemem;
00077 
00078 /**
00079  * Heap size
00080  *
00081  * Currently fixed at 128kB.
00082  */
00083 #define HEAP_SIZE ( 128 * 1024 )
00084 
00085 /** The heap itself */
00086 static char heap[HEAP_SIZE] __attribute__ (( aligned ( __alignof__(void *) )));
00087 
00088 /**
00089  * Allocate a memory block
00090  *
00091  * @v size              Requested size
00092  * @v align             Physical alignment
00093  * @ret ptr             Memory block, or NULL
00094  *
00095  * Allocates a memory block @b physically aligned as requested.  No
00096  * guarantees are provided for the alignment of the virtual address.
00097  *
00098  * @c align must be a power of two.  @c size may not be zero.
00099  */
00100 void * alloc_memblock ( size_t size, size_t align ) {
00101         struct memory_block *block;
00102         size_t align_mask;
00103         size_t pre_size;
00104         ssize_t post_size;
00105         struct memory_block *pre;
00106         struct memory_block *post;
00107 
00108         /* Round up size to multiple of MIN_MEMBLOCK_SIZE and
00109          * calculate alignment mask.
00110          */
00111         size = ( size + MIN_MEMBLOCK_SIZE - 1 ) & ~( MIN_MEMBLOCK_SIZE - 1 );
00112         align_mask = ( align - 1 ) | ( MIN_MEMBLOCK_SIZE - 1 );
00113 
00114         DBG ( "Allocating %#zx (aligned %#zx)\n", size, align );
00115 
00116         /* Search through blocks for the first one with enough space */
00117         list_for_each_entry ( block, &free_blocks, list ) {
00118                 pre_size = ( - virt_to_phys ( block ) ) & align_mask;
00119                 post_size = block->size - pre_size - size;
00120                 if ( post_size >= 0 ) {
00121                         /* Split block into pre-block, block, and
00122                          * post-block.  After this split, the "pre"
00123                          * block is the one currently linked into the
00124                          * free list.
00125                          */
00126                         pre   = block;
00127                         block = ( ( ( void * ) pre   ) + pre_size );
00128                         post  = ( ( ( void * ) block ) + size     );
00129                         DBG ( "[%p,%p) -> [%p,%p) + [%p,%p)\n", pre,
00130                               ( ( ( void * ) pre ) + pre->size ), pre, block,
00131                               post, ( ( ( void * ) pre ) + pre->size ) );
00132                         /* If there is a "post" block, add it in to
00133                          * the free list.  Leak it if it is too small
00134                          * (which can happen only at the very end of
00135                          * the heap).
00136                          */
00137                         if ( ( size_t ) post_size >= MIN_MEMBLOCK_SIZE ) {
00138                                 post->size = post_size;
00139                                 list_add ( &post->list, &pre->list );
00140                         }
00141                         /* Shrink "pre" block, leaving the main block
00142                          * isolated and no longer part of the free
00143                          * list.
00144                          */
00145                         pre->size = pre_size;
00146                         /* If there is no "pre" block, remove it from
00147                          * the list.  Also remove it (i.e. leak it) if
00148                          * it is too small, which can happen only at
00149                          * the very start of the heap.
00150                          */
00151                         if ( pre_size < MIN_MEMBLOCK_SIZE )
00152                                 list_del ( &pre->list );
00153                         /* Update total free memory */
00154                         freemem -= size;
00155                         /* Return allocated block */
00156                         DBG ( "Allocated [%p,%p)\n", block,
00157                               ( ( ( void * ) block ) + size ) );
00158                         return block;
00159                 }
00160         }
00161 
00162         DBG ( "Failed to allocate %#zx (aligned %#zx)\n", size, align );
00163         return NULL;
00164 }
00165 
00166 /**
00167  * Free a memory block
00168  *
00169  * @v ptr               Memory allocated by alloc_memblock(), or NULL
00170  * @v size              Size of the memory
00171  *
00172  * If @c ptr is NULL, no action is taken.
00173  */
00174 void free_memblock ( void *ptr, size_t size ) {
00175         struct memory_block *freeing;
00176         struct memory_block *block;
00177         ssize_t gap_before;
00178         ssize_t gap_after = -1;
00179 
00180         /* Allow for ptr==NULL */
00181         if ( ! ptr )
00182                 return;
00183 
00184         /* Round up size to match actual size that alloc_memblock()
00185          * would have used.
00186          */
00187         size = ( size + MIN_MEMBLOCK_SIZE - 1 ) & ~( MIN_MEMBLOCK_SIZE - 1 );
00188         freeing = ptr;
00189         freeing->size = size;
00190         DBG ( "Freeing [%p,%p)\n", freeing, ( ( ( void * ) freeing ) + size ));
00191 
00192         /* Insert/merge into free list */
00193         list_for_each_entry ( block, &free_blocks, list ) {
00194                 /* Calculate gaps before and after the "freeing" block */
00195                 gap_before = ( ( ( void * ) freeing ) - 
00196                                ( ( ( void * ) block ) + block->size ) );
00197                 gap_after = ( ( ( void * ) block ) - 
00198                               ( ( ( void * ) freeing ) + freeing->size ) );
00199                 /* Merge with immediately preceding block, if possible */
00200                 if ( gap_before == 0 ) {
00201                         DBG ( "[%p,%p) + [%p,%p) -> [%p,%p)\n", block,
00202                               ( ( ( void * ) block ) + block->size ), freeing,
00203                               ( ( ( void * ) freeing ) + freeing->size ),block,
00204                               ( ( ( void * ) freeing ) + freeing->size ) );
00205                         block->size += size;
00206                         list_del ( &block->list );
00207                         freeing = block;
00208                 }
00209                 /* Stop processing as soon as we reach a following block */
00210                 if ( gap_after >= 0 )
00211                         break;
00212         }
00213 
00214         /* Insert before the immediately following block.  If
00215          * possible, merge the following block into the "freeing"
00216          * block.
00217          */
00218         DBG ( "[%p,%p)\n", freeing, ( ( ( void * ) freeing ) + freeing->size));
00219         list_add_tail ( &freeing->list, &block->list );
00220         if ( gap_after == 0 ) {
00221                 DBG ( "[%p,%p) + [%p,%p) -> [%p,%p)\n", freeing,
00222                       ( ( ( void * ) freeing ) + freeing->size ), block,
00223                       ( ( ( void * ) block ) + block->size ), freeing,
00224                       ( ( ( void * ) block ) + block->size ) );
00225                 freeing->size += block->size;
00226                 list_del ( &block->list );
00227         }
00228 
00229         /* Update free memory counter */
00230         freemem += size;
00231 }
00232 
00233 /**
00234  * Reallocate memory
00235  *
00236  * @v old_ptr           Memory previously allocated by malloc(), or NULL
00237  * @v new_size          Requested size
00238  * @ret new_ptr         Allocated memory, or NULL
00239  *
00240  * Allocates memory with no particular alignment requirement.  @c
00241  * new_ptr will be aligned to at least a multiple of sizeof(void*).
00242  * If @c old_ptr is non-NULL, then the contents of the newly allocated
00243  * memory will be the same as the contents of the previously allocated
00244  * memory, up to the minimum of the old and new sizes.  The old memory
00245  * will be freed.
00246  *
00247  * If allocation fails the previously allocated block is left
00248  * untouched and NULL is returned.
00249  *
00250  * Calling realloc() with a new size of zero is a valid way to free a
00251  * memory block.
00252  */
00253 void * realloc ( void *old_ptr, size_t new_size ) {
00254         struct autosized_block *old_block;
00255         struct autosized_block *new_block;
00256         size_t old_total_size;
00257         size_t new_total_size;
00258         size_t old_size;
00259         void *new_ptr = NOWHERE;
00260 
00261         /* Allocate new memory if necessary.  If allocation fails,
00262          * return without touching the old block.
00263          */
00264         if ( new_size ) {
00265                 new_total_size = ( new_size +
00266                                    offsetof ( struct autosized_block, data ) );
00267                 new_block = alloc_memblock ( new_total_size, 1 );
00268                 if ( ! new_block )
00269                         return NULL;
00270                 new_block->size = new_total_size;
00271                 new_ptr = &new_block->data;
00272         }
00273         
00274         /* Copy across relevant part of the old data region (if any),
00275          * then free it.  Note that at this point either (a) new_ptr
00276          * is valid, or (b) new_size is 0; either way, the memcpy() is
00277          * valid.
00278          */
00279         if ( old_ptr && ( old_ptr != NOWHERE ) ) {
00280                 old_block = container_of ( old_ptr, struct autosized_block,
00281                                            data );
00282                 old_total_size = old_block->size;
00283                 old_size = ( old_total_size -
00284                              offsetof ( struct autosized_block, data ) );
00285                 memcpy ( new_ptr, old_ptr,
00286                          ( ( old_size < new_size ) ? old_size : new_size ) );
00287                 free_memblock ( old_block, old_total_size );
00288         }
00289 
00290         return new_ptr;
00291 }
00292 
00293 /**
00294  * Allocate memory
00295  *
00296  * @v size              Requested size
00297  * @ret ptr             Memory, or NULL
00298  *
00299  * Allocates memory with no particular alignment requirement.  @c ptr
00300  * will be aligned to at least a multiple of sizeof(void*).
00301  */
00302 void * malloc ( size_t size ) {
00303         return realloc ( NULL, size );
00304 }
00305 
00306 /**
00307  * Free memory
00308  *
00309  * @v ptr               Memory allocated by malloc(), or NULL
00310  *
00311  * Memory allocated with malloc_dma() cannot be freed with free(); it
00312  * must be freed with free_dma() instead.
00313  *
00314  * If @c ptr is NULL, no action is taken.
00315  */
00316 void free ( void *ptr ) {
00317         realloc ( ptr, 0 );
00318 }
00319 
00320 /**
00321  * Allocate cleared memory
00322  *
00323  * @v size              Requested size
00324  * @ret ptr             Allocated memory
00325  *
00326  * Allocate memory as per malloc(), and zero it.
00327  *
00328  * This function name is non-standard, but pretty intuitive.
00329  * zalloc(size) is always equivalent to calloc(1,size)
00330  */
00331 void * zalloc ( size_t size ) {
00332         void *data;
00333 
00334         data = malloc ( size );
00335         if ( data )
00336                 memset ( data, 0, size );
00337         return data;
00338 }
00339 
00340 /**
00341  * Add memory to allocation pool
00342  *
00343  * @v start             Start address
00344  * @v end               End address
00345  *
00346  * Adds a block of memory [start,end) to the allocation pool.  This is
00347  * a one-way operation; there is no way to reclaim this memory.
00348  *
00349  * @c start must be aligned to at least a multiple of sizeof(void*).
00350  */
00351 void mpopulate ( void *start, size_t len ) {
00352         /* Prevent free_memblock() from rounding up len beyond the end
00353          * of what we were actually given...
00354          */
00355         free_memblock ( start, ( len & ~( MIN_MEMBLOCK_SIZE - 1 ) ) );
00356 }
00357 
00358 /**
00359  * Initialise the heap
00360  *
00361  */
00362 static void init_heap ( void ) {
00363         mpopulate ( heap, sizeof ( heap ) );
00364 }
00365 
00366 /** Memory allocator initialisation function */
00367 struct init_fn heap_init_fn __init_fn ( INIT_EARLY ) = {
00368         .initialise = init_heap,
00369 };
00370 
00371 #if 0
00372 #include <stdio.h>
00373 /**
00374  * Dump free block list
00375  *
00376  */
00377 void mdumpfree ( void ) {
00378         struct memory_block *block;
00379 
00380         printf ( "Free block list:\n" );
00381         list_for_each_entry ( block, &free_blocks, list ) {
00382                 printf ( "[%p,%p] (size %#zx)\n", block,
00383                          ( ( ( void * ) block ) + block->size ), block->size );
00384         }
00385 }
00386 #endif

Generated on Tue Apr 6 20:00:51 2010 for gPXE by  doxygen 1.5.7.1