Version of http://mbed.org/cookbook/NetServicesTribute with setting set the same for LPC2368

Dependents:   UDPSocketExample 24LCxx_I2CApp WeatherPlatform_pachube HvZServerLib ... more

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mem.c Source File

mem.c

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