mem.c 23.5 KB
Newer Older
1
/*
dongly's avatar
dongly 已提交
2
 * Copyright (c) 2006-2022, RT-Thread Development Team
B
Bernard Xiong 已提交
3
 *
4
 * SPDX-License-Identifier: Apache-2.0
5 6 7
 *
 * Change Logs:
 * Date           Author       Notes
8 9 10
 * 2008-7-12      Bernard      the first version
 * 2010-06-09     Bernard      fix the end stub of heap
 *                             fix memory check in rt_realloc function
11
 * 2010-07-13     Bernard      fix RT_ALIGN issue found by kuronca
12
 * 2010-10-14     Bernard      fix rt_realloc issue when realloc a NULL pointer.
13
 * 2017-07-14     armink       fix rt_realloc issue when new size is 0
B
Bernard Xiong 已提交
14
 * 2018-10-02     Bernard      Add 64bit support
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
 */

/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *         Simon Goldschmidt
 *
 */

50
#include <rthw.h>
51 52
#include <rtthread.h>

53 54 55 56 57
#if defined (RT_USING_SMALL_MEM)
 /**
  * memory item on the small mem
  */
struct rt_small_mem_item
58
{
59
    rt_ubase_t              pool_ptr;         /**< small memory object addr */
B
Bernard Xiong 已提交
60
#ifdef ARCH_CPU_64BIT
61
    rt_uint32_t             resv;
62
#endif /* ARCH_CPU_64BIT */
63 64
    rt_size_t               next;             /**< next free item */
    rt_size_t               prev;             /**< prev free item */
65
#ifdef RT_USING_MEMTRACE
B
Bernard Xiong 已提交
66
#ifdef ARCH_CPU_64BIT
67
    rt_uint8_t              thread[8];       /**< thread name */
B
Bernard Xiong 已提交
68
#else
69
    rt_uint8_t              thread[4];       /**< thread name */
70 71
#endif /* ARCH_CPU_64BIT */
#endif /* RT_USING_MEMTRACE */
72 73
};

74 75 76 77 78 79 80 81 82 83 84
/**
 * Base structure of small memory object
 */
struct rt_small_mem
{
    struct rt_memory            parent;                 /**< inherit from rt_memory */
    rt_uint8_t                 *heap_ptr;               /**< pointer to the heap */
    struct rt_small_mem_item   *heap_end;
    struct rt_small_mem_item   *lfree;
    rt_size_t                   mem_size_aligned;       /**< aligned memory size */
};
85

86
#define HEAP_MAGIC 0x1ea0
87

B
Bernard Xiong 已提交
88 89 90
#ifdef ARCH_CPU_64BIT
#define MIN_SIZE 24
#else
91
#define MIN_SIZE 12
92
#endif /* ARCH_CPU_64BIT */
B
Bernard Xiong 已提交
93

94 95 96 97 98 99 100 101 102 103
#define MEM_MASK             0xfffffffe
#define MEM_USED()         ((((rt_base_t)(small_mem)) & MEM_MASK) | 0x1)
#define MEM_FREED()        ((((rt_base_t)(small_mem)) & MEM_MASK) | 0x0)
#define MEM_ISUSED(_mem)   \
                      (((rt_base_t)(((struct rt_small_mem_item *)(_mem))->pool_ptr)) & (~MEM_MASK))
#define MEM_POOL(_mem)     \
    ((struct rt_small_mem *)(((rt_base_t)(((struct rt_small_mem_item *)(_mem))->pool_ptr)) & (MEM_MASK)))
#define MEM_SIZE(_heap, _mem)      \
    (((struct rt_small_mem_item *)(_mem))->next - ((rt_ubase_t)(_mem) - \
    (rt_ubase_t)((_heap)->heap_ptr)) - RT_ALIGN(sizeof(struct rt_small_mem_item), RT_ALIGN_SIZE))
B
bernard.xiong 已提交
104

105 106
#define MIN_SIZE_ALIGNED     RT_ALIGN(MIN_SIZE, RT_ALIGN_SIZE)
#define SIZEOF_STRUCT_MEM    RT_ALIGN(sizeof(struct rt_small_mem_item), RT_ALIGN_SIZE)
107

108
#ifdef RT_USING_MEMTRACE
109
rt_inline void rt_smem_setname(struct rt_small_mem_item *mem, const char *name)
110 111 112 113 114 115 116 117 118 119 120 121 122
{
    int index;
    for (index = 0; index < sizeof(mem->thread); index ++)
    {
        if (name[index] == '\0') break;
        mem->thread[index] = name[index];
    }

    for (; index < sizeof(mem->thread); index ++)
    {
        mem->thread[index] = ' ';
    }
}
123
#endif /* RT_USING_MEMTRACE */
124

125
static void plug_holes(struct rt_small_mem *m, struct rt_small_mem_item *mem)
126
{
127 128
    struct rt_small_mem_item *nmem;
    struct rt_small_mem_item *pmem;
D
dzzxzz@gmail.com 已提交
129

130 131
    RT_ASSERT((rt_uint8_t *)mem >= m->heap_ptr);
    RT_ASSERT((rt_uint8_t *)mem < (rt_uint8_t *)m->heap_end);
D
dzzxzz@gmail.com 已提交
132 133

    /* plug hole forward */
134 135 136
    nmem = (struct rt_small_mem_item *)&m->heap_ptr[mem->next];
    if (mem != nmem && !MEM_ISUSED(nmem) &&
        (rt_uint8_t *)nmem != (rt_uint8_t *)m->heap_end)
D
dzzxzz@gmail.com 已提交
137
    {
138
        /* if mem->next is unused and not end of m->heap_ptr,
D
dzzxzz@gmail.com 已提交
139 140
         * combine mem and mem->next
         */
141
        if (m->lfree == nmem)
D
dzzxzz@gmail.com 已提交
142
        {
143
            m->lfree = mem;
D
dzzxzz@gmail.com 已提交
144
        }
145
        nmem->pool_ptr = 0;
D
dzzxzz@gmail.com 已提交
146
        mem->next = nmem->next;
147
        ((struct rt_small_mem_item *)&m->heap_ptr[nmem->next])->prev = (rt_uint8_t *)mem - m->heap_ptr;
D
dzzxzz@gmail.com 已提交
148 149 150
    }

    /* plug hole backward */
151 152
    pmem = (struct rt_small_mem_item *)&m->heap_ptr[mem->prev];
    if (pmem != mem && !MEM_ISUSED(pmem))
D
dzzxzz@gmail.com 已提交
153 154
    {
        /* if mem->prev is unused, combine mem and mem->prev */
155
        if (m->lfree == mem)
D
dzzxzz@gmail.com 已提交
156
        {
157
            m->lfree = pmem;
D
dzzxzz@gmail.com 已提交
158
        }
159
        mem->pool_ptr = 0;
D
dzzxzz@gmail.com 已提交
160
        pmem->next = mem->next;
161
        ((struct rt_small_mem_item *)&m->heap_ptr[mem->next])->prev = (rt_uint8_t *)pmem - m->heap_ptr;
D
dzzxzz@gmail.com 已提交
162
    }
163 164 165
}

/**
166 167 168 169 170 171 172
 * @brief This function will initialize small memory management algorithm.
 *
 * @param m the small memory management object.
 *
 * @param name is the name of the small memory management object.
 *
 * @param begin_addr the beginning address of memory.
173
 *
174
 * @param size is the size of the memory.
175
 *
176
 * @return Return a pointer to the memory object. When the return value is RT_NULL, it means the init failed.
177
 */
178 179 180
rt_smem_t rt_smem_init(const char    *name,
                     void          *begin_addr,
                     rt_size_t      size)
181
{
182 183 184
    struct rt_small_mem_item *mem;
    struct rt_small_mem *small_mem;
    rt_ubase_t start_addr, begin_align, end_align, mem_size;
D
dzzxzz@gmail.com 已提交
185

186 187 188 189
    small_mem = (struct rt_small_mem *)RT_ALIGN((rt_ubase_t)begin_addr, RT_ALIGN_SIZE);
    start_addr = (rt_ubase_t)small_mem + sizeof(*small_mem);
    begin_align = RT_ALIGN((rt_ubase_t)start_addr, RT_ALIGN_SIZE);
    end_align   = RT_ALIGN_DOWN((rt_ubase_t)begin_addr + size, RT_ALIGN_SIZE);
D
dzzxzz@gmail.com 已提交
190 191 192

    /* alignment addr */
    if ((end_align > (2 * SIZEOF_STRUCT_MEM)) &&
193
        ((end_align - 2 * SIZEOF_STRUCT_MEM) >= start_addr))
D
dzzxzz@gmail.com 已提交
194 195
    {
        /* calculate the aligned memory size */
196
        mem_size = end_align - begin_align - 2 * SIZEOF_STRUCT_MEM;
D
dzzxzz@gmail.com 已提交
197 198 199 200
    }
    else
    {
        rt_kprintf("mem init, error begin address 0x%x, and end address 0x%x\n",
201
                   (rt_ubase_t)begin_addr, (rt_ubase_t)begin_addr + size);
D
dzzxzz@gmail.com 已提交
202

203
        return RT_NULL;
D
dzzxzz@gmail.com 已提交
204 205
    }

206 207 208 209 210 211 212 213
    rt_memset(small_mem, 0, sizeof(*small_mem));
    /* initialize small memory object */
    rt_object_init(&(small_mem->parent.parent), RT_Object_Class_Memory, name);
    small_mem->parent.algorithm = "small";
    small_mem->parent.address = begin_align;
    small_mem->parent.total = mem_size;
    small_mem->mem_size_aligned = mem_size;

D
dzzxzz@gmail.com 已提交
214
    /* point to begin address of heap */
215
    small_mem->heap_ptr = (rt_uint8_t *)begin_align;
D
dzzxzz@gmail.com 已提交
216 217

    RT_DEBUG_LOG(RT_DEBUG_MEM, ("mem init, heap begin address 0x%x, size %d\n",
218
                                (rt_ubase_t)small_mem->heap_ptr, small_mem->mem_size_aligned));
219

D
dzzxzz@gmail.com 已提交
220
    /* initialize the start of the heap */
221 222 223
    mem        = (struct rt_small_mem_item *)small_mem->heap_ptr;
    mem->pool_ptr = MEM_FREED();
    mem->next  = small_mem->mem_size_aligned + SIZEOF_STRUCT_MEM;
D
dzzxzz@gmail.com 已提交
224
    mem->prev  = 0;
E
emlslxl 已提交
225
#ifdef RT_USING_MEMTRACE
226
    rt_smem_setname(mem, "INIT");
227
#endif /* RT_USING_MEMTRACE */
228

D
dzzxzz@gmail.com 已提交
229
    /* initialize the end of the heap */
230 231 232 233
    small_mem->heap_end        = (struct rt_small_mem_item *)&small_mem->heap_ptr[mem->next];
    small_mem->heap_end->pool_ptr = MEM_USED();
    small_mem->heap_end->next  = small_mem->mem_size_aligned + SIZEOF_STRUCT_MEM;
    small_mem->heap_end->prev  = small_mem->mem_size_aligned + SIZEOF_STRUCT_MEM;
E
emlslxl 已提交
234
#ifdef RT_USING_MEMTRACE
235
    rt_smem_setname(small_mem->heap_end, "INIT");
236
#endif /* RT_USING_MEMTRACE */
237

D
dzzxzz@gmail.com 已提交
238
    /* initialize the lowest-free pointer to the start of the heap */
239 240 241
    small_mem->lfree = (struct rt_small_mem_item *)small_mem->heap_ptr;

    return &small_mem->parent;
242
}
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
RTM_EXPORT(rt_smem_init);

/**
 * @brief This function will remove a small mem from the system.
 *
 * @param m the small memory management object.
 *
 * @return RT_EOK
 */
rt_err_t rt_smem_detach(rt_smem_t m)
{
    RT_ASSERT(m != RT_NULL);
    RT_ASSERT(rt_object_get_type(&m->parent) == RT_Object_Class_Memory);
    RT_ASSERT(rt_object_is_systemobject(&m->parent));

    rt_object_detach(&(m->parent));

    return RT_EOK;
}
RTM_EXPORT(rt_smem_detach);
263 264 265 266 267

/**
 * @addtogroup MM
 */

D
dogandog 已提交
268
/**@{*/
269 270

/**
271
 * @brief Allocate a block of memory with a minimum of 'size' bytes.
272
 *
273 274
 * @param m the small memory management object.
 *
275 276
 * @param size is the minimum size of the requested block in bytes.
 *
Nameless-Y's avatar
Nameless-Y 已提交
277
 * @return the pointer to allocated memory or NULL if no free memory was found.
278
 */
279
void *rt_smem_alloc(rt_smem_t m, rt_size_t size)
280
{
D
dzzxzz@gmail.com 已提交
281
    rt_size_t ptr, ptr2;
282 283
    struct rt_small_mem_item *mem, *mem2;
    struct rt_small_mem *small_mem;
284

D
dzzxzz@gmail.com 已提交
285 286
    if (size == 0)
        return RT_NULL;
287

288 289 290
    RT_ASSERT(m != RT_NULL);
    RT_ASSERT(rt_object_get_type(&m->parent) == RT_Object_Class_Memory);
    RT_ASSERT(rt_object_is_systemobject(&m->parent));
291

D
dzzxzz@gmail.com 已提交
292
    if (size != RT_ALIGN(size, RT_ALIGN_SIZE))
dongly's avatar
dongly 已提交
293
    {
D
dzzxzz@gmail.com 已提交
294
        RT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d, but align to %d\n",
295
                                    size, RT_ALIGN(size, RT_ALIGN_SIZE)));
dongly's avatar
dongly 已提交
296
    }
D
dzzxzz@gmail.com 已提交
297
    else
dongly's avatar
dongly 已提交
298
    {
D
dzzxzz@gmail.com 已提交
299
        RT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d\n", size));
dongly's avatar
dongly 已提交
300
    }
D
dzzxzz@gmail.com 已提交
301

302
    small_mem = (struct rt_small_mem *)m;
D
dzzxzz@gmail.com 已提交
303 304 305
    /* alignment size */
    size = RT_ALIGN(size, RT_ALIGN_SIZE);

306 307 308 309
    /* every data block must be at least MIN_SIZE_ALIGNED long */
    if (size < MIN_SIZE_ALIGNED)
        size = MIN_SIZE_ALIGNED;

310
    if (size > small_mem->mem_size_aligned)
D
dzzxzz@gmail.com 已提交
311 312 313 314 315 316
    {
        RT_DEBUG_LOG(RT_DEBUG_MEM, ("no memory\n"));

        return RT_NULL;
    }

317 318 319
    for (ptr = (rt_uint8_t *)small_mem->lfree - small_mem->heap_ptr;
         ptr <= small_mem->mem_size_aligned - size;
         ptr = ((struct rt_small_mem_item *)&small_mem->heap_ptr[ptr])->next)
D
dzzxzz@gmail.com 已提交
320
    {
321
        mem = (struct rt_small_mem_item *)&small_mem->heap_ptr[ptr];
D
dzzxzz@gmail.com 已提交
322

323
        if ((!MEM_ISUSED(mem)) && (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size)
D
dzzxzz@gmail.com 已提交
324 325 326 327 328 329 330
        {
            /* mem is not used and at least perfect fit is possible:
             * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */

            if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >=
                (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED))
            {
331
                /* (in addition to the above, we test if another struct rt_small_mem_item (SIZEOF_STRUCT_MEM) containing
D
dzzxzz@gmail.com 已提交
332 333 334 335
                 * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
                 * -> split large block, create empty remainder,
                 * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if
                 * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
336
                 * struct rt_small_mem_item would fit in but no data between mem2 and mem2->next
D
dzzxzz@gmail.com 已提交
337 338 339 340 341 342 343
                 * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
                 *       region that couldn't hold data, but when mem->next gets freed,
                 *       the 2 regions would be combined, resulting in more free memory
                 */
                ptr2 = ptr + SIZEOF_STRUCT_MEM + size;

                /* create mem2 struct */
344 345
                mem2       = (struct rt_small_mem_item *)&small_mem->heap_ptr[ptr2];
                mem2->pool_ptr = MEM_FREED();
D
dzzxzz@gmail.com 已提交
346 347
                mem2->next = mem->next;
                mem2->prev = ptr;
E
emlslxl 已提交
348
#ifdef RT_USING_MEMTRACE
349
                rt_smem_setname(mem2, "    ");
350
#endif /* RT_USING_MEMTRACE */
D
dzzxzz@gmail.com 已提交
351 352 353 354

                /* and insert it between mem and mem->next */
                mem->next = ptr2;

355
                if (mem2->next != small_mem->mem_size_aligned + SIZEOF_STRUCT_MEM)
D
dzzxzz@gmail.com 已提交
356
                {
357
                    ((struct rt_small_mem_item *)&small_mem->heap_ptr[mem2->next])->prev = ptr2;
D
dzzxzz@gmail.com 已提交
358
                }
359 360 361
                small_mem->parent.used += (size + SIZEOF_STRUCT_MEM);
                if (small_mem->parent.max < small_mem->parent.used)
                    small_mem->parent.max = small_mem->parent.used;
D
dzzxzz@gmail.com 已提交
362 363 364 365 366 367 368 369 370 371
            }
            else
            {
                /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
                 * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
                 * take care of this).
                 * -> near fit or excact fit: do not split, no mem2 creation
                 * also can't move mem->next directly behind mem, since mem->next
                 * will always be used at this point!
                 */
372 373 374
                small_mem->parent.used += mem->next - ((rt_uint8_t *)mem - small_mem->heap_ptr);
                if (small_mem->parent.max < small_mem->parent.used)
                    small_mem->parent.max = small_mem->parent.used;
D
dzzxzz@gmail.com 已提交
375
            }
376 377
            /* set small memory object */
            mem->pool_ptr = MEM_USED();
E
emlslxl 已提交
378
#ifdef RT_USING_MEMTRACE
379
            if (rt_thread_self())
380
                rt_smem_setname(mem, rt_thread_self()->name);
381
            else
382
                rt_smem_setname(mem, "NONE");
383
#endif /* RT_USING_MEMTRACE */
384

385
            if (mem == small_mem->lfree)
D
dzzxzz@gmail.com 已提交
386 387
            {
                /* Find next free block after mem and update lowest free pointer */
388 389
                while (MEM_ISUSED(small_mem->lfree) && small_mem->lfree != small_mem->heap_end)
                    small_mem->lfree = (struct rt_small_mem_item *)&small_mem->heap_ptr[small_mem->lfree->next];
390

391
                RT_ASSERT(((small_mem->lfree == small_mem->heap_end) || (!MEM_ISUSED(small_mem->lfree))));
D
dzzxzz@gmail.com 已提交
392
            }
393
            RT_ASSERT((rt_ubase_t)mem + SIZEOF_STRUCT_MEM + size <= (rt_ubase_t)small_mem->heap_end);
B
Bernard Xiong 已提交
394 395
            RT_ASSERT((rt_ubase_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM) % RT_ALIGN_SIZE == 0);
            RT_ASSERT((((rt_ubase_t)mem) & (RT_ALIGN_SIZE - 1)) == 0);
396

D
dzzxzz@gmail.com 已提交
397
            RT_DEBUG_LOG(RT_DEBUG_MEM,
B
Bernard Xiong 已提交
398
                         ("allocate memory at 0x%x, size: %d\n",
B
Bernard Xiong 已提交
399
                          (rt_ubase_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM),
400
                          (rt_ubase_t)(mem->next - ((rt_uint8_t *)mem - small_mem->heap_ptr))));
401

D
dzzxzz@gmail.com 已提交
402 403 404 405 406 407
            /* return the memory data except mem struct */
            return (rt_uint8_t *)mem + SIZEOF_STRUCT_MEM;
        }
    }

    return RT_NULL;
408
}
409
RTM_EXPORT(rt_smem_alloc);
410 411

/**
Nameless-Y's avatar
Nameless-Y 已提交
412
 * @brief This function will change the size of previously allocated memory block.
413
 *
414 415 416
 * @param m the small memory management object.
 *
 * @param rmem is the pointer to memory allocated by rt_mem_alloc.
B
bernard.xiong 已提交
417
 *
Nameless-Y's avatar
Nameless-Y 已提交
418
 * @param newsize is the required new size.
419 420
 *
 * @return the changed memory block address.
421
 */
422
void *rt_smem_realloc(rt_smem_t m, void *rmem, rt_size_t newsize)
423
{
D
dzzxzz@gmail.com 已提交
424 425
    rt_size_t size;
    rt_size_t ptr, ptr2;
426 427
    struct rt_small_mem_item *mem, *mem2;
    struct rt_small_mem *small_mem;
D
dzzxzz@gmail.com 已提交
428
    void *nmem;
429

430 431 432
    RT_ASSERT(m != RT_NULL);
    RT_ASSERT(rt_object_get_type(&m->parent) == RT_Object_Class_Memory);
    RT_ASSERT(rt_object_is_systemobject(&m->parent));
433

434
    small_mem = (struct rt_small_mem *)m;
D
dzzxzz@gmail.com 已提交
435 436
    /* alignment size */
    newsize = RT_ALIGN(newsize, RT_ALIGN_SIZE);
437
    if (newsize > small_mem->mem_size_aligned)
D
dzzxzz@gmail.com 已提交
438 439
    {
        RT_DEBUG_LOG(RT_DEBUG_MEM, ("realloc: out of memory\n"));
440

D
dzzxzz@gmail.com 已提交
441 442
        return RT_NULL;
    }
443 444
    else if (newsize == 0)
    {
445
        rt_smem_free(rmem);
446 447
        return RT_NULL;
    }
448

D
dzzxzz@gmail.com 已提交
449 450
    /* allocate a new memory block */
    if (rmem == RT_NULL)
451
        return rt_smem_alloc(&small_mem->parent, newsize);
D
dzzxzz 已提交
452

453 454 455
    RT_ASSERT((((rt_ubase_t)rmem) & (RT_ALIGN_SIZE - 1)) == 0);
    RT_ASSERT((rt_uint8_t *)rmem >= (rt_uint8_t *)small_mem->heap_ptr);
    RT_ASSERT((rt_uint8_t *)rmem < (rt_uint8_t *)small_mem->heap_end);
456

457
    mem = (struct rt_small_mem_item *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);
458

459 460
    /* current memory block size */
    ptr = (rt_uint8_t *)mem - small_mem->heap_ptr;
D
dzzxzz@gmail.com 已提交
461 462 463 464 465 466
    size = mem->next - ptr - SIZEOF_STRUCT_MEM;
    if (size == newsize)
    {
        /* the size is the same as */
        return rmem;
    }
467

D
dzzxzz@gmail.com 已提交
468 469 470
    if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE < size)
    {
        /* split memory block */
471
        small_mem->parent.used -= (size - newsize);
472

D
dzzxzz@gmail.com 已提交
473
        ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
474 475
        mem2 = (struct rt_small_mem_item *)&small_mem->heap_ptr[ptr2];
        mem2->pool_ptr = MEM_FREED();
D
dzzxzz@gmail.com 已提交
476 477
        mem2->next = mem->next;
        mem2->prev = ptr;
478
#ifdef RT_USING_MEMTRACE
479
        rt_smem_setname(mem2, "    ");
480
#endif /* RT_USING_MEMTRACE */
D
dzzxzz@gmail.com 已提交
481
        mem->next = ptr2;
482
        if (mem2->next != small_mem->mem_size_aligned + SIZEOF_STRUCT_MEM)
D
dzzxzz@gmail.com 已提交
483
        {
484
            ((struct rt_small_mem_item *)&small_mem->heap_ptr[mem2->next])->prev = ptr2;
D
dzzxzz@gmail.com 已提交
485
        }
mysterywolf's avatar
mysterywolf 已提交
486

487
        if (mem2 < small_mem->lfree)
G
greed-island 已提交
488 489
        {
            /* the splited struct is now the lowest */
490
            small_mem->lfree = mem2;
G
greed-island 已提交
491
        }
D
dzzxzz@gmail.com 已提交
492

493
        plug_holes(small_mem, mem2);
D
dzzxzz@gmail.com 已提交
494 495 496 497 498

        return rmem;
    }

    /* expand memory */
499
    nmem = rt_smem_alloc(&small_mem->parent, newsize);
D
dzzxzz@gmail.com 已提交
500 501
    if (nmem != RT_NULL) /* check memory */
    {
B
Bernard Xiong 已提交
502
        rt_memcpy(nmem, rmem, size < newsize ? size : newsize);
503
        rt_smem_free(rmem);
D
dzzxzz@gmail.com 已提交
504 505 506
    }

    return nmem;
507
}
508
RTM_EXPORT(rt_smem_realloc);
509 510

/**
511
 * @brief This function will release the previously allocated memory block by
512
 *        rt_mem_alloc. The released memory block is taken back to system heap.
513
 *
Nameless-Y's avatar
Nameless-Y 已提交
514
 * @param rmem the address of memory which will be released.
515
 */
516
void rt_smem_free(void *rmem)
517
{
518 519
    struct rt_small_mem_item *mem;
    struct rt_small_mem *small_mem;
520

D
dzzxzz@gmail.com 已提交
521 522
    if (rmem == RT_NULL)
        return;
523

B
Bernard Xiong 已提交
524
    RT_ASSERT((((rt_ubase_t)rmem) & (RT_ALIGN_SIZE - 1)) == 0);
525

526 527
    /* Get the corresponding struct rt_small_mem_item ... */
    mem = (struct rt_small_mem_item *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);
D
dzzxzz@gmail.com 已提交
528
    /* ... which has to be in a used state ... */
529 530 531 532 533 534 535 536 537
    small_mem = MEM_POOL(mem);
    RT_ASSERT(small_mem != RT_NULL);
    RT_ASSERT(MEM_ISUSED(mem));
    RT_ASSERT(rt_object_get_type(&small_mem->parent.parent) == RT_Object_Class_Memory);
    RT_ASSERT(rt_object_is_systemobject(&small_mem->parent.parent));
    RT_ASSERT((rt_uint8_t *)rmem >= (rt_uint8_t *)small_mem->heap_ptr &&
              (rt_uint8_t *)rmem < (rt_uint8_t *)small_mem->heap_end);
    RT_ASSERT(MEM_POOL(&small_mem->heap_ptr[mem->next]) == small_mem);

538 539 540 541 542
    RT_DEBUG_LOG(RT_DEBUG_MEM,
                 ("release memory 0x%x, size: %d\n",
                  (rt_ubase_t)rmem,
                  (rt_ubase_t)(mem->next - ((rt_uint8_t *)mem - small_mem->heap_ptr))));

D
dzzxzz@gmail.com 已提交
543
    /* ... and is now unused. */
544
    mem->pool_ptr = MEM_FREED();
545
#ifdef RT_USING_MEMTRACE
546
    rt_smem_setname(mem, "    ");
547
#endif /* RT_USING_MEMTRACE */
548

549
    if (mem < small_mem->lfree)
D
dzzxzz@gmail.com 已提交
550 551
    {
        /* the newly freed struct is now the lowest */
552
        small_mem->lfree = mem;
D
dzzxzz@gmail.com 已提交
553
    }
554

555
    small_mem->parent.used -= (mem->next - ((rt_uint8_t *)mem - small_mem->heap_ptr));
556

D
dzzxzz@gmail.com 已提交
557
    /* finally, see if prev or next are free also */
558
    plug_holes(small_mem, mem);
559
}
560
RTM_EXPORT(rt_smem_free);
B
bernard.xiong 已提交
561

562 563
#ifdef RT_USING_FINSH
#include <finsh.h>
D
dzzxzz@gmail.com 已提交
564

565
#ifdef RT_USING_MEMTRACE
566
int memcheck(int argc, char *argv[])
567 568
{
    int position;
569
    rt_base_t level;
570 571 572 573 574 575 576 577
    struct rt_small_mem_item *mem;
    struct rt_small_mem *m;
    struct rt_object_information *information;
    struct rt_list_node *node;
    struct rt_object *object;
    char *name;

    name = argc > 1 ? argv[1] : RT_NULL;
578
    level = rt_hw_interrupt_disable();
579 580 581 582 583
    /* get mem object */
    information = rt_object_get_information(RT_Object_Class_Memory);
    for (node = information->object_list.next;
         node != &(information->object_list);
         node  = node->next)
584
    {
585 586 587 588 589 590 591 592 593 594 595 596 597 598
        object = rt_list_entry(node, struct rt_object, list);
        /* find the specified object */
        if (name != RT_NULL && rt_strncmp(name, object->name, RT_NAME_MAX) != 0)
            continue;
        /* mem object */
        m = (struct rt_small_mem *)object;
        /* check mem */
        for (mem = (struct rt_small_mem_item *)m->heap_ptr; mem != m->heap_end; mem = (struct rt_small_mem_item *)&m->heap_ptr[mem->next])
        {
            position = (rt_ubase_t)mem - (rt_ubase_t)m->heap_ptr;
            if (position < 0) goto __exit;
            if (position > (int)m->mem_size_aligned) goto __exit;
            if (MEM_POOL(mem) != m) goto __exit;
        }
599 600 601 602 603 604
    }
    rt_hw_interrupt_enable(level);

    return 0;
__exit:
    rt_kprintf("Memory block wrong:\n");
605
    rt_kprintf("   name: %s\n", m->parent.parent.name);
606
    rt_kprintf("address: 0x%08x\n", mem);
607 608
    rt_kprintf("   pool: 0x%04x\n", mem->pool_ptr);
    rt_kprintf("   size: %d\n", mem->next - position - SIZEOF_STRUCT_MEM);
609 610 611 612 613 614
    rt_hw_interrupt_enable(level);

    return 0;
}
MSH_CMD_EXPORT(memcheck, check memory data);

E
emlslxl 已提交
615
int memtrace(int argc, char **argv)
616
{
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    struct rt_small_mem_item *mem;
    struct rt_small_mem *m;
    struct rt_object_information *information;
    struct rt_list_node *node;
    struct rt_object *object;
    char *name;

    name = argc > 1 ? argv[1] : RT_NULL;
    /* get mem object */
    information = rt_object_get_information(RT_Object_Class_Memory);
    for (node = information->object_list.next;
         node != &(information->object_list);
         node  = node->next)
    {
        object = rt_list_entry(node, struct rt_object, list);
        /* find the specified object */
        if (name != RT_NULL && rt_strncmp(name, object->name, RT_NAME_MAX) != 0)
            continue;
        /* mem object */
        m = (struct rt_small_mem *)object;
        /* show memory information */
        rt_kprintf("\nmemory heap address:\n");
        rt_kprintf("name    : %s\n", m->parent.parent.name);
        rt_kprintf("total   : 0x%d\n", m->parent.total);
        rt_kprintf("used    : 0x%d\n", m->parent.used);
        rt_kprintf("max_used: 0x%d\n", m->parent.max);
        rt_kprintf("heap_ptr: 0x%08x\n", m->heap_ptr);
        rt_kprintf("lfree   : 0x%08x\n", m->lfree);
        rt_kprintf("heap_end: 0x%08x\n", m->heap_end);
        rt_kprintf("\n--memory item information --\n");
        for (mem = (struct rt_small_mem_item *)m->heap_ptr; mem != m->heap_end; mem = (struct rt_small_mem_item *)&m->heap_ptr[mem->next])
        {
            int size = MEM_SIZE(m, mem);
650

651 652 653 654 655 656 657
            rt_kprintf("[0x%08x - ", mem);
            if (size < 1024)
                rt_kprintf("%5d", size);
            else if (size < 1024 * 1024)
                rt_kprintf("%4dK", size / 1024);
            else
                rt_kprintf("%4dM", size / (1024 * 1024));
658

659 660 661 662 663 664
            rt_kprintf("] %c%c%c%c", mem->thread[0], mem->thread[1], mem->thread[2], mem->thread[3]);
            if (MEM_POOL(mem) != m)
                rt_kprintf(": ***\n");
            else
                rt_kprintf("\n");
        }
665 666 667 668
    }
    return 0;
}
MSH_CMD_EXPORT(memtrace, dump memory trace information);
669 670
#endif /* RT_USING_MEMTRACE */
#endif /* RT_USING_FINSH */
671

672
#endif /* defined (RT_USING_SMALL_MEM) */
673

D
dogandog 已提交
674
/**@}*/