Magnificent7 / Hackathon
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers lwip_mem.c Source File

lwip_mem.c

Go to the documentation of this file.
00001 /**
00002  * @file
00003  * Dynamic memory manager
00004  *
00005  * This is a lightweight replacement for the standard C library malloc().
00006  *
00007  * If you want to use the standard C library malloc() instead, define
00008  * MEM_LIBC_MALLOC to 1 in your lwipopts.h
00009  *
00010  * To let mem_malloc() use pools (prevents fragmentation and is much faster than
00011  * a heap but might waste some memory), define MEM_USE_POOLS to 1, define
00012  * MEM_USE_CUSTOM_POOLS to 1 and create a file "lwippools.h" that includes a list
00013  * of pools like this (more pools can be added between _START and _END):
00014  *
00015  * Define three pools with sizes 256, 512, and 1512 bytes
00016  * LWIP_MALLOC_MEMPOOL_START
00017  * LWIP_MALLOC_MEMPOOL(20, 256)
00018  * LWIP_MALLOC_MEMPOOL(10, 512)
00019  * LWIP_MALLOC_MEMPOOL(5, 1512)
00020  * LWIP_MALLOC_MEMPOOL_END
00021  */
00022 
00023 /*
00024  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
00025  * All rights reserved.
00026  *
00027  * Redistribution and use in source and binary forms, with or without modification,
00028  * are permitted provided that the following conditions are met:
00029  *
00030  * 1. Redistributions of source code must retain the above copyright notice,
00031  *    this list of conditions and the following disclaimer.
00032  * 2. Redistributions in binary form must reproduce the above copyright notice,
00033  *    this list of conditions and the following disclaimer in the documentation
00034  *    and/or other materials provided with the distribution.
00035  * 3. The name of the author may not be used to endorse or promote products
00036  *    derived from this software without specific prior written permission.
00037  *
00038  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
00039  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
00040  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
00041  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00042  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
00043  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00044  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
00045  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
00046  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
00047  * OF SUCH DAMAGE.
00048  *
00049  * This file is part of the lwIP TCP/IP stack.
00050  *
00051  * Author: Adam Dunkels <adam@sics.se>
00052  *         Simon Goldschmidt
00053  *
00054  */
00055 
00056 #include "lwip/opt.h"
00057 
00058 #if !MEM_LIBC_MALLOC /* don't build if not configured for use in lwipopts.h */
00059 
00060 #include "lwip/def.h"
00061 #include "lwip/mem.h"
00062 #include "lwip/sys.h"
00063 #include "lwip/stats.h"
00064 #include "lwip/err.h"
00065 
00066 #include <string.h>
00067 
00068 #if MEM_USE_POOLS
00069 /* lwIP head implemented with different sized pools */
00070 
00071 /**
00072  * Allocate memory: determine the smallest pool that is big enough
00073  * to contain an element of 'size' and get an element from that pool.
00074  *
00075  * @param size the size in bytes of the memory needed
00076  * @return a pointer to the allocated memory or NULL if the pool is empty
00077  */
00078 void *
00079 mem_malloc(mem_size_t size)
00080 {
00081   struct memp_malloc_helper *element;
00082   memp_t poolnr;
00083   mem_size_t required_size = size + sizeof(struct memp_malloc_helper);
00084 
00085   for (poolnr = MEMP_POOL_FIRST; poolnr <= MEMP_POOL_LAST; poolnr = (memp_t)(poolnr + 1)) {
00086 #if MEM_USE_POOLS_TRY_BIGGER_POOL
00087 again:
00088 #endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */
00089     /* is this pool big enough to hold an element of the required size
00090        plus a struct memp_malloc_helper that saves the pool this element came from? */
00091     if (required_size <= memp_sizes[poolnr]) {
00092       break;
00093     }
00094   }
00095   if (poolnr > MEMP_POOL_LAST) {
00096     LWIP_ASSERT("mem_malloc(): no pool is that big!", 0);
00097     return NULL;
00098   }
00099   element = (struct memp_malloc_helper*)memp_malloc(poolnr);
00100   if (element == NULL) {
00101     /* No need to DEBUGF or ASSERT: This error is already
00102        taken care of in memp.c */
00103 #if MEM_USE_POOLS_TRY_BIGGER_POOL
00104     /** Try a bigger pool if this one is empty! */
00105     if (poolnr < MEMP_POOL_LAST) {
00106       poolnr++;
00107       goto again;
00108     }
00109 #endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */
00110     return NULL;
00111   }
00112 
00113   /* save the pool number this element came from */
00114   element->poolnr = poolnr;
00115   /* and return a pointer to the memory directly after the struct memp_malloc_helper */
00116   element++;
00117 
00118   return element;
00119 }
00120 
00121 /**
00122  * Free memory previously allocated by mem_malloc. Loads the pool number
00123  * and calls memp_free with that pool number to put the element back into
00124  * its pool
00125  *
00126  * @param rmem the memory element to free
00127  */
00128 void
00129 mem_free(void *rmem)
00130 {
00131   struct memp_malloc_helper *hmem = (struct memp_malloc_helper*)rmem;
00132 
00133   LWIP_ASSERT("rmem != NULL", (rmem != NULL));
00134   LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem)));
00135 
00136   /* get the original struct memp_malloc_helper */
00137   hmem--;
00138 
00139   LWIP_ASSERT("hmem != NULL", (hmem != NULL));
00140   LWIP_ASSERT("hmem == MEM_ALIGN(hmem)", (hmem == LWIP_MEM_ALIGN(hmem)));
00141   LWIP_ASSERT("hmem->poolnr < MEMP_MAX", (hmem->poolnr < MEMP_MAX));
00142 
00143   /* and put it in the pool we saved earlier */
00144   memp_free(hmem->poolnr, hmem);
00145 }
00146 
00147 #else /* MEM_USE_POOLS */
00148 /* lwIP replacement for your libc malloc() */
00149 
00150 /**
00151  * The heap is made up as a list of structs of this type.
00152  * This does not have to be aligned since for getting its size,
00153  * we only use the macro SIZEOF_STRUCT_MEM, which automatically alignes.
00154  */
00155 struct mem {
00156   /** index (-> ram[next]) of the next struct */
00157   mem_size_t next;
00158   /** index (-> ram[prev]) of the previous struct */
00159   mem_size_t prev;
00160   /** 1: this area is used; 0: this area is unused */
00161   u8_t used;
00162 };
00163 
00164 /** All allocated blocks will be MIN_SIZE bytes big, at least!
00165  * MIN_SIZE can be overridden to suit your needs. Smaller values save space,
00166  * larger values could prevent too small blocks to fragment the RAM too much. */
00167 #ifndef MIN_SIZE
00168 #define MIN_SIZE             12
00169 #endif /* MIN_SIZE */
00170 /* some alignment macros: we define them here for better source code layout */
00171 #define MIN_SIZE_ALIGNED     LWIP_MEM_ALIGN_SIZE(MIN_SIZE)
00172 #define SIZEOF_STRUCT_MEM    LWIP_MEM_ALIGN_SIZE(sizeof(struct mem))
00173 #define MEM_SIZE_ALIGNED     LWIP_MEM_ALIGN_SIZE(MEM_SIZE)
00174 
00175 /** If you want to relocate the heap to external memory, simply define
00176  * LWIP_RAM_HEAP_POINTER as a void-pointer to that location.
00177  * If so, make sure the memory at that location is big enough (see below on
00178  * how that space is calculated). */
00179 #ifndef LWIP_RAM_HEAP_POINTER
00180 
00181 #if defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM)
00182 #  if defined (__ICCARM__)
00183 #     define ETHMEM_SECTION
00184 #  elif defined(TOOLCHAIN_GCC_CR)
00185 #     define ETHMEM_SECTION __attribute__((section(".data.$RamPeriph32")))
00186 #  else
00187 #     define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned))
00188 #  endif
00189 #elif defined(TARGET_LPC1768)
00190 #  if defined (__ICCARM__)
00191 #     define ETHMEM_SECTION
00192 #  elif defined(TOOLCHAIN_GCC_CR)
00193 #     define ETHMEM_SECTION __attribute__((section(".data.$RamPeriph32")))
00194 #  else
00195 #     define ETHMEM_SECTION __attribute__((section("AHBSRAM0"),aligned))
00196 #  endif
00197 #else
00198 #define ETHMEM_SECTION
00199 #endif
00200 
00201 /** the heap. we need one struct mem at the end and some room for alignment */
00202 #if defined (__ICCARM__)
00203 #pragma location = ".ethusbram"
00204 #endif
00205 u8_t ram_heap[MEM_SIZE_ALIGNED + (2*SIZEOF_STRUCT_MEM) + MEM_ALIGNMENT] ETHMEM_SECTION;
00206 #define LWIP_RAM_HEAP_POINTER ram_heap
00207 #endif /* LWIP_RAM_HEAP_POINTER */
00208 
00209 /** pointer to the heap (ram_heap): for alignment, ram is now a pointer instead of an array */
00210 static u8_t *ram;
00211 /** the last entry, always unused! */
00212 static struct mem *ram_end;
00213 /** pointer to the lowest free block, this is used for faster search */
00214 static struct mem *lfree;
00215 
00216 /** concurrent access protection */
00217 static sys_mutex_t mem_mutex;
00218 
00219 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00220 
00221 static volatile u8_t mem_free_count;
00222 
00223 /* Allow mem_free from other (e.g. interrupt) context */
00224 #define LWIP_MEM_FREE_DECL_PROTECT()  SYS_ARCH_DECL_PROTECT(lev_free)
00225 #define LWIP_MEM_FREE_PROTECT()       SYS_ARCH_PROTECT(lev_free)
00226 #define LWIP_MEM_FREE_UNPROTECT()     SYS_ARCH_UNPROTECT(lev_free)
00227 #define LWIP_MEM_ALLOC_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_alloc)
00228 #define LWIP_MEM_ALLOC_PROTECT()      SYS_ARCH_PROTECT(lev_alloc)
00229 #define LWIP_MEM_ALLOC_UNPROTECT()    SYS_ARCH_UNPROTECT(lev_alloc)
00230 
00231 #else /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00232 
00233 /* Protect the heap only by using a semaphore */
00234 #define LWIP_MEM_FREE_DECL_PROTECT()
00235 #define LWIP_MEM_FREE_PROTECT()    sys_mutex_lock(&mem_mutex)
00236 #define LWIP_MEM_FREE_UNPROTECT()  sys_mutex_unlock(&mem_mutex)
00237 /* mem_malloc is protected using semaphore AND LWIP_MEM_ALLOC_PROTECT */
00238 #define LWIP_MEM_ALLOC_DECL_PROTECT()
00239 #define LWIP_MEM_ALLOC_PROTECT()
00240 #define LWIP_MEM_ALLOC_UNPROTECT()
00241 
00242 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00243 
00244 
00245 /**
00246  * "Plug holes" by combining adjacent empty struct mems.
00247  * After this function is through, there should not exist
00248  * one empty struct mem pointing to another empty struct mem.
00249  *
00250  * @param mem this points to a struct mem which just has been freed
00251  * @internal this function is only called by mem_free() and mem_trim()
00252  *
00253  * This assumes access to the heap is protected by the calling function
00254  * already.
00255  */
00256 static void
00257 plug_holes(struct mem *mem)
00258 {
00259   struct mem *nmem;
00260   struct mem *pmem;
00261 
00262   LWIP_ASSERT("plug_holes: mem >= ram", (u8_t *)mem >= ram);
00263   LWIP_ASSERT("plug_holes: mem < ram_end", (u8_t *)mem < (u8_t *)ram_end);
00264   LWIP_ASSERT("plug_holes: mem->used == 0", mem->used == 0);
00265 
00266   /* plug hole forward */
00267   LWIP_ASSERT("plug_holes: mem->next <= MEM_SIZE_ALIGNED", mem->next <= MEM_SIZE_ALIGNED);
00268 
00269   nmem = (struct mem *)(void *)&ram[mem->next];
00270   if (mem != nmem && nmem->used == 0 && (u8_t *)nmem != (u8_t *)ram_end) {
00271     /* if mem->next is unused and not end of ram, combine mem and mem->next */
00272     if (lfree == nmem) {
00273       lfree = mem;
00274     }
00275     mem->next = nmem->next;
00276     ((struct mem *)(void *)&ram[nmem->next])->prev = (mem_size_t)((u8_t *)mem - ram);
00277   }
00278 
00279   /* plug hole backward */
00280   pmem = (struct mem *)(void *)&ram[mem->prev];
00281   if (pmem != mem && pmem->used == 0) {
00282     /* if mem->prev is unused, combine mem and mem->prev */
00283     if (lfree == mem) {
00284       lfree = pmem;
00285     }
00286     pmem->next = mem->next;
00287     ((struct mem *)(void *)&ram[mem->next])->prev = (mem_size_t)((u8_t *)pmem - ram);
00288   }
00289 }
00290 
00291 /**
00292  * Zero the heap and initialize start, end and lowest-free
00293  */
00294 void
00295 mem_init(void)
00296 {
00297   struct mem *mem;
00298 
00299   LWIP_ASSERT("Sanity check alignment",
00300     (SIZEOF_STRUCT_MEM & (MEM_ALIGNMENT-1)) == 0);
00301 
00302   /* align the heap */
00303   ram = (u8_t *)LWIP_MEM_ALIGN(LWIP_RAM_HEAP_POINTER);
00304   /* initialize the start of the heap */
00305   mem = (struct mem *)(void *)ram;
00306   mem->next = MEM_SIZE_ALIGNED;
00307   mem->prev = 0;
00308   mem->used = 0;
00309   /* initialize the end of the heap */
00310   ram_end = (struct mem *)(void *)&ram[MEM_SIZE_ALIGNED];
00311   ram_end->used = 1;
00312   ram_end->next = MEM_SIZE_ALIGNED;
00313   ram_end->prev = MEM_SIZE_ALIGNED;
00314 
00315   /* initialize the lowest-free pointer to the start of the heap */
00316   lfree = (struct mem *)(void *)ram;
00317 
00318   MEM_STATS_AVAIL(avail, MEM_SIZE_ALIGNED);
00319 
00320   if(sys_mutex_new(&mem_mutex) != ERR_OK) {
00321     LWIP_ASSERT("failed to create mem_mutex", 0);
00322   }
00323 }
00324 
00325 /**
00326  * Put a struct mem back on the heap
00327  *
00328  * @param rmem is the data portion of a struct mem as returned by a previous
00329  *             call to mem_malloc()
00330  */
00331 void
00332 mem_free(void *rmem)
00333 {
00334   struct mem *mem;
00335   LWIP_MEM_FREE_DECL_PROTECT();
00336 
00337   if (rmem == NULL) {
00338     LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("mem_free(p == NULL) was called.\n"));
00339     return;
00340   }
00341   LWIP_ASSERT("mem_free: sanity check alignment", (((mem_ptr_t)rmem) & (MEM_ALIGNMENT-1)) == 0);
00342 
00343   LWIP_ASSERT("mem_free: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
00344     (u8_t *)rmem < (u8_t *)ram_end);
00345 
00346   if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
00347     SYS_ARCH_DECL_PROTECT(lev);
00348     LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory\n"));
00349     /* protect mem stats from concurrent access */
00350     SYS_ARCH_PROTECT(lev);
00351     MEM_STATS_INC(illegal);
00352     SYS_ARCH_UNPROTECT(lev);
00353     return;
00354   }
00355   /* protect the heap from concurrent access */
00356   LWIP_MEM_FREE_PROTECT();
00357   /* Get the corresponding struct mem ... */
00358   mem = (struct mem *)(void *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
00359   /* ... which has to be in a used state ... */
00360   LWIP_ASSERT("mem_free: mem->used", mem->used);
00361   /* ... and is now unused. */
00362   mem->used = 0;
00363 
00364   if (mem < lfree) {
00365     /* the newly freed struct is now the lowest */
00366     lfree = mem;
00367   }
00368 
00369   MEM_STATS_DEC_USED(used, mem->next - (mem_size_t)(((u8_t *)mem - ram)));
00370 
00371   /* finally, see if prev or next are free also */
00372   plug_holes(mem);
00373 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00374   mem_free_count = 1;
00375 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00376   LWIP_MEM_FREE_UNPROTECT();
00377 }
00378 
00379 /**
00380  * Shrink memory returned by mem_malloc().
00381  *
00382  * @param rmem pointer to memory allocated by mem_malloc the is to be shrinked
00383  * @param newsize required size after shrinking (needs to be smaller than or
00384  *                equal to the previous size)
00385  * @return for compatibility reasons: is always == rmem, at the moment
00386  *         or NULL if newsize is > old size, in which case rmem is NOT touched
00387  *         or freed!
00388  */
00389 void *
00390 mem_trim(void *rmem, mem_size_t newsize)
00391 {
00392   mem_size_t size;
00393   mem_size_t ptr, ptr2;
00394   struct mem *mem, *mem2;
00395   /* use the FREE_PROTECT here: it protects with sem OR SYS_ARCH_PROTECT */
00396   LWIP_MEM_FREE_DECL_PROTECT();
00397 
00398   /* Expand the size of the allocated memory region so that we can
00399      adjust for alignment. */
00400   newsize = LWIP_MEM_ALIGN_SIZE(newsize);
00401 
00402   if(newsize < MIN_SIZE_ALIGNED) {
00403     /* every data block must be at least MIN_SIZE_ALIGNED long */
00404     newsize = MIN_SIZE_ALIGNED;
00405   }
00406 
00407   if (newsize > MEM_SIZE_ALIGNED) {
00408     return NULL;
00409   }
00410 
00411   LWIP_ASSERT("mem_trim: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
00412    (u8_t *)rmem < (u8_t *)ram_end);
00413 
00414   if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
00415     SYS_ARCH_DECL_PROTECT(lev);
00416     LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_trim: illegal memory\n"));
00417     /* protect mem stats from concurrent access */
00418     SYS_ARCH_PROTECT(lev);
00419     MEM_STATS_INC(illegal);
00420     SYS_ARCH_UNPROTECT(lev);
00421     return rmem;
00422   }
00423   /* Get the corresponding struct mem ... */
00424   mem = (struct mem *)(void *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
00425   /* ... and its offset pointer */
00426   ptr = (mem_size_t)((u8_t *)mem - ram);
00427 
00428   size = mem->next - ptr - SIZEOF_STRUCT_MEM;
00429   LWIP_ASSERT("mem_trim can only shrink memory", newsize <= size);
00430   if (newsize > size) {
00431     /* not supported */
00432     return NULL;
00433   }
00434   if (newsize == size) {
00435     /* No change in size, simply return */
00436     return rmem;
00437   }
00438 
00439   /* protect the heap from concurrent access */
00440   LWIP_MEM_FREE_PROTECT();
00441 
00442   mem2 = (struct mem *)(void *)&ram[mem->next];
00443   if(mem2->used == 0) {
00444     /* The next struct is unused, we can simply move it at little */
00445     mem_size_t next;
00446     /* remember the old next pointer */
00447     next = mem2->next;
00448     /* create new struct mem which is moved directly after the shrinked mem */
00449     ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
00450     if (lfree == mem2) {
00451       lfree = (struct mem *)(void *)&ram[ptr2];
00452     }
00453     mem2 = (struct mem *)(void *)&ram[ptr2];
00454     mem2->used = 0;
00455     /* restore the next pointer */
00456     mem2->next = next;
00457     /* link it back to mem */
00458     mem2->prev = ptr;
00459     /* link mem to it */
00460     mem->next = ptr2;
00461     /* last thing to restore linked list: as we have moved mem2,
00462      * let 'mem2->next->prev' point to mem2 again. but only if mem2->next is not
00463      * the end of the heap */
00464     if (mem2->next != MEM_SIZE_ALIGNED) {
00465       ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
00466     }
00467     MEM_STATS_DEC_USED(used, (size - newsize));
00468     /* no need to plug holes, we've already done that */
00469   } else if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED <= size) {
00470     /* Next struct is used but there's room for another struct mem with
00471      * at least MIN_SIZE_ALIGNED of data.
00472      * Old size ('size') must be big enough to contain at least 'newsize' plus a struct mem
00473      * ('SIZEOF_STRUCT_MEM') with some data ('MIN_SIZE_ALIGNED').
00474      * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
00475      *       region that couldn't hold data, but when mem->next gets freed,
00476      *       the 2 regions would be combined, resulting in more free memory */
00477     ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
00478     mem2 = (struct mem *)(void *)&ram[ptr2];
00479     if (mem2 < lfree) {
00480       lfree = mem2;
00481     }
00482     mem2->used = 0;
00483     mem2->next = mem->next;
00484     mem2->prev = ptr;
00485     mem->next = ptr2;
00486     if (mem2->next != MEM_SIZE_ALIGNED) {
00487       ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
00488     }
00489     MEM_STATS_DEC_USED(used, (size - newsize));
00490     /* the original mem->next is used, so no need to plug holes! */
00491   }
00492   /* else {
00493     next struct mem is used but size between mem and mem2 is not big enough
00494     to create another struct mem
00495     -> don't do anyhting.
00496     -> the remaining space stays unused since it is too small
00497   } */
00498 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00499   mem_free_count = 1;
00500 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00501   LWIP_MEM_FREE_UNPROTECT();
00502   return rmem;
00503 }
00504 
00505 /**
00506  * Adam's mem_malloc() plus solution for bug #17922
00507  * Allocate a block of memory with a minimum of 'size' bytes.
00508  *
00509  * @param size is the minimum size of the requested block in bytes.
00510  * @return pointer to allocated memory or NULL if no free memory was found.
00511  *
00512  * Note that the returned value will always be aligned (as defined by MEM_ALIGNMENT).
00513  */
00514 void *
00515 mem_malloc(mem_size_t size)
00516 {
00517   mem_size_t ptr, ptr2;
00518   struct mem *mem, *mem2;
00519 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00520   u8_t local_mem_free_count = 0;
00521 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00522   LWIP_MEM_ALLOC_DECL_PROTECT();
00523 
00524   if (size == 0) {
00525     return NULL;
00526   }
00527 
00528   /* Expand the size of the allocated memory region so that we can
00529      adjust for alignment. */
00530   size = LWIP_MEM_ALIGN_SIZE(size);
00531 
00532   if(size < MIN_SIZE_ALIGNED) {
00533     /* every data block must be at least MIN_SIZE_ALIGNED long */
00534     size = MIN_SIZE_ALIGNED;
00535   }
00536 
00537   if (size > MEM_SIZE_ALIGNED) {
00538     return NULL;
00539   }
00540 
00541   /* protect the heap from concurrent access */
00542   sys_mutex_lock(&mem_mutex);
00543   LWIP_MEM_ALLOC_PROTECT();
00544 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00545   /* run as long as a mem_free disturbed mem_malloc */
00546   do {
00547     local_mem_free_count = 0;
00548 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00549 
00550     /* Scan through the heap searching for a free block that is big enough,
00551      * beginning with the lowest free block.
00552      */
00553     for (ptr = (mem_size_t)((u8_t *)lfree - ram); ptr < MEM_SIZE_ALIGNED - size;
00554          ptr = ((struct mem *)(void *)&ram[ptr])->next) {
00555       mem = (struct mem *)(void *)&ram[ptr];
00556 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00557       mem_free_count = 0;
00558       LWIP_MEM_ALLOC_UNPROTECT();
00559       /* allow mem_free to run */
00560       LWIP_MEM_ALLOC_PROTECT();
00561       if (mem_free_count != 0) {
00562         local_mem_free_count = mem_free_count;
00563       }
00564       mem_free_count = 0;
00565 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00566 
00567       if ((!mem->used) &&
00568           (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size) {
00569         /* mem is not used and at least perfect fit is possible:
00570          * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */
00571 
00572         if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >= (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)) {
00573           /* (in addition to the above, we test if another struct mem (SIZEOF_STRUCT_MEM) containing
00574            * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
00575            * -> split large block, create empty remainder,
00576            * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if
00577            * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
00578            * struct mem would fit in but no data between mem2 and mem2->next
00579            * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
00580            *       region that couldn't hold data, but when mem->next gets freed,
00581            *       the 2 regions would be combined, resulting in more free memory
00582            */
00583           ptr2 = ptr + SIZEOF_STRUCT_MEM + size;
00584           /* create mem2 struct */
00585           mem2 = (struct mem *)(void *)&ram[ptr2];
00586           mem2->used = 0;
00587           mem2->next = mem->next;
00588           mem2->prev = ptr;
00589           /* and insert it between mem and mem->next */
00590           mem->next = ptr2;
00591           mem->used = 1;
00592 
00593           if (mem2->next != MEM_SIZE_ALIGNED) {
00594             ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
00595           }
00596           MEM_STATS_INC_USED(used, (size + SIZEOF_STRUCT_MEM));
00597         } else {
00598           /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
00599            * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
00600            * take care of this).
00601            * -> near fit or excact fit: do not split, no mem2 creation
00602            * also can't move mem->next directly behind mem, since mem->next
00603            * will always be used at this point!
00604            */
00605           mem->used = 1;
00606           MEM_STATS_INC_USED(used, mem->next - (mem_size_t)((u8_t *)mem - ram));
00607         }
00608 
00609         if (mem == lfree) {
00610           /* Find next free block after mem and update lowest free pointer */
00611           while (lfree->used && lfree != ram_end) {
00612             LWIP_MEM_ALLOC_UNPROTECT();
00613             /* prevent high interrupt latency... */
00614             LWIP_MEM_ALLOC_PROTECT();
00615             lfree = (struct mem *)(void *)&ram[lfree->next];
00616           }
00617           LWIP_ASSERT("mem_malloc: !lfree->used", ((lfree == ram_end) || (!lfree->used)));
00618         }
00619         LWIP_MEM_ALLOC_UNPROTECT();
00620         sys_mutex_unlock(&mem_mutex);
00621         LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.",
00622          (mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end);
00623                 LWIP_ASSERT("mem_malloc: allocated memory properly aligned.",
00624                         ((mem_ptr_t)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0);
00625         LWIP_ASSERT("mem_malloc: sanity check alignment",
00626                         (((mem_ptr_t)mem) & (MEM_ALIGNMENT-1)) == 0);
00627 
00628         return (u8_t *)mem + SIZEOF_STRUCT_MEM;
00629       }
00630     }
00631 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00632     /* if we got interrupted by a mem_free, try again */
00633   } while(local_mem_free_count != 0);
00634 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00635   LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size));
00636   MEM_STATS_INC(err);
00637   LWIP_MEM_ALLOC_UNPROTECT();
00638   sys_mutex_unlock(&mem_mutex);
00639   return NULL;
00640 }
00641 
00642 #endif /* MEM_USE_POOLS */
00643 /**
00644  * Contiguously allocates enough space for count objects that are size bytes
00645  * of memory each and returns a pointer to the allocated memory.
00646  *
00647  * The allocated memory is filled with bytes of value zero.
00648  *
00649  * @param count number of objects to allocate
00650  * @param size size of the objects to allocate
00651  * @return pointer to allocated memory / NULL pointer if there is an error
00652  */
00653 void *mem_calloc(mem_size_t count, mem_size_t size)
00654 {
00655   void *p;
00656 
00657   /* allocate 'count' objects of size 'size' */
00658   p = mem_malloc(count * size);
00659   if (p) {
00660     /* zero the memory */
00661     memset(p, 0, count * size);
00662   }
00663   return p;
00664 }
00665 
00666 #endif /* !MEM_LIBC_MALLOC */