memheap.c 28.8 KB
Newer Older
1
/*
2
 * Copyright (c) 2006-2018, RT-Thread Development Team
B
Bernard Xiong 已提交
3
 *
4 5 6 7 8
 * SPDX-License-Identifier: Apache-2.0
 */

/*
 * File      : memheap.c
9 10 11 12
 *
 * Change Logs:
 * Date           Author       Notes
 * 2012-04-10     Bernard      first implementation
13
 * 2012-10-16     Bernard      add the mutex lock for heap object.
14 15
 * 2012-12-29     Bernard      memheap can be used as system heap.
 *                             change mutex lock to semaphore lock.
B
Bernard Xiong 已提交
16
 * 2013-04-10     Bernard      add rt_memheap_realloc function.
B
Bernard Xiong 已提交
17
 * 2013-05-24     Bernard      fix the rt_memheap_realloc issue.
18
 * 2013-07-11     Grissiom     fix the memory block splitting issue.
19
 * 2013-07-15     Grissiom     optimize rt_memheap_realloc
20
 */
21

22
#include <rthw.h>
23 24 25 26 27
#include <rtthread.h>

#ifdef RT_USING_MEMHEAP

/* dynamic pool magic and mask */
28 29 30 31
#define RT_MEMHEAP_MAGIC        0x1ea01ea0
#define RT_MEMHEAP_MASK         0xfffffffe
#define RT_MEMHEAP_USED         0x01
#define RT_MEMHEAP_FREED        0x00
32

33 34
#define RT_MEMHEAP_IS_USED(i)   ((i)->magic & RT_MEMHEAP_USED)
#define RT_MEMHEAP_MINIALLOC    12
35

36
#define RT_MEMHEAP_SIZE         RT_ALIGN(sizeof(struct rt_memheap_item), RT_ALIGN_SIZE)
37
#define MEMITEM_SIZE(item)      ((rt_ubase_t)item->next - (rt_ubase_t)item - RT_MEMHEAP_SIZE)
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#define MEMITEM(ptr)            (struct rt_memheap_item*)((rt_uint8_t*)ptr - RT_MEMHEAP_SIZE)

#ifdef RT_USING_MEMTRACE
rt_inline void rt_memheap_setname(struct rt_memheap_item *item, const char *name)
{
    int index;
    rt_uint8_t* ptr;

    ptr = (rt_uint8_t*)&(item->next_free);
    for (index = 0; index < sizeof(void*); index ++)
    {
        if (name[index] == '\0') break;
        ptr[index] = name[index];
    }
    if (name[index] == '\0') ptr[index] = '\0';
    else 
    {
        ptr = (rt_uint8_t*)&(item->prev_free);
        for (index = 0; index < sizeof(void*) && (index + sizeof(void*))< RT_NAME_MAX; index ++)
        {
            if (name[sizeof(void*) + index] == '\0') break;
            ptr[index] = name[sizeof(void*) + index];
        }

        if (name[sizeof(void*) + index] == '\0') ptr[index] = '\0';
    }
}

void rt_mem_set_tag(void* ptr, const char* name)
{
    struct rt_memheap_item* item;

    if (ptr && name)
    {
        item = MEMITEM(ptr);
        rt_memheap_setname(item, name);
    }
}
#endif
77 78 79 80 81 82 83 84 85

/*
 * The initialized memory pool will be:
 * +-----------------------------------+--------------------------+
 * | whole freed memory block          | Used Memory Block Tailer |
 * +-----------------------------------+--------------------------+
 *
 * block_list --> whole freed memory block
 *
86 87
 * The length of Used Memory Block Tailer is 0,
 * which is prevents block merging across list
88
 */
89 90 91
rt_err_t rt_memheap_init(struct rt_memheap *memheap,
                         const char        *name,
                         void              *start_addr,
B
Bernard Xiong 已提交
92
                         rt_size_t         size)
93
{
94
    struct rt_memheap_item *item;
95

96
    RT_ASSERT(memheap != RT_NULL);
97

98 99
    /* initialize pool object */
    rt_object_init(&(memheap->parent), RT_Object_Class_MemHeap, name);
100

101 102
    memheap->start_addr     = start_addr;
    memheap->pool_size      = RT_ALIGN_DOWN(size, RT_ALIGN_SIZE);
103
    memheap->available_size = memheap->pool_size - (2 * RT_MEMHEAP_SIZE);
104
    memheap->max_used_size  = memheap->pool_size - memheap->available_size;
105

106 107
    /* initialize the free list header */
    item            = &(memheap->free_header);
108
    item->magic     = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
109 110 111 112 113 114 115 116 117 118 119
    item->pool_ptr  = memheap;
    item->next      = RT_NULL;
    item->prev      = RT_NULL;
    item->next_free = item;
    item->prev_free = item;

    /* set the free list to free list header */
    memheap->free_list = item;

    /* initialize the first big memory block */
    item            = (struct rt_memheap_item *)start_addr;
120
    item->magic     = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
121 122 123 124 125 126 127
    item->pool_ptr  = memheap;
    item->next      = RT_NULL;
    item->prev      = RT_NULL;
    item->next_free = item;
    item->prev_free = item;

    item->next = (struct rt_memheap_item *)
128
                 ((rt_uint8_t *)item + memheap->available_size + RT_MEMHEAP_SIZE);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    item->prev = item->next;

    /* block list header */
    memheap->block_list = item;

    /* place the big memory block to free list */
    item->next_free = memheap->free_list->next_free;
    item->prev_free = memheap->free_list;
    memheap->free_list->next_free->prev_free = item;
    memheap->free_list->next_free            = item;

    /* move to the end of memory pool to build a small tailer block,
     * which prevents block merging
     */
    item = item->next;
    /* it's a used memory block */
145
    item->magic     = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED);
146 147 148 149 150 151
    item->pool_ptr  = memheap;
    item->next      = (struct rt_memheap_item *)start_addr;
    item->prev      = (struct rt_memheap_item *)start_addr;
    /* not in free list */
    item->next_free = item->prev_free = RT_NULL;

152 153
    /* initialize semaphore lock */
    rt_sem_init(&(memheap->lock), name, 1, RT_IPC_FLAG_FIFO);
154 155

    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
156
                 ("memory heap: start addr 0x%08x, size %d, free list header 0x%08x\n",
157
                  start_addr, size, &(memheap->free_header)));
158

159
    return RT_EOK;
160
}
161
RTM_EXPORT(rt_memheap_init);
162

163
rt_err_t rt_memheap_detach(struct rt_memheap *heap)
164
{
165
    RT_ASSERT(heap);
166 167
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);
    RT_ASSERT(rt_object_is_systemobject(&heap->parent));
Moral-Hao's avatar
Moral-Hao 已提交
168 169
    
    rt_sem_detach(&heap->lock);
170
    rt_object_detach(&(heap->parent));
171

172 173
    /* Return a successful completion. */
    return RT_EOK;
174
}
175
RTM_EXPORT(rt_memheap_detach);
176

B
Bernard Xiong 已提交
177
void *rt_memheap_alloc(struct rt_memheap *heap, rt_size_t size)
178
{
179 180 181 182 183
    rt_err_t result;
    rt_uint32_t free_size;
    struct rt_memheap_item *header_ptr;

    RT_ASSERT(heap != RT_NULL);
184
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);
185 186 187 188 189 190

    /* align allocated size */
    size = RT_ALIGN(size, RT_ALIGN_SIZE);
    if (size < RT_MEMHEAP_MINIALLOC)
        size = RT_MEMHEAP_MINIALLOC;

191 192
    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("allocate %d on heap:%8.*s",
                                    size, RT_NAME_MAX, heap->parent.name));
193 194 195 196 197 198 199

    if (size < heap->available_size)
    {
        /* search on free list */
        free_size = 0;

        /* lock memheap */
200
        result = rt_sem_take(&(heap->lock), RT_WAITING_FOREVER);
201 202 203 204 205 206 207 208 209 210 211 212
        if (result != RT_EOK)
        {
            rt_set_errno(result);

            return RT_NULL;
        }

        /* get the first free memory block */
        header_ptr = heap->free_list->next_free;
        while (header_ptr != heap->free_list && free_size < size)
        {
            /* get current freed memory block size */
B
Bernard Xiong 已提交
213
            free_size = MEMITEM_SIZE(header_ptr);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
            if (free_size < size)
            {
                /* move to next free memory block */
                header_ptr = header_ptr->next_free;
            }
        }

        /* determine if the memory is available. */
        if (free_size >= size)
        {
            /* a block that satisfies the request has been found. */

            /* determine if the block needs to be split. */
            if (free_size >= (size + RT_MEMHEAP_SIZE + RT_MEMHEAP_MINIALLOC))
            {
                struct rt_memheap_item *new_ptr;

                /* split the block. */
                new_ptr = (struct rt_memheap_item *)
                          (((rt_uint8_t *)header_ptr) + size + RT_MEMHEAP_SIZE);

                RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
236
                             ("split: block[0x%08x] nextm[0x%08x] prevm[0x%08x] to new[0x%08x]\n",
237 238 239 240
                              header_ptr,
                              header_ptr->next,
                              header_ptr->prev,
                              new_ptr));
241

242
                /* mark the new block as a memory block and freed. */
243
                new_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

                /* put the pool pointer into the new block. */
                new_ptr->pool_ptr = heap;

                /* break down the block list */
                new_ptr->prev          = header_ptr;
                new_ptr->next          = header_ptr->next;
                header_ptr->next->prev = new_ptr;
                header_ptr->next       = new_ptr;

                /* remove header ptr from free list */
                header_ptr->next_free->prev_free = header_ptr->prev_free;
                header_ptr->prev_free->next_free = header_ptr->next_free;
                header_ptr->next_free = RT_NULL;
                header_ptr->prev_free = RT_NULL;

                /* insert new_ptr to free list */
                new_ptr->next_free = heap->free_list->next_free;
                new_ptr->prev_free = heap->free_list;
                heap->free_list->next_free->prev_free = new_ptr;
                heap->free_list->next_free            = new_ptr;
265
                RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("new ptr: next_free 0x%08x, prev_free 0x%08x\n",
266 267
                                                new_ptr->next_free,
                                                new_ptr->prev_free));
268

269 270 271 272
                /* decrement the available byte count.  */
                heap->available_size = heap->available_size -
                                       size -
                                       RT_MEMHEAP_SIZE;
273 274
                if (heap->pool_size - heap->available_size > heap->max_used_size)
                    heap->max_used_size = heap->pool_size - heap->available_size;
275 276 277 278 279
            }
            else
            {
                /* decrement the entire free size from the available bytes count. */
                heap->available_size = heap->available_size - free_size;
280 281
                if (heap->pool_size - heap->available_size > heap->max_used_size)
                    heap->max_used_size = heap->pool_size - heap->available_size;
282 283 284

                /* remove header_ptr from free list */
                RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
285
                             ("one block: block[0x%08x], next_free 0x%08x, prev_free 0x%08x\n",
286 287 288
                              header_ptr,
                              header_ptr->next_free,
                              header_ptr->prev_free));
289

290 291 292 293 294
                header_ptr->next_free->prev_free = header_ptr->prev_free;
                header_ptr->prev_free->next_free = header_ptr->next_free;
                header_ptr->next_free = RT_NULL;
                header_ptr->prev_free = RT_NULL;
            }
295

296
            /* Mark the allocated block as not available. */
297
            header_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED);
298

299 300 301
            /* release lock */
            rt_sem_release(&(heap->lock));

302 303
            /* Return a memory address to the caller.  */
            RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
304
                         ("alloc mem: memory[0x%08x], heap[0x%08x], size: %d\n",
305 306
                          (void *)((rt_uint8_t *)header_ptr + RT_MEMHEAP_SIZE),
                          header_ptr,
307
                          size));
308

309
            return (void *)((rt_uint8_t *)header_ptr + RT_MEMHEAP_SIZE);
310
        }
311

312
        /* release lock */
313
        rt_sem_release(&(heap->lock));
314
    }
315

316
    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("allocate memory: failed\n"));
317 318 319 320

    /* Return the completion status.  */
    return RT_NULL;
}
321
RTM_EXPORT(rt_memheap_alloc);
322

Y
yiyue.fang 已提交
323
void *rt_memheap_realloc(struct rt_memheap *heap, void *ptr, rt_size_t newsize)
B
Bernard Xiong 已提交
324
{
B
Bernard Xiong 已提交
325
    rt_err_t result;
Y
yiyue.fang 已提交
326 327 328 329
    rt_size_t oldsize;
    struct rt_memheap_item *header_ptr;
    struct rt_memheap_item *new_ptr;

330 331 332
    RT_ASSERT(heap);
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);

Y
yiyue.fang 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    if (newsize == 0)
    {
        rt_memheap_free(ptr);

        return RT_NULL;
    }
    /* align allocated size */
    newsize = RT_ALIGN(newsize, RT_ALIGN_SIZE);
    if (newsize < RT_MEMHEAP_MINIALLOC)
        newsize = RT_MEMHEAP_MINIALLOC;

    if (ptr == RT_NULL)
    {
        return rt_memheap_alloc(heap, newsize);
    }

    /* get memory block header and get the size of memory block */
    header_ptr = (struct rt_memheap_item *)
                 ((rt_uint8_t *)ptr - RT_MEMHEAP_SIZE);
    oldsize = MEMITEM_SIZE(header_ptr);
353
    /* re-allocate memory */
B
Bernard Xiong 已提交
354 355
    if (newsize > oldsize)
    {
356
        void *new_ptr;
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        struct rt_memheap_item *next_ptr;

        /* lock memheap */
        result = rt_sem_take(&(heap->lock), RT_WAITING_FOREVER);
        if (result != RT_EOK)
        {
            rt_set_errno(result);
            return RT_NULL;
        }

        next_ptr = header_ptr->next;

        /* header_ptr should not be the tail */
        RT_ASSERT(next_ptr > header_ptr);

        /* check whether the following free space is enough to expand */
        if (!RT_MEMHEAP_IS_USED(next_ptr))
        {
            rt_int32_t nextsize;

            nextsize = MEMITEM_SIZE(next_ptr);
            RT_ASSERT(next_ptr > 0);

            /* Here is the ASCII art of the situation that we can make use of
             * the next free node without alloc/memcpy, |*| is the control
             * block:
             *
             *      oldsize           free node
             * |*|-----------|*|----------------------|*|
             *         newsize          >= minialloc
             * |*|----------------|*|-----------------|*|
             */
            if (nextsize + oldsize > newsize + RT_MEMHEAP_MINIALLOC)
            {
                /* decrement the entire free size from the available bytes count. */
                heap->available_size = heap->available_size - (newsize - oldsize);
                if (heap->pool_size - heap->available_size > heap->max_used_size)
                    heap->max_used_size = heap->pool_size - heap->available_size;

                /* remove next_ptr from free list */
                RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
                             ("remove block: block[0x%08x], next_free 0x%08x, prev_free 0x%08x",
                              next_ptr,
                              next_ptr->next_free,
                              next_ptr->prev_free));

                next_ptr->next_free->prev_free = next_ptr->prev_free;
                next_ptr->prev_free->next_free = next_ptr->next_free;
                next_ptr->next->prev = next_ptr->prev;
                next_ptr->prev->next = next_ptr->next;

                /* build a new one on the right place */
409
                next_ptr = (struct rt_memheap_item *)((char *)ptr + newsize);
410 411 412 413 414 415 416 417

                RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
                             ("new free block: block[0x%08x] nextm[0x%08x] prevm[0x%08x]",
                              next_ptr,
                              next_ptr->next,
                              next_ptr->prev));

                /* mark the new block as a memory block and freed. */
418
                next_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

                /* put the pool pointer into the new block. */
                next_ptr->pool_ptr = heap;

                next_ptr->prev          = header_ptr;
                next_ptr->next          = header_ptr->next;
                header_ptr->next->prev = next_ptr;
                header_ptr->next       = next_ptr;

                /* insert next_ptr to free list */
                next_ptr->next_free = heap->free_list->next_free;
                next_ptr->prev_free = heap->free_list;
                heap->free_list->next_free->prev_free = next_ptr;
                heap->free_list->next_free            = next_ptr;
                RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("new ptr: next_free 0x%08x, prev_free 0x%08x",
                                                next_ptr->next_free,
                                                next_ptr->prev_free));

                /* release lock */
                rt_sem_release(&(heap->lock));

                return ptr;
            }
        }

        /* release lock */
        rt_sem_release(&(heap->lock));

B
Bernard Xiong 已提交
447
        /* re-allocate a memory block */
448
        new_ptr = (void *)rt_memheap_alloc(heap, newsize);
B
Bernard Xiong 已提交
449 450 451 452 453
        if (new_ptr != RT_NULL)
        {
            rt_memcpy(new_ptr, ptr, oldsize < newsize ? oldsize : newsize);
            rt_memheap_free(ptr);
        }
B
Bernard Xiong 已提交
454

B
Bernard Xiong 已提交
455 456 457
        return new_ptr;
    }

458 459 460 461
    /* don't split when there is less than one node space left */
    if (newsize + RT_MEMHEAP_SIZE + RT_MEMHEAP_MINIALLOC >= oldsize)
        return ptr;

Y
yiyue.fang 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475
    /* lock memheap */
    result = rt_sem_take(&(heap->lock), RT_WAITING_FOREVER);
    if (result != RT_EOK)
    {
        rt_set_errno(result);

        return RT_NULL;
    }

    /* split the block. */
    new_ptr = (struct rt_memheap_item *)
              (((rt_uint8_t *)header_ptr) + newsize + RT_MEMHEAP_SIZE);

    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
476
                 ("split: block[0x%08x] nextm[0x%08x] prevm[0x%08x] to new[0x%08x]\n",
Y
yiyue.fang 已提交
477 478 479 480 481 482
                  header_ptr,
                  header_ptr->next,
                  header_ptr->prev,
                  new_ptr));

    /* mark the new block as a memory block and freed. */
483
    new_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
Y
yiyue.fang 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    /* put the pool pointer into the new block. */
    new_ptr->pool_ptr = heap;

    /* break down the block list */
    new_ptr->prev          = header_ptr;
    new_ptr->next          = header_ptr->next;
    header_ptr->next->prev = new_ptr;
    header_ptr->next       = new_ptr;

    /* determine if the block can be merged with the next neighbor. */
    if (!RT_MEMHEAP_IS_USED(new_ptr->next))
    {
        struct rt_memheap_item *free_ptr;

        /* merge block with next neighbor. */
        free_ptr = new_ptr->next;
        heap->available_size = heap->available_size - MEMITEM_SIZE(free_ptr);

        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
503
                     ("merge: right node 0x%08x, next_free 0x%08x, prev_free 0x%08x\n",
Y
yiyue.fang 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
                      header_ptr, header_ptr->next_free, header_ptr->prev_free));

        free_ptr->next->prev = new_ptr;
        new_ptr->next   = free_ptr->next;

        /* remove free ptr from free list */
        free_ptr->next_free->prev_free = free_ptr->prev_free;
        free_ptr->prev_free->next_free = free_ptr->next_free;
    }

    /* insert the split block to free list */
    new_ptr->next_free = heap->free_list->next_free;
    new_ptr->prev_free = heap->free_list;
    heap->free_list->next_free->prev_free = new_ptr;
    heap->free_list->next_free            = new_ptr;
519
    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("new free ptr: next_free 0x%08x, prev_free 0x%08x\n",
Y
yiyue.fang 已提交
520 521 522 523 524
                                    new_ptr->next_free,
                                    new_ptr->prev_free));

    /* increment the available byte count.  */
    heap->available_size = heap->available_size + MEMITEM_SIZE(new_ptr);
B
Bernard Xiong 已提交
525 526 527 528

    /* release lock */
    rt_sem_release(&(heap->lock));

Y
yiyue.fang 已提交
529 530
    /* return the old memory block */
    return ptr;
B
Bernard Xiong 已提交
531 532 533
}
RTM_EXPORT(rt_memheap_realloc);

534
void rt_memheap_free(void *ptr)
535
{
536 537 538 539 540
    rt_err_t result;
    struct rt_memheap *heap;
    struct rt_memheap_item *header_ptr, *new_ptr;
    rt_uint32_t insert_header;

541 542
    /* NULL check */
    if (ptr == RT_NULL) return;
543

544 545 546
    /* set initial status as OK */
    insert_header = 1;
    new_ptr       = RT_NULL;
Y
yiyue.fang 已提交
547 548
    header_ptr    = (struct rt_memheap_item *)
                    ((rt_uint8_t *)ptr - RT_MEMHEAP_SIZE);
549

550
    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("free memory: memory[0x%08x], block[0x%08x]\n",
551
                                    ptr, header_ptr));
552

553
    /* check magic */
554 555
    if (header_ptr->magic != (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED))
    {
556 557
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("bad magic:0x%08x @ memheap\n",
                                        header_ptr->magic));
558 559
    }
    RT_ASSERT(header_ptr->magic == (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED));
560 561
    /* check whether this block of memory has been over-written. */
    RT_ASSERT((header_ptr->next->magic & RT_MEMHEAP_MASK) == RT_MEMHEAP_MAGIC);
562 563 564

    /* get pool ptr */
    heap = header_ptr->pool_ptr;
565

566 567 568
    RT_ASSERT(heap);
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);

569
    /* lock memheap */
570
    result = rt_sem_take(&(heap->lock), RT_WAITING_FOREVER);
571 572 573
    if (result != RT_EOK)
    {
        rt_set_errno(result);
Y
yiyue.fang 已提交
574

575 576
        return ;
    }
577

578
    /* Mark the memory as available. */
579
    header_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
580
    /* Adjust the available number of bytes. */
581
    heap->available_size += MEMITEM_SIZE(header_ptr);
582

583 584 585
    /* Determine if the block can be merged with the previous neighbor. */
    if (!RT_MEMHEAP_IS_USED(header_ptr->prev))
    {
586
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("merge: left node 0x%08x\n",
587
                                        header_ptr->prev));
588

589
        /* adjust the available number of bytes. */
590
        heap->available_size += RT_MEMHEAP_SIZE;
591

592 593 594
        /* yes, merge block with previous neighbor. */
        (header_ptr->prev)->next = header_ptr->next;
        (header_ptr->next)->prev = header_ptr->prev;
595

596 597 598 599 600
        /* move header pointer to previous. */
        header_ptr = header_ptr->prev;
        /* don't insert header to free list */
        insert_header = 0;
    }
601

602 603 604 605
    /* determine if the block can be merged with the next neighbor. */
    if (!RT_MEMHEAP_IS_USED(header_ptr->next))
    {
        /* adjust the available number of bytes. */
606
        heap->available_size += RT_MEMHEAP_SIZE;
607

608 609
        /* merge block with next neighbor. */
        new_ptr = header_ptr->next;
610

611
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
612
                     ("merge: right node 0x%08x, next_free 0x%08x, prev_free 0x%08x\n",
613
                      new_ptr, new_ptr->next_free, new_ptr->prev_free));
614

615 616
        new_ptr->next->prev = header_ptr;
        header_ptr->next    = new_ptr->next;
617

618 619 620 621
        /* remove new ptr from free list */
        new_ptr->next_free->prev_free = new_ptr->prev_free;
        new_ptr->prev_free->next_free = new_ptr->next_free;
    }
622

623 624 625 626 627 628 629
    if (insert_header)
    {
        /* no left merge, insert to free list */
        header_ptr->next_free = heap->free_list->next_free;
        header_ptr->prev_free = heap->free_list;
        heap->free_list->next_free->prev_free = header_ptr;
        heap->free_list->next_free            = header_ptr;
630

631
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
632
                     ("insert to free list: next_free 0x%08x, prev_free 0x%08x\n",
633
                      header_ptr->next_free, header_ptr->prev_free));
634
    }
635

636
    /* release lock */
637
    rt_sem_release(&(heap->lock));
638
}
639
RTM_EXPORT(rt_memheap_free);
640

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
#ifdef RT_USING_FINSH
static void _memheap_dump_tag(struct rt_memheap_item* item)
{
    rt_uint8_t name[2 * sizeof(void*)];
    rt_uint8_t* ptr;

    ptr = (rt_uint8_t*)&(item->next_free);
    rt_memcpy(name, ptr, sizeof(void*));
    ptr = (rt_uint8_t*)&(item->prev_free);
    rt_memcpy(&name[sizeof(void*)], ptr, sizeof(void*));

    rt_kprintf("%.*s", 2 * sizeof(void*), name);
}

int rt_memheap_dump(struct rt_memheap *heap)
{
    struct rt_memheap_item *item, *end;

    if (heap == RT_NULL) return 0;
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);

    rt_kprintf("\n[%.*s] [0x%08x - 0x%08x]->\n", RT_NAME_MAX, heap->parent.name, 
        (rt_ubase_t)heap->start_addr, (rt_ubase_t)heap->start_addr + heap->pool_size);
    rt_kprintf("------------------------------\n");

    /* lock memheap */
    rt_sem_take(&(heap->lock), RT_WAITING_FOREVER);
    item = heap->block_list;

    end = (struct rt_memheap_item *) ((rt_uint8_t *)heap->start_addr + heap->pool_size - RT_MEMHEAP_SIZE);

    /* for each memory block */
    while ((rt_ubase_t)item < ((rt_ubase_t)end))
    {
        if (RT_MEMHEAP_IS_USED(item) && ((item->magic & RT_MEMHEAP_MASK) != RT_MEMHEAP_MAGIC))
            rt_kprintf("0x%08x", item + 1);

        if (item->magic == (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED))
        {
            rt_kprintf("0x%08x: %-8d ",     item + 1, MEMITEM_SIZE(item));
            _memheap_dump_tag(item);
            rt_kprintf("\n");
        }
        else
        {
            rt_kprintf("0x%08x: %-8d <F>\n", item + 1, MEMITEM_SIZE(item));
        }

        item = item->next;
    }
    rt_sem_release(&(heap->lock));

    return 0;
}

int memtrace(void)
{
    int count = rt_object_get_length(RT_Object_Class_MemHeap);
    struct rt_memheap **heaps;

    if (count > 0)
    {
        int index;
        extern int list_memheap(void);

        heaps = (struct rt_memheap**)rt_malloc(sizeof(struct rt_memheap*) * count);
        if (heaps == RT_NULL) return 0;

        list_memheap();

        rt_kprintf("memheap header size: %d\n", RT_MEMHEAP_SIZE);
        count = rt_object_get_pointers(RT_Object_Class_MemHeap, (rt_object_t*)heaps, count);
        for (index = 0; index < count; index++)
        {
            rt_memheap_dump(heaps[index]);
        }

        rt_free(heaps);
    }

    return 0;
}
MSH_CMD_EXPORT(memtrace, dump memory trace information);
#endif

726 727 728 729 730
#ifdef RT_USING_MEMHEAP_AS_HEAP
static struct rt_memheap _heap;

void rt_system_heap_init(void *begin_addr, void *end_addr)
{
731 732 733 734 735
    /* initialize a default heap in the system */
    rt_memheap_init(&_heap,
                    "heap",
                    begin_addr,
                    (rt_uint32_t)end_addr - (rt_uint32_t)begin_addr);
736 737 738 739
}

void *rt_malloc(rt_size_t size)
{
740
    void *ptr;
B
Bernard Xiong 已提交
741

742 743 744 745 746 747 748 749 750 751
    /* try to allocate in system heap */
    ptr = rt_memheap_alloc(&_heap, size);
    if (ptr == RT_NULL)
    {
        struct rt_object *object;
        struct rt_list_node *node;
        struct rt_memheap *heap;
        struct rt_object_information *information;

        /* try to allocate on other memory heap */
752 753
        information = rt_object_get_information(RT_Object_Class_MemHeap);
        RT_ASSERT(information != RT_NULL);
754 755 756 757 758 759 760
        for (node  = information->object_list.next;
             node != &(information->object_list);
             node  = node->next)
        {
            object = rt_list_entry(node, struct rt_object, list);
            heap   = (struct rt_memheap *)object;

761 762 763
            RT_ASSERT(heap);
            RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);

764 765 766 767 768 769 770 771 772 773
            /* not allocate in the default system heap */
            if (heap == &_heap)
                continue;

            ptr = rt_memheap_alloc(heap, size);
            if (ptr != RT_NULL)
                break;
        }
    }

774 775 776 777

#ifdef RT_USING_MEMTRACE
    if (ptr == RT_NULL)
    {
778
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("malloc[%d] => NULL", size));
779 780 781 782 783 784 785 786 787
    }
    else
    {
        struct rt_memheap_item *item = MEMITEM(ptr);
        if (rt_thread_self())
            rt_memheap_setname(item, rt_thread_self()->name);
        else
            rt_memheap_setname(item, "<null>");

788
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("malloc => 0x%08x : %d", ptr, size));
789 790 791
    }
#endif

792
    return ptr;
793 794 795 796 797
}
RTM_EXPORT(rt_malloc);

void rt_free(void *rmem)
{
798
    rt_memheap_free(rmem);
799 800 801 802 803
}
RTM_EXPORT(rt_free);

void *rt_realloc(void *rmem, rt_size_t newsize)
{
Y
yiyue.fang 已提交
804
    void *new_ptr;
805 806
    struct rt_memheap_item *header_ptr;

Y
yiyue.fang 已提交
807 808
    if (rmem == RT_NULL)
        return rt_malloc(newsize);
809

810 811 812 813 814 815
    if (newsize == 0)
    {
        rt_free(rmem);
        return RT_NULL;
    }

816
    /* get old memory item */
Y
yiyue.fang 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    header_ptr = (struct rt_memheap_item *)
                 ((rt_uint8_t *)rmem - RT_MEMHEAP_SIZE);

    new_ptr = rt_memheap_realloc(header_ptr->pool_ptr, rmem, newsize);
    if (new_ptr == RT_NULL && newsize != 0)
    {
        /* allocate memory block from other memheap */
        new_ptr = rt_malloc(newsize);
        if (new_ptr != RT_NULL && rmem != RT_NULL)
        {
            rt_size_t oldsize;

            /* get the size of old memory block */
            oldsize = MEMITEM_SIZE(header_ptr);
            if (newsize > oldsize)
                rt_memcpy(new_ptr, rmem, oldsize);
            else
                rt_memcpy(new_ptr, rmem, newsize);
835 836

            rt_free(rmem);
Y
yiyue.fang 已提交
837 838 839
        }
    }

840 841 842
#ifdef RT_USING_MEMTRACE
    if (new_ptr == RT_NULL)
    {
843
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("realloc[%d] => NULL", newsize));
844 845 846 847 848 849 850 851 852
    }
    else
    {
        struct rt_memheap_item *item = MEMITEM(new_ptr);
        if (rt_thread_self())
            rt_memheap_setname(item, rt_thread_self()->name);
        else
            rt_memheap_setname(item, "<null>");

853 854
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("realloc => 0x%08x : %d",
                                        new_ptr, newsize));
855 856 857
    }
#endif

Y
yiyue.fang 已提交
858
    return new_ptr;
859 860 861 862 863
}
RTM_EXPORT(rt_realloc);

void *rt_calloc(rt_size_t count, rt_size_t size)
{
864 865 866 867 868 869 870 871 872 873 874
    void *ptr;
    rt_size_t total_size;

    total_size = count * size;
    ptr = rt_malloc(total_size);
    if (ptr != RT_NULL)
    {
        /* clean memory */
        rt_memset(ptr, 0, total_size);
    }

875 876 877
#ifdef RT_USING_MEMTRACE
    if (ptr == RT_NULL)
    {
878 879
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("calloc[%d x %d] => NULL",
                                        count, size));
880 881 882
    }
    else
    {
883 884
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("calloc => 0x%08x : %d",
                                        ptr, count * size));
885 886 887
    }
#endif

888
    return ptr;
889 890 891
}
RTM_EXPORT(rt_calloc);

U
unknown 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905
void rt_memory_info(rt_uint32_t *total,
                    rt_uint32_t *used,
                    rt_uint32_t *max_used)
{
    if (total != RT_NULL)
        *total = _heap.pool_size;

    if (used  != RT_NULL)
        *used = _heap.pool_size - _heap.available_size;

    if (max_used != RT_NULL)
        *max_used = _heap.max_used_size;
}

906 907
#endif

908
#endif