A version of LWIP, provided for backwards compatibility.

Dependents:   AA_DemoBoard DemoBoard HelloServerDemo DemoBoard_RangeIndicator ... 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 /**
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 
00065 #include <string.h>
00066 
00067 #if MEM_USE_POOLS
00068 /* lwIP head implemented with different sized pools */
00069 
00070 /**
00071  * Allocate memory: determine the smallest pool that is big enough
00072  * to contain an element of 'size' and get an element from that pool.
00073  *
00074  * @param size the size in bytes of the memory needed
00075  * @return a pointer to the allocated memory or NULL if the pool is empty
00076  */
00077 void *
00078 mem_malloc(mem_size_t size)
00079 {
00080   struct memp_malloc_helper *element;
00081   memp_t poolnr;
00082   mem_size_t required_size = size + sizeof(struct memp_malloc_helper);
00083 
00084   for (poolnr = MEMP_POOL_FIRST; poolnr <= MEMP_POOL_LAST; poolnr++) {
00085 #if MEM_USE_POOLS_TRY_BIGGER_POOL
00086 again:
00087 #endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */
00088     /* is this pool big enough to hold an element of the required size
00089        plus a struct memp_malloc_helper that saves the pool this element came from? */
00090     if (required_size <= memp_sizes[poolnr]) {
00091       break;
00092     }
00093   }
00094   if (poolnr > MEMP_POOL_LAST) {
00095     LWIP_ASSERT("mem_malloc(): no pool is that big!", 0);
00096     return NULL;
00097   }
00098   element = (struct memp_malloc_helper*)memp_malloc(poolnr);
00099   if (element == NULL) {
00100     /* No need to DEBUGF or ASSERT: This error is already
00101        taken care of in memp.c */
00102 #if MEM_USE_POOLS_TRY_BIGGER_POOL
00103     /** Try a bigger pool if this one is empty! */
00104     if (poolnr < MEMP_POOL_LAST) {
00105       poolnr++;
00106       goto again;
00107     }
00108 #endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */
00109     return NULL;
00110   }
00111 
00112   /* save the pool number this element came from */
00113   element->poolnr = poolnr;
00114   /* and return a pointer to the memory directly after the struct memp_malloc_helper */
00115   element++;
00116 
00117   return element;
00118 }
00119 
00120 /**
00121  * Free memory previously allocated by mem_malloc. Loads the pool number
00122  * and calls memp_free with that pool number to put the element back into
00123  * its pool
00124  *
00125  * @param rmem the memory element to free
00126  */
00127 void
00128 mem_free(void *rmem)
00129 {
00130   struct memp_malloc_helper *hmem = (struct memp_malloc_helper*)rmem;
00131 
00132   LWIP_ASSERT("rmem != NULL", (rmem != NULL));
00133   LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem)));
00134 
00135   /* get the original struct memp_malloc_helper */
00136   hmem--;
00137 
00138   LWIP_ASSERT("hmem != NULL", (hmem != NULL));
00139   LWIP_ASSERT("hmem == MEM_ALIGN(hmem)", (hmem == LWIP_MEM_ALIGN(hmem)));
00140   LWIP_ASSERT("hmem->poolnr < MEMP_MAX", (hmem->poolnr < MEMP_MAX));
00141 
00142   /* and put it in the pool we saved earlier */
00143   memp_free(hmem->poolnr, hmem);
00144 }
00145 
00146 #else /* MEM_USE_POOLS */
00147 /* lwIP replacement for your libc malloc() */
00148 
00149 /**
00150  * The heap is made up as a list of structs of this type.
00151  * This does not have to be aligned since for getting its size,
00152  * we only use the macro SIZEOF_STRUCT_MEM, which automatically alignes.
00153  */
00154 struct mem {
00155   /** index (-> ram[next]) of the next struct */
00156   mem_size_t next;
00157   /** index (-> ram[next]) of the next struct */
00158   mem_size_t prev;
00159   /** 1: this area is used; 0: this area is unused */
00160   u8_t used;
00161 };
00162 
00163 /** All allocated blocks will be MIN_SIZE bytes big, at least!
00164  * MIN_SIZE can be overridden to suit your needs. Smaller values save space,
00165  * larger values could prevent too small blocks to fragment the RAM too much. */
00166 #ifndef MIN_SIZE
00167 #define MIN_SIZE             12
00168 #endif /* MIN_SIZE */
00169 /* some alignment macros: we define them here for better source code layout */
00170 #define MIN_SIZE_ALIGNED     LWIP_MEM_ALIGN_SIZE(MIN_SIZE)
00171 #define SIZEOF_STRUCT_MEM    LWIP_MEM_ALIGN_SIZE(sizeof(struct mem))
00172 #define MEM_SIZE_ALIGNED     LWIP_MEM_ALIGN_SIZE(MEM_SIZE)
00173 
00174 /** the heap. we need one struct mem at the end and some room for alignment */
00175 #ifndef MEM_POSITION
00176 static u8_t ram_heap[MEM_SIZE_ALIGNED + (2*SIZEOF_STRUCT_MEM) + MEM_ALIGNMENT];
00177 #endif
00178 /** pointer to the heap (ram_heap): for alignment, ram is now a pointer instead of an array */
00179 static u8_t *ram;
00180 /** the last entry, always unused! */
00181 static struct mem *ram_end;
00182 /** pointer to the lowest free block, this is used for faster search */
00183 static struct mem *lfree;
00184 
00185 /** concurrent access protection */
00186 //static sys_sem_t mem_sem;
00187 
00188 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00189 
00190 static volatile u8_t mem_free_count;
00191 
00192 /* Allow mem_free from other (e.g. interrupt) context */
00193 #define LWIP_MEM_FREE_DECL_PROTECT()  SYS_ARCH_DECL_PROTECT(lev_free)
00194 #define LWIP_MEM_FREE_PROTECT()       SYS_ARCH_PROTECT(lev_free)
00195 #define LWIP_MEM_FREE_UNPROTECT()     SYS_ARCH_UNPROTECT(lev_free)
00196 #define LWIP_MEM_ALLOC_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_alloc)
00197 #define LWIP_MEM_ALLOC_PROTECT()      SYS_ARCH_PROTECT(lev_alloc)
00198 #define LWIP_MEM_ALLOC_UNPROTECT()    SYS_ARCH_UNPROTECT(lev_alloc)
00199 
00200 #else /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00201 
00202 /* Protect the heap only by using a semaphore */
00203 #define LWIP_MEM_FREE_DECL_PROTECT()
00204 #define LWIP_MEM_FREE_PROTECT()    sys_arch_sem_wait(mem_sem, 0)
00205 #define LWIP_MEM_FREE_UNPROTECT()  sys_sem_signal(mem_sem)
00206 /* mem_malloc is protected using semaphore AND LWIP_MEM_ALLOC_PROTECT */
00207 #define LWIP_MEM_ALLOC_DECL_PROTECT()
00208 #define LWIP_MEM_ALLOC_PROTECT()
00209 #define LWIP_MEM_ALLOC_UNPROTECT()
00210 
00211 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00212 
00213 
00214 /**
00215  * "Plug holes" by combining adjacent empty struct mems.
00216  * After this function is through, there should not exist
00217  * one empty struct mem pointing to another empty struct mem.
00218  *
00219  * @param mem this points to a struct mem which just has been freed
00220  * @internal this function is only called by mem_free() and mem_realloc()
00221  *
00222  * This assumes access to the heap is protected by the calling function
00223  * already.
00224  */
00225 static void
00226 plug_holes(struct mem *mem)
00227 {
00228   struct mem *nmem;
00229   struct mem *pmem;
00230 
00231   LWIP_ASSERT("plug_holes: mem >= ram", (u8_t *)mem >= ram);
00232   LWIP_ASSERT("plug_holes: mem < ram_end", (u8_t *)mem < (u8_t *)ram_end);
00233   LWIP_ASSERT("plug_holes: mem->used == 0", mem->used == 0);
00234 
00235   /* plug hole forward */
00236   LWIP_ASSERT("plug_holes: mem->next <= MEM_SIZE_ALIGNED", mem->next <= MEM_SIZE_ALIGNED);
00237 
00238   nmem = (struct mem *)&ram[mem->next];
00239   if (mem != nmem && nmem->used == 0 && (u8_t *)nmem != (u8_t *)ram_end) {
00240     /* if mem->next is unused and not end of ram, combine mem and mem->next */
00241     if (lfree == nmem) {
00242       lfree = mem;
00243     }
00244     mem->next = nmem->next;
00245     ((struct mem *)&ram[nmem->next])->prev = (u8_t *)mem - ram;
00246   }
00247 
00248   /* plug hole backward */
00249   pmem = (struct mem *)&ram[mem->prev];
00250   if (pmem != mem && pmem->used == 0) {
00251     /* if mem->prev is unused, combine mem and mem->prev */
00252     if (lfree == mem) {
00253       lfree = pmem;
00254     }
00255     pmem->next = mem->next;
00256     ((struct mem *)&ram[mem->next])->prev = (u8_t *)pmem - ram;
00257   }
00258 }
00259 
00260 /**
00261  * Zero the heap and initialize start, end and lowest-free
00262  */
00263 void
00264 mem_init(void)
00265 {
00266   struct mem *mem;
00267 
00268   LWIP_ASSERT("Sanity check alignment",
00269     (SIZEOF_STRUCT_MEM & (MEM_ALIGNMENT-1)) == 0);
00270 
00271   /* align the heap */
00272   #ifndef MEM_POSITION
00273   ram = LWIP_MEM_ALIGN(ram_heap);
00274   #else
00275   ram = LWIP_MEM_ALIGN(MEM_POSITION);
00276   #endif
00277   /* initialize the start of the heap */
00278   mem = (struct mem *)ram;
00279   mem->next = MEM_SIZE_ALIGNED;
00280   mem->prev = 0;
00281   mem->used = 0;
00282   /* initialize the end of the heap */
00283   ram_end = (struct mem *)&ram[MEM_SIZE_ALIGNED];
00284   ram_end->used = 1;
00285   ram_end->next = MEM_SIZE_ALIGNED;
00286   ram_end->prev = MEM_SIZE_ALIGNED;
00287 
00288   //mem_sem = sys_sem_new(1);
00289 
00290   /* initialize the lowest-free pointer to the start of the heap */
00291   lfree = (struct mem *)ram;
00292 
00293   MEM_STATS_AVAIL(avail, MEM_SIZE_ALIGNED);
00294 }
00295 
00296 /**
00297  * Put a struct mem back on the heap
00298  *
00299  * @param rmem is the data portion of a struct mem as returned by a previous
00300  *             call to mem_malloc()
00301  */
00302 void
00303 mem_free(void *rmem)
00304 {
00305   struct mem *mem;
00306   LWIP_MEM_FREE_DECL_PROTECT();
00307 
00308   if (rmem == NULL) {
00309     LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_TRACE | 2, ("mem_free(p == NULL) was called.\n"));
00310     return;
00311   }
00312   LWIP_ASSERT("mem_free: sanity check alignment", (((mem_ptr_t)rmem) & (MEM_ALIGNMENT-1)) == 0);
00313 
00314   LWIP_ASSERT("mem_free: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
00315     (u8_t *)rmem < (u8_t *)ram_end);
00316 
00317   if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
00318     SYS_ARCH_DECL_PROTECT(lev);
00319     LWIP_DEBUGF(MEM_DEBUG | 3, ("mem_free: illegal memory\n"));
00320     /* protect mem stats from concurrent access */
00321     SYS_ARCH_PROTECT(lev);
00322     MEM_STATS_INC(illegal);
00323     SYS_ARCH_UNPROTECT(lev);
00324     return;
00325   }
00326   /* protect the heap from concurrent access */
00327   LWIP_MEM_FREE_PROTECT();
00328   /* Get the corresponding struct mem ... */
00329   mem = (struct mem *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
00330   /* ... which has to be in a used state ... */
00331   LWIP_ASSERT("mem_free: mem->used", mem->used);
00332   /* ... and is now unused. */
00333   mem->used = 0;
00334 
00335   if (mem < lfree) {
00336     /* the newly freed struct is now the lowest */
00337     lfree = mem;
00338   }
00339 
00340   MEM_STATS_DEC_USED(used, mem->next - ((u8_t *)mem - ram));
00341 
00342   /* finally, see if prev or next are free also */
00343   plug_holes(mem);
00344 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00345   mem_free_count = 1;
00346 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00347   LWIP_MEM_FREE_UNPROTECT();
00348 }
00349 
00350 /**
00351  * In contrast to its name, mem_realloc can only shrink memory, not expand it.
00352  * Since the only use (for now) is in pbuf_realloc (which also can only shrink),
00353  * this shouldn't be a problem!
00354  *
00355  * @param rmem pointer to memory allocated by mem_malloc the is to be shrinked
00356  * @param newsize required size after shrinking (needs to be smaller than or
00357  *                equal to the previous size)
00358  * @return for compatibility reasons: is always == rmem, at the moment
00359  *         or NULL if newsize is > old size, in which case rmem is NOT touched
00360  *         or freed!
00361  */
00362 void *
00363 mem_realloc(void *rmem, mem_size_t newsize)
00364 {
00365   mem_size_t size;
00366   mem_size_t ptr, ptr2;
00367   struct mem *mem, *mem2;
00368   /* use the FREE_PROTECT here: it protects with sem OR SYS_ARCH_PROTECT */
00369   LWIP_MEM_FREE_DECL_PROTECT();
00370 
00371   /* Expand the size of the allocated memory region so that we can
00372      adjust for alignment. */
00373   newsize = LWIP_MEM_ALIGN_SIZE(newsize);
00374 
00375   if(newsize < MIN_SIZE_ALIGNED) {
00376     /* every data block must be at least MIN_SIZE_ALIGNED long */
00377     newsize = MIN_SIZE_ALIGNED;
00378   }
00379 
00380   if (newsize > MEM_SIZE_ALIGNED) {
00381     return NULL;
00382   }
00383 
00384   LWIP_ASSERT("mem_realloc: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
00385    (u8_t *)rmem < (u8_t *)ram_end);
00386 
00387   if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
00388     SYS_ARCH_DECL_PROTECT(lev);
00389     LWIP_DEBUGF(MEM_DEBUG | 3, ("mem_realloc: illegal memory\n"));
00390     /* protect mem stats from concurrent access */
00391     SYS_ARCH_PROTECT(lev);
00392     MEM_STATS_INC(illegal);
00393     SYS_ARCH_UNPROTECT(lev);
00394     return rmem;
00395   }
00396   /* Get the corresponding struct mem ... */
00397   mem = (struct mem *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
00398   /* ... and its offset pointer */
00399   ptr = (u8_t *)mem - ram;
00400 
00401   size = mem->next - ptr - SIZEOF_STRUCT_MEM;
00402   LWIP_ASSERT("mem_realloc can only shrink memory", newsize <= size);
00403   if (newsize > size) {
00404     /* not supported */
00405     return NULL;
00406   }
00407   if (newsize == size) {
00408     /* No change in size, simply return */
00409     return rmem;
00410   }
00411 
00412   /* protect the heap from concurrent access */
00413   LWIP_MEM_FREE_PROTECT();
00414 
00415   MEM_STATS_DEC_USED(used, (size - newsize));
00416 
00417   mem2 = (struct mem *)&ram[mem->next];
00418   if(mem2->used == 0) {
00419     /* The next struct is unused, we can simply move it at little */
00420     mem_size_t next;
00421     /* remember the old next pointer */
00422     next = mem2->next;
00423     /* create new struct mem which is moved directly after the shrinked mem */
00424     ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
00425     if (lfree == mem2) {
00426       lfree = (struct mem *)&ram[ptr2];
00427     }
00428     mem2 = (struct mem *)&ram[ptr2];
00429     mem2->used = 0;
00430     /* restore the next pointer */
00431     mem2->next = next;
00432     /* link it back to mem */
00433     mem2->prev = ptr;
00434     /* link mem to it */
00435     mem->next = ptr2;
00436     /* last thing to restore linked list: as we have moved mem2,
00437      * let 'mem2->next->prev' point to mem2 again. but only if mem2->next is not
00438      * the end of the heap */
00439     if (mem2->next != MEM_SIZE_ALIGNED) {
00440       ((struct mem *)&ram[mem2->next])->prev = ptr2;
00441     }
00442     /* no need to plug holes, we've already done that */
00443   } else if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED <= size) {
00444     /* Next struct is used but there's room for another struct mem with
00445      * at least MIN_SIZE_ALIGNED of data.
00446      * Old size ('size') must be big enough to contain at least 'newsize' plus a struct mem
00447      * ('SIZEOF_STRUCT_MEM') with some data ('MIN_SIZE_ALIGNED').
00448      * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
00449      *       region that couldn't hold data, but when mem->next gets freed,
00450      *       the 2 regions would be combined, resulting in more free memory */
00451     ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
00452     mem2 = (struct mem *)&ram[ptr2];
00453     if (mem2 < lfree) {
00454       lfree = mem2;
00455     }
00456     mem2->used = 0;
00457     mem2->next = mem->next;
00458     mem2->prev = ptr;
00459     mem->next = ptr2;
00460     if (mem2->next != MEM_SIZE_ALIGNED) {
00461       ((struct mem *)&ram[mem2->next])->prev = ptr2;
00462     }
00463     /* the original mem->next is used, so no need to plug holes! */
00464   }
00465   /* else {
00466     next struct mem is used but size between mem and mem2 is not big enough
00467     to create another struct mem
00468     -> don't do anyhting. 
00469     -> the remaining space stays unused since it is too small
00470   } */
00471 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00472   mem_free_count = 1;
00473 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00474   LWIP_MEM_FREE_UNPROTECT();
00475   return rmem;
00476 }
00477 
00478 /**
00479  * Adam's mem_malloc() plus solution for bug #17922
00480  * Allocate a block of memory with a minimum of 'size' bytes.
00481  *
00482  * @param size is the minimum size of the requested block in bytes.
00483  * @return pointer to allocated memory or NULL if no free memory was found.
00484  *
00485  * Note that the returned value will always be aligned (as defined by MEM_ALIGNMENT).
00486  */
00487 void *
00488 mem_malloc(mem_size_t size)
00489 {
00490   mem_size_t ptr, ptr2;
00491   struct mem *mem, *mem2;
00492 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00493   u8_t local_mem_free_count = 0;
00494 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00495   LWIP_MEM_ALLOC_DECL_PROTECT();
00496 
00497   if (size == 0) {
00498     return NULL;
00499   }
00500 
00501   /* Expand the size of the allocated memory region so that we can
00502      adjust for alignment. */
00503   size = LWIP_MEM_ALIGN_SIZE(size);
00504 
00505   if(size < MIN_SIZE_ALIGNED) {
00506     /* every data block must be at least MIN_SIZE_ALIGNED long */
00507     size = MIN_SIZE_ALIGNED;
00508   }
00509 
00510   if (size > MEM_SIZE_ALIGNED) {
00511     return NULL;
00512   }
00513 
00514   /* protect the heap from concurrent access */
00515   sys_arch_sem_wait(mem_sem, 0);
00516   LWIP_MEM_ALLOC_PROTECT();
00517 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00518   /* run as long as a mem_free disturbed mem_malloc */
00519   do {
00520     local_mem_free_count = 0;
00521 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00522 
00523     /* Scan through the heap searching for a free block that is big enough,
00524      * beginning with the lowest free block.
00525      */
00526     for (ptr = (u8_t *)lfree - ram; ptr < MEM_SIZE_ALIGNED - size;
00527          ptr = ((struct mem *)&ram[ptr])->next) {
00528       mem = (struct mem *)&ram[ptr];
00529 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00530       mem_free_count = 0;
00531       LWIP_MEM_ALLOC_UNPROTECT();
00532       /* allow mem_free to run */
00533       LWIP_MEM_ALLOC_PROTECT();
00534       if (mem_free_count != 0) {
00535         local_mem_free_count = mem_free_count;
00536       }
00537       mem_free_count = 0;
00538 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00539 
00540       if ((!mem->used) &&
00541           (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size) {
00542         /* mem is not used and at least perfect fit is possible:
00543          * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */
00544 
00545         if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >= (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)) {
00546           /* (in addition to the above, we test if another struct mem (SIZEOF_STRUCT_MEM) containing
00547            * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
00548            * -> split large block, create empty remainder,
00549            * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if
00550            * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
00551            * struct mem would fit in but no data between mem2 and mem2->next
00552            * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
00553            *       region that couldn't hold data, but when mem->next gets freed,
00554            *       the 2 regions would be combined, resulting in more free memory
00555            */
00556           ptr2 = ptr + SIZEOF_STRUCT_MEM + size;
00557           /* create mem2 struct */
00558           mem2 = (struct mem *)&ram[ptr2];
00559           mem2->used = 0;
00560           mem2->next = mem->next;
00561           mem2->prev = ptr;
00562           /* and insert it between mem and mem->next */
00563           mem->next = ptr2;
00564           mem->used = 1;
00565 
00566           if (mem2->next != MEM_SIZE_ALIGNED) {
00567             ((struct mem *)&ram[mem2->next])->prev = ptr2;
00568           }
00569           MEM_STATS_INC_USED(used, (size + SIZEOF_STRUCT_MEM));
00570         } else {
00571           /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
00572            * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
00573            * take care of this).
00574            * -> near fit or excact fit: do not split, no mem2 creation
00575            * also can't move mem->next directly behind mem, since mem->next
00576            * will always be used at this point!
00577            */
00578           mem->used = 1;
00579           MEM_STATS_INC_USED(used, mem->next - ((u8_t *)mem - ram));
00580         }
00581 
00582         if (mem == lfree) {
00583           /* Find next free block after mem and update lowest free pointer */
00584           while (lfree->used && lfree != ram_end) {
00585             LWIP_MEM_ALLOC_UNPROTECT();
00586             /* prevent high interrupt latency... */
00587             LWIP_MEM_ALLOC_PROTECT();
00588             lfree = (struct mem *)&ram[lfree->next];
00589           }
00590           LWIP_ASSERT("mem_malloc: !lfree->used", ((lfree == ram_end) || (!lfree->used)));
00591         }
00592         LWIP_MEM_ALLOC_UNPROTECT();
00593         sys_sem_signal(mem_sem);
00594         LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.",
00595          (mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end);
00596         LWIP_ASSERT("mem_malloc: allocated memory properly aligned.",
00597          ((mem_ptr_t)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0);
00598         LWIP_ASSERT("mem_malloc: sanity check alignment",
00599           (((mem_ptr_t)mem) & (MEM_ALIGNMENT-1)) == 0);
00600 
00601         return (u8_t *)mem + SIZEOF_STRUCT_MEM;
00602       }
00603     }
00604 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
00605     /* if we got interrupted by a mem_free, try again */
00606   } while(local_mem_free_count != 0);
00607 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
00608   LWIP_DEBUGF(MEM_DEBUG | 2, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size));
00609   MEM_STATS_INC(err);
00610   LWIP_MEM_ALLOC_UNPROTECT();
00611   sys_sem_signal(mem_sem);
00612   return NULL;
00613 }
00614 
00615 #endif /* MEM_USE_POOLS */
00616 /**
00617  * Contiguously allocates enough space for count objects that are size bytes
00618  * of memory each and returns a pointer to the allocated memory.
00619  *
00620  * The allocated memory is filled with bytes of value zero.
00621  *
00622  * @param count number of objects to allocate
00623  * @param size size of the objects to allocate
00624  * @return pointer to allocated memory / NULL pointer if there is an error
00625  */
00626 void *mem_calloc(mem_size_t count, mem_size_t size)
00627 {
00628   void *p;
00629 
00630   /* allocate 'count' objects of size 'size' */
00631   p = mem_malloc(count * size);
00632   if (p) {
00633     /* zero the memory */
00634     memset(p, 0, count * size);
00635   }
00636   return p;
00637 }
00638 #endif /* !MEM_LIBC_MALLOC */