Deprecated fork of old network stack source from github. Please use official library instead: https://mbed.org/users/mbed_official/code/EthernetInterface/

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 /**
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)
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 #else
00190 #   define ETHMEM_SECTION __attribute((section("AHBSRAM0")))
00191 #endif
00192 
00193 /** the heap. we need one struct mem at the end and some room for alignment */
00194 u8_t ram_heap[MEM_SIZE_ALIGNED + (2*SIZEOF_STRUCT_MEM) + MEM_ALIGNMENT] ETHMEM_SECTION;
00195 #define LWIP_RAM_HEAP_POINTER ram_heap
00196 #endif /* LWIP_RAM_HEAP_POINTER */
00197 
00198 /** pointer to the heap (ram_heap): for alignment, ram is now a pointer instead of an array */
00199 static u8_t *ram;
00200 /** the last entry, always unused! */
00201 static struct mem *ram_end;
00202 /** pointer to the lowest free block, this is used for faster search */
00203 static struct mem *lfree;
00204 
00205 /** concurrent access protection */
00206 static sys_mutex_t mem_mutex;
00207 
00208 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00209 
00210 static volatile u8_t mem_free_count;
00211 
00212 /* Allow mem_free from other (e.g. interrupt) context */
00213 #define LWIP_MEM_FREE_DECL_PROTECT()  SYS_ARCH_DECL_PROTECT(lev_free)
00214 #define LWIP_MEM_FREE_PROTECT()       SYS_ARCH_PROTECT(lev_free)
00215 #define LWIP_MEM_FREE_UNPROTECT()     SYS_ARCH_UNPROTECT(lev_free)
00216 #define LWIP_MEM_ALLOC_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_alloc)
00217 #define LWIP_MEM_ALLOC_PROTECT()      SYS_ARCH_PROTECT(lev_alloc)
00218 #define LWIP_MEM_ALLOC_UNPROTECT()    SYS_ARCH_UNPROTECT(lev_alloc)
00219 
00220 #else /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00221 
00222 /* Protect the heap only by using a semaphore */
00223 #define LWIP_MEM_FREE_DECL_PROTECT()
00224 #define LWIP_MEM_FREE_PROTECT()    sys_mutex_lock(&mem_mutex)
00225 #define LWIP_MEM_FREE_UNPROTECT()  sys_mutex_unlock(&mem_mutex)
00226 /* mem_malloc is protected using semaphore AND LWIP_MEM_ALLOC_PROTECT */
00227 #define LWIP_MEM_ALLOC_DECL_PROTECT()
00228 #define LWIP_MEM_ALLOC_PROTECT()
00229 #define LWIP_MEM_ALLOC_UNPROTECT()
00230 
00231 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00232 
00233 
00234 /**
00235  * "Plug holes" by combining adjacent empty struct mems.
00236  * After this function is through, there should not exist
00237  * one empty struct mem pointing to another empty struct mem.
00238  *
00239  * @param mem this points to a struct mem which just has been freed
00240  * @internal this function is only called by mem_free() and mem_trim()
00241  *
00242  * This assumes access to the heap is protected by the calling function
00243  * already.
00244  */
00245 static void
00246 plug_holes(struct mem *mem)
00247 {
00248   struct mem *nmem;
00249   struct mem *pmem;
00250 
00251   LWIP_ASSERT("plug_holes: mem >= ram", (u8_t *)mem >= ram);
00252   LWIP_ASSERT("plug_holes: mem < ram_end", (u8_t *)mem < (u8_t *)ram_end);
00253   LWIP_ASSERT("plug_holes: mem->used == 0", mem->used == 0);
00254 
00255   /* plug hole forward */
00256   LWIP_ASSERT("plug_holes: mem->next <= MEM_SIZE_ALIGNED", mem->next <= MEM_SIZE_ALIGNED);
00257 
00258   nmem = (struct mem *)(void *)&ram[mem->next];
00259   if (mem != nmem && nmem->used == 0 && (u8_t *)nmem != (u8_t *)ram_end) {
00260     /* if mem->next is unused and not end of ram, combine mem and mem->next */
00261     if (lfree == nmem) {
00262       lfree = mem;
00263     }
00264     mem->next = nmem->next;
00265     ((struct mem *)(void *)&ram[nmem->next])->prev = (mem_size_t)((u8_t *)mem - ram);
00266   }
00267 
00268   /* plug hole backward */
00269   pmem = (struct mem *)(void *)&ram[mem->prev];
00270   if (pmem != mem && pmem->used == 0) {
00271     /* if mem->prev is unused, combine mem and mem->prev */
00272     if (lfree == mem) {
00273       lfree = pmem;
00274     }
00275     pmem->next = mem->next;
00276     ((struct mem *)(void *)&ram[mem->next])->prev = (mem_size_t)((u8_t *)pmem - ram);
00277   }
00278 }
00279 
00280 /**
00281  * Zero the heap and initialize start, end and lowest-free
00282  */
00283 void
00284 mem_init(void)
00285 {
00286   struct mem *mem;
00287 
00288   LWIP_ASSERT("Sanity check alignment",
00289     (SIZEOF_STRUCT_MEM & (MEM_ALIGNMENT-1)) == 0);
00290 
00291   /* align the heap */
00292   ram = (u8_t *)LWIP_MEM_ALIGN(LWIP_RAM_HEAP_POINTER);
00293   /* initialize the start of the heap */
00294   mem = (struct mem *)(void *)ram;
00295   mem->next = MEM_SIZE_ALIGNED;
00296   mem->prev = 0;
00297   mem->used = 0;
00298   /* initialize the end of the heap */
00299   ram_end = (struct mem *)(void *)&ram[MEM_SIZE_ALIGNED];
00300   ram_end->used = 1;
00301   ram_end->next = MEM_SIZE_ALIGNED;
00302   ram_end->prev = MEM_SIZE_ALIGNED;
00303 
00304   /* initialize the lowest-free pointer to the start of the heap */
00305   lfree = (struct mem *)(void *)ram;
00306 
00307   MEM_STATS_AVAIL(avail, MEM_SIZE_ALIGNED);
00308 
00309   if(sys_mutex_new(&mem_mutex) != ERR_OK) {
00310     LWIP_ASSERT("failed to create mem_mutex", 0);
00311   }
00312 }
00313 
00314 /**
00315  * Put a struct mem back on the heap
00316  *
00317  * @param rmem is the data portion of a struct mem as returned by a previous
00318  *             call to mem_malloc()
00319  */
00320 void
00321 mem_free(void *rmem)
00322 {
00323   struct mem *mem;
00324   LWIP_MEM_FREE_DECL_PROTECT();
00325 
00326   if (rmem == NULL) {
00327     LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("mem_free(p == NULL) was called.\n"));
00328     return;
00329   }
00330   LWIP_ASSERT("mem_free: sanity check alignment", (((mem_ptr_t)rmem) & (MEM_ALIGNMENT-1)) == 0);
00331 
00332   LWIP_ASSERT("mem_free: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
00333     (u8_t *)rmem < (u8_t *)ram_end);
00334 
00335   if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
00336     SYS_ARCH_DECL_PROTECT(lev);
00337     LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory\n"));
00338     /* protect mem stats from concurrent access */
00339     SYS_ARCH_PROTECT(lev);
00340     MEM_STATS_INC(illegal);
00341     SYS_ARCH_UNPROTECT(lev);
00342     return;
00343   }
00344   /* protect the heap from concurrent access */
00345   LWIP_MEM_FREE_PROTECT();
00346   /* Get the corresponding struct mem ... */
00347   mem = (struct mem *)(void *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
00348   /* ... which has to be in a used state ... */
00349   LWIP_ASSERT("mem_free: mem->used", mem->used);
00350   /* ... and is now unused. */
00351   mem->used = 0;
00352 
00353   if (mem < lfree) {
00354     /* the newly freed struct is now the lowest */
00355     lfree = mem;
00356   }
00357 
00358   MEM_STATS_DEC_USED(used, mem->next - (mem_size_t)(((u8_t *)mem - ram)));
00359 
00360   /* finally, see if prev or next are free also */
00361   plug_holes(mem);
00362 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00363   mem_free_count = 1;
00364 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00365   LWIP_MEM_FREE_UNPROTECT();
00366 }
00367 
00368 /**
00369  * Shrink memory returned by mem_malloc().
00370  *
00371  * @param rmem pointer to memory allocated by mem_malloc the is to be shrinked
00372  * @param newsize required size after shrinking (needs to be smaller than or
00373  *                equal to the previous size)
00374  * @return for compatibility reasons: is always == rmem, at the moment
00375  *         or NULL if newsize is > old size, in which case rmem is NOT touched
00376  *         or freed!
00377  */
00378 void *
00379 mem_trim(void *rmem, mem_size_t newsize)
00380 {
00381   mem_size_t size;
00382   mem_size_t ptr, ptr2;
00383   struct mem *mem, *mem2;
00384   /* use the FREE_PROTECT here: it protects with sem OR SYS_ARCH_PROTECT */
00385   LWIP_MEM_FREE_DECL_PROTECT();
00386 
00387   /* Expand the size of the allocated memory region so that we can
00388      adjust for alignment. */
00389   newsize = LWIP_MEM_ALIGN_SIZE(newsize);
00390 
00391   if(newsize < MIN_SIZE_ALIGNED) {
00392     /* every data block must be at least MIN_SIZE_ALIGNED long */
00393     newsize = MIN_SIZE_ALIGNED;
00394   }
00395 
00396   if (newsize > MEM_SIZE_ALIGNED) {
00397     return NULL;
00398   }
00399 
00400   LWIP_ASSERT("mem_trim: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
00401    (u8_t *)rmem < (u8_t *)ram_end);
00402 
00403   if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
00404     SYS_ARCH_DECL_PROTECT(lev);
00405     LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_trim: illegal memory\n"));
00406     /* protect mem stats from concurrent access */
00407     SYS_ARCH_PROTECT(lev);
00408     MEM_STATS_INC(illegal);
00409     SYS_ARCH_UNPROTECT(lev);
00410     return rmem;
00411   }
00412   /* Get the corresponding struct mem ... */
00413   mem = (struct mem *)(void *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
00414   /* ... and its offset pointer */
00415   ptr = (mem_size_t)((u8_t *)mem - ram);
00416 
00417   size = mem->next - ptr - SIZEOF_STRUCT_MEM;
00418   LWIP_ASSERT("mem_trim can only shrink memory", newsize <= size);
00419   if (newsize > size) {
00420     /* not supported */
00421     return NULL;
00422   }
00423   if (newsize == size) {
00424     /* No change in size, simply return */
00425     return rmem;
00426   }
00427 
00428   /* protect the heap from concurrent access */
00429   LWIP_MEM_FREE_PROTECT();
00430 
00431   mem2 = (struct mem *)(void *)&ram[mem->next];
00432   if(mem2->used == 0) {
00433     /* The next struct is unused, we can simply move it at little */
00434     mem_size_t next;
00435     /* remember the old next pointer */
00436     next = mem2->next;
00437     /* create new struct mem which is moved directly after the shrinked mem */
00438     ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
00439     if (lfree == mem2) {
00440       lfree = (struct mem *)(void *)&ram[ptr2];
00441     }
00442     mem2 = (struct mem *)(void *)&ram[ptr2];
00443     mem2->used = 0;
00444     /* restore the next pointer */
00445     mem2->next = next;
00446     /* link it back to mem */
00447     mem2->prev = ptr;
00448     /* link mem to it */
00449     mem->next = ptr2;
00450     /* last thing to restore linked list: as we have moved mem2,
00451      * let 'mem2->next->prev' point to mem2 again. but only if mem2->next is not
00452      * the end of the heap */
00453     if (mem2->next != MEM_SIZE_ALIGNED) {
00454       ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
00455     }
00456     MEM_STATS_DEC_USED(used, (size - newsize));
00457     /* no need to plug holes, we've already done that */
00458   } else if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED <= size) {
00459     /* Next struct is used but there's room for another struct mem with
00460      * at least MIN_SIZE_ALIGNED of data.
00461      * Old size ('size') must be big enough to contain at least 'newsize' plus a struct mem
00462      * ('SIZEOF_STRUCT_MEM') with some data ('MIN_SIZE_ALIGNED').
00463      * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
00464      *       region that couldn't hold data, but when mem->next gets freed,
00465      *       the 2 regions would be combined, resulting in more free memory */
00466     ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
00467     mem2 = (struct mem *)(void *)&ram[ptr2];
00468     if (mem2 < lfree) {
00469       lfree = mem2;
00470     }
00471     mem2->used = 0;
00472     mem2->next = mem->next;
00473     mem2->prev = ptr;
00474     mem->next = ptr2;
00475     if (mem2->next != MEM_SIZE_ALIGNED) {
00476       ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
00477     }
00478     MEM_STATS_DEC_USED(used, (size - newsize));
00479     /* the original mem->next is used, so no need to plug holes! */
00480   }
00481   /* else {
00482     next struct mem is used but size between mem and mem2 is not big enough
00483     to create another struct mem
00484     -> don't do anyhting. 
00485     -> the remaining space stays unused since it is too small
00486   } */
00487 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00488   mem_free_count = 1;
00489 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00490   LWIP_MEM_FREE_UNPROTECT();
00491   return rmem;
00492 }
00493 
00494 /**
00495  * Adam's mem_malloc() plus solution for bug #17922
00496  * Allocate a block of memory with a minimum of 'size' bytes.
00497  *
00498  * @param size is the minimum size of the requested block in bytes.
00499  * @return pointer to allocated memory or NULL if no free memory was found.
00500  *
00501  * Note that the returned value will always be aligned (as defined by MEM_ALIGNMENT).
00502  */
00503 void *
00504 mem_malloc(mem_size_t size)
00505 {
00506   mem_size_t ptr, ptr2;
00507   struct mem *mem, *mem2;
00508 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00509   u8_t local_mem_free_count = 0;
00510 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00511   LWIP_MEM_ALLOC_DECL_PROTECT();
00512 
00513   if (size == 0) {
00514     return NULL;
00515   }
00516 
00517   /* Expand the size of the allocated memory region so that we can
00518      adjust for alignment. */
00519   size = LWIP_MEM_ALIGN_SIZE(size);
00520 
00521   if(size < MIN_SIZE_ALIGNED) {
00522     /* every data block must be at least MIN_SIZE_ALIGNED long */
00523     size = MIN_SIZE_ALIGNED;
00524   }
00525 
00526   if (size > MEM_SIZE_ALIGNED) {
00527     return NULL;
00528   }
00529 
00530   /* protect the heap from concurrent access */
00531   sys_mutex_lock(&mem_mutex);
00532   LWIP_MEM_ALLOC_PROTECT();
00533 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00534   /* run as long as a mem_free disturbed mem_malloc */
00535   do {
00536     local_mem_free_count = 0;
00537 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00538 
00539     /* Scan through the heap searching for a free block that is big enough,
00540      * beginning with the lowest free block.
00541      */
00542     for (ptr = (mem_size_t)((u8_t *)lfree - ram); ptr < MEM_SIZE_ALIGNED - size;
00543          ptr = ((struct mem *)(void *)&ram[ptr])->next) {
00544       mem = (struct mem *)(void *)&ram[ptr];
00545 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00546       mem_free_count = 0;
00547       LWIP_MEM_ALLOC_UNPROTECT();
00548       /* allow mem_free to run */
00549       LWIP_MEM_ALLOC_PROTECT();
00550       if (mem_free_count != 0) {
00551         local_mem_free_count = mem_free_count;
00552       }
00553       mem_free_count = 0;
00554 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00555 
00556       if ((!mem->used) &&
00557           (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size) {
00558         /* mem is not used and at least perfect fit is possible:
00559          * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */
00560 
00561         if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >= (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)) {
00562           /* (in addition to the above, we test if another struct mem (SIZEOF_STRUCT_MEM) containing
00563            * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
00564            * -> split large block, create empty remainder,
00565            * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if
00566            * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
00567            * struct mem would fit in but no data between mem2 and mem2->next
00568            * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
00569            *       region that couldn't hold data, but when mem->next gets freed,
00570            *       the 2 regions would be combined, resulting in more free memory
00571            */
00572           ptr2 = ptr + SIZEOF_STRUCT_MEM + size;
00573           /* create mem2 struct */
00574           mem2 = (struct mem *)(void *)&ram[ptr2];
00575           mem2->used = 0;
00576           mem2->next = mem->next;
00577           mem2->prev = ptr;
00578           /* and insert it between mem and mem->next */
00579           mem->next = ptr2;
00580           mem->used = 1;
00581 
00582           if (mem2->next != MEM_SIZE_ALIGNED) {
00583             ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
00584           }
00585           MEM_STATS_INC_USED(used, (size + SIZEOF_STRUCT_MEM));
00586         } else {
00587           /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
00588            * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
00589            * take care of this).
00590            * -> near fit or excact fit: do not split, no mem2 creation
00591            * also can't move mem->next directly behind mem, since mem->next
00592            * will always be used at this point!
00593            */
00594           mem->used = 1;
00595           MEM_STATS_INC_USED(used, mem->next - (mem_size_t)((u8_t *)mem - ram));
00596         }
00597 
00598         if (mem == lfree) {
00599           /* Find next free block after mem and update lowest free pointer */
00600           while (lfree->used && lfree != ram_end) {
00601             LWIP_MEM_ALLOC_UNPROTECT();
00602             /* prevent high interrupt latency... */
00603             LWIP_MEM_ALLOC_PROTECT();
00604             lfree = (struct mem *)(void *)&ram[lfree->next];
00605           }
00606           LWIP_ASSERT("mem_malloc: !lfree->used", ((lfree == ram_end) || (!lfree->used)));
00607         }
00608         LWIP_MEM_ALLOC_UNPROTECT();
00609         sys_mutex_unlock(&mem_mutex);
00610         LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.",
00611          (mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end);
00612         LWIP_ASSERT("mem_malloc: allocated memory properly aligned.",
00613          ((mem_ptr_t)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0);
00614         LWIP_ASSERT("mem_malloc: sanity check alignment",
00615           (((mem_ptr_t)mem) & (MEM_ALIGNMENT-1)) == 0);
00616 
00617         return (u8_t *)mem + SIZEOF_STRUCT_MEM;
00618       }
00619     }
00620 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00621     /* if we got interrupted by a mem_free, try again */
00622   } while(local_mem_free_count != 0);
00623 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00624   LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size));
00625   MEM_STATS_INC(err);
00626   LWIP_MEM_ALLOC_UNPROTECT();
00627   sys_mutex_unlock(&mem_mutex);
00628   return NULL;
00629 }
00630 
00631 #endif /* MEM_USE_POOLS */
00632 /**
00633  * Contiguously allocates enough space for count objects that are size bytes
00634  * of memory each and returns a pointer to the allocated memory.
00635  *
00636  * The allocated memory is filled with bytes of value zero.
00637  *
00638  * @param count number of objects to allocate
00639  * @param size size of the objects to allocate
00640  * @return pointer to allocated memory / NULL pointer if there is an error
00641  */
00642 void *mem_calloc(mem_size_t count, mem_size_t size)
00643 {
00644   void *p;
00645 
00646   /* allocate 'count' objects of size 'size' */
00647   p = mem_malloc(count * size);
00648   if (p) {
00649     /* zero the memory */
00650     memset(p, 0, count * size);
00651   }
00652   return p;
00653 }
00654 
00655 #endif /* !MEM_LIBC_MALLOC */