memheap.c 36.3 KB
Newer Older
1
/*
mysterywolf's avatar
mysterywolf 已提交
2
 * Copyright (c) 2006-2021, 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
 * 2021-06-03     Flybreak     Fix the crash problem after opening Oz optimization on ac6.
21
 */
22

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

#ifdef RT_USING_MEMHEAP

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

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

37
#define RT_MEMHEAP_SIZE         RT_ALIGN(sizeof(struct rt_memheap_item), RT_ALIGN_SIZE)
38
#define MEMITEM_SIZE(item)      ((rt_ubase_t)item->next - (rt_ubase_t)item - RT_MEMHEAP_SIZE)
39 40 41
#define MEMITEM(ptr)            (struct rt_memheap_item*)((rt_uint8_t*)ptr - RT_MEMHEAP_SIZE)

#ifdef RT_USING_MEMTRACE
Nameless-Y's avatar
Nameless-Y 已提交
42 43 44 45 46 47 48
/**
 * @brief This function will set a new name for memheap.
 *
 * @param item is a pointer point to a memheap object.
 *
 * @param name is the new name to be set.
 */
49 50 51
rt_inline void rt_memheap_setname(struct rt_memheap_item *item, const char *name)
{
    int index;
G
guozhanxin 已提交
52
    rt_uint8_t *ptr;
53

G
guozhanxin 已提交
54 55
    ptr = (rt_uint8_t *) & (item->next_free);
    for (index = 0; index < sizeof(void *); index ++)
56 57 58 59 60
    {
        if (name[index] == '\0') break;
        ptr[index] = name[index];
    }
    if (name[index] == '\0') ptr[index] = '\0';
G
guozhanxin 已提交
61
    else
62
    {
G
guozhanxin 已提交
63 64
        ptr = (rt_uint8_t *) & (item->prev_free);
        for (index = 0; index < sizeof(void *) && (index + sizeof(void *)) < RT_NAME_MAX; index ++)
65
        {
G
guozhanxin 已提交
66 67
            if (name[sizeof(void *) + index] == '\0') break;
            ptr[index] = name[sizeof(void *) + index];
68 69
        }

G
guozhanxin 已提交
70
        if (name[sizeof(void *) + index] == '\0') ptr[index] = '\0';
71 72 73
    }
}

Nameless-Y's avatar
Nameless-Y 已提交
74 75 76 77 78 79 80
/**
 * @brief This function will set a new name for memheap.
 *
 * @param ptr is a pointer point to a memheap object.
 *
 * @param name is the new name to be set.
 */
G
guozhanxin 已提交
81
void rt_mem_set_tag(void *ptr, const char *name)
82
{
G
guozhanxin 已提交
83
    struct rt_memheap_item *item;
84 85 86 87 88 89 90

    if (ptr && name)
    {
        item = MEMITEM(ptr);
        rt_memheap_setname(item, name);
    }
}
91
#endif /* RT_USING_MEMTRACE */
92

Nameless-Y's avatar
Nameless-Y 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
/**
 * @brief   This function initializes a piece of memory called memheap.
 *
 * @note    The initialized memory pool will be:
 *          +-----------------------------------+--------------------------+
 *          | whole freed memory block          | Used Memory Block Tailer |
 *          +-----------------------------------+--------------------------+
 *
 *          block_list --> whole freed memory block
 *
 *          The length of Used Memory Block Tailer is 0,
 *          which is prevents block merging across list
 *
 * @param   memheap is a pointer of the memheap object.
 *
 * @param   name is the name of the memheap.
 *
 * @param   start_addr is the start address of the memheap.
111
 *
Nameless-Y's avatar
Nameless-Y 已提交
112
 * @param   size is the size of the memheap.
113
 *
Nameless-Y's avatar
Nameless-Y 已提交
114
 * @return  RT_EOK
115
 */
116 117 118
rt_err_t rt_memheap_init(struct rt_memheap *memheap,
                         const char        *name,
                         void              *start_addr,
B
Bernard Xiong 已提交
119
                         rt_size_t         size)
120
{
121
    struct rt_memheap_item *item;
122

123
    RT_ASSERT(memheap != RT_NULL);
124

125 126
    /* initialize pool object */
    rt_object_init(&(memheap->parent), RT_Object_Class_MemHeap, name);
127

128 129
    memheap->start_addr     = start_addr;
    memheap->pool_size      = RT_ALIGN_DOWN(size, RT_ALIGN_SIZE);
130
    memheap->available_size = memheap->pool_size - (2 * RT_MEMHEAP_SIZE);
131
    memheap->max_used_size  = memheap->pool_size - memheap->available_size;
132

133 134
    /* initialize the free list header */
    item            = &(memheap->free_header);
135
    item->magic     = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
136 137 138 139 140 141 142 143 144 145 146
    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;
147
    item->magic     = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
148 149 150 151 152 153
    item->pool_ptr  = memheap;
    item->next      = RT_NULL;
    item->prev      = RT_NULL;
    item->next_free = item;
    item->prev_free = item;

C
cliff-cmc 已提交
154 155
#ifdef RT_USING_MEMTRACE
    rt_memset(item->owner_thread_name, ' ', sizeof(item->owner_thread_name));
156
#endif /* RT_USING_MEMTRACE */
C
cliff-cmc 已提交
157

158
    item->next = (struct rt_memheap_item *)
159
                 ((rt_uint8_t *)item + memheap->available_size + RT_MEMHEAP_SIZE);
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    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 */
176
    item->magic     = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED);
177 178 179 180 181 182
    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;

183
    /* initialize semaphore lock */
184
    rt_sem_init(&(memheap->lock), name, 1, RT_IPC_FLAG_PRIO);
185 186

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

190
    return RT_EOK;
191
}
192
RTM_EXPORT(rt_memheap_init);
193

Nameless-Y's avatar
Nameless-Y 已提交
194 195 196 197 198 199 200
/**
 * @brief   This function will remove a memheap from the system.
 *
 * @param   heap is a pointer of memheap object.
 *
 * @return  RT_EOK
 */
201
rt_err_t rt_memheap_detach(struct rt_memheap *heap)
202
{
203
    RT_ASSERT(heap);
204 205
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);
    RT_ASSERT(rt_object_is_systemobject(&heap->parent));
mysterywolf's avatar
mysterywolf 已提交
206

Moral-Hao's avatar
Moral-Hao 已提交
207
    rt_sem_detach(&heap->lock);
208
    rt_object_detach(&(heap->parent));
209

210 211
    /* Return a successful completion. */
    return RT_EOK;
212
}
213
RTM_EXPORT(rt_memheap_detach);
214

Nameless-Y's avatar
Nameless-Y 已提交
215 216 217 218 219 220 221 222 223
/**
 * @brief  Allocate a block of memory with a minimum of 'size' bytes on memheap.
 *
 * @param   heap is a pointer for memheap object.
 *
 * @param   size is the minimum size of the requested block in bytes.
 *
 * @return  the pointer to allocated memory or NULL if no free memory was found.
 */
B
Bernard Xiong 已提交
224
void *rt_memheap_alloc(struct rt_memheap *heap, rt_size_t size)
225
{
226 227 228 229 230
    rt_err_t result;
    rt_uint32_t free_size;
    struct rt_memheap_item *header_ptr;

    RT_ASSERT(heap != RT_NULL);
231
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);
232 233 234 235 236 237

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

238 239
    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("allocate %d on heap:%8.*s",
                                    size, RT_NAME_MAX, heap->parent.name));
240 241 242 243 244 245 246

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

        /* lock memheap */
247
        result = rt_sem_take(&(heap->lock), RT_WAITING_FOREVER);
248 249 250 251 252 253 254 255 256 257 258 259
        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 已提交
260
            free_size = MEMITEM_SIZE(header_ptr);
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
            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,
283
                             ("split: block[0x%08x] nextm[0x%08x] prevm[0x%08x] to new[0x%08x]\n",
284 285 286 287
                              header_ptr,
                              header_ptr->next,
                              header_ptr->prev,
                              new_ptr));
288

289
                /* mark the new block as a memory block and freed. */
290
                new_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
291 292 293 294

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

C
cliff-cmc 已提交
295 296
#ifdef RT_USING_MEMTRACE
                rt_memset(new_ptr->owner_thread_name, ' ', sizeof(new_ptr->owner_thread_name));
297
#endif /* RT_USING_MEMTRACE */
C
cliff-cmc 已提交
298

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
                /* 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;
316
                RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("new ptr: next_free 0x%08x, prev_free 0x%08x\n",
317 318
                                                new_ptr->next_free,
                                                new_ptr->prev_free));
319

320 321 322 323
                /* decrement the available byte count.  */
                heap->available_size = heap->available_size -
                                       size -
                                       RT_MEMHEAP_SIZE;
324 325
                if (heap->pool_size - heap->available_size > heap->max_used_size)
                    heap->max_used_size = heap->pool_size - heap->available_size;
326 327 328 329 330
            }
            else
            {
                /* decrement the entire free size from the available bytes count. */
                heap->available_size = heap->available_size - free_size;
331 332
                if (heap->pool_size - heap->available_size > heap->max_used_size)
                    heap->max_used_size = heap->pool_size - heap->available_size;
333 334 335

                /* remove header_ptr from free list */
                RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
336
                             ("one block: block[0x%08x], next_free 0x%08x, prev_free 0x%08x\n",
337 338 339
                              header_ptr,
                              header_ptr->next_free,
                              header_ptr->prev_free));
340

341 342 343 344 345
                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;
            }
346

347
            /* Mark the allocated block as not available. */
348
            header_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED);
349

C
cliff-cmc 已提交
350 351 352 353 354
#ifdef RT_USING_MEMTRACE
            if (rt_thread_self())
                rt_memcpy(header_ptr->owner_thread_name, rt_thread_self()->name, sizeof(header_ptr->owner_thread_name));
            else
                rt_memcpy(header_ptr->owner_thread_name, "NONE", sizeof(header_ptr->owner_thread_name));
355
#endif /* RT_USING_MEMTRACE */
C
cliff-cmc 已提交
356

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

360 361
            /* Return a memory address to the caller.  */
            RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
362
                         ("alloc mem: memory[0x%08x], heap[0x%08x], size: %d\n",
363 364
                          (void *)((rt_uint8_t *)header_ptr + RT_MEMHEAP_SIZE),
                          header_ptr,
365
                          size));
366

367
            return (void *)((rt_uint8_t *)header_ptr + RT_MEMHEAP_SIZE);
368
        }
369

370
        /* release lock */
371
        rt_sem_release(&(heap->lock));
372
    }
373

374
    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("allocate memory: failed\n"));
375 376 377 378

    /* Return the completion status.  */
    return RT_NULL;
}
379
RTM_EXPORT(rt_memheap_alloc);
380

Nameless-Y's avatar
Nameless-Y 已提交
381 382 383 384 385 386 387 388 389 390 391 392
/**
 * @brief This function will change the size of previously allocated memory block.
 *
 * @param heap is a pointer to the memheap object, which will reallocate
 *             memory from the block
 *
 * @param ptr is a pointer to start address of memory.
 *
 * @param newsize is the required new size.
 *
 * @return the changed memory block address.
 */
Y
yiyue.fang 已提交
393
void *rt_memheap_realloc(struct rt_memheap *heap, void *ptr, rt_size_t newsize)
B
Bernard Xiong 已提交
394
{
B
Bernard Xiong 已提交
395
    rt_err_t result;
Y
yiyue.fang 已提交
396 397 398 399
    rt_size_t oldsize;
    struct rt_memheap_item *header_ptr;
    struct rt_memheap_item *new_ptr;

400 401 402
    RT_ASSERT(heap);
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);

Y
yiyue.fang 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    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);
423
    /* re-allocate memory */
B
Bernard Xiong 已提交
424 425
    if (newsize > oldsize)
    {
426
        void *new_ptr;
427 428
        /* Fix the crash problem after opening Oz optimization on ac6  */
        volatile struct rt_memheap_item *next_ptr;
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

        /* 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 */
480
                next_ptr = (struct rt_memheap_item *)((char *)ptr + newsize);
481 482 483 484 485 486 487 488

                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. */
489
                next_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
490 491 492 493

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

C
cliff-cmc 已提交
494
#ifdef RT_USING_MEMTRACE
495
                rt_memset((void *)next_ptr->owner_thread_name, ' ', sizeof(next_ptr->owner_thread_name));
496
#endif /* RT_USING_MEMTRACE */
C
cliff-cmc 已提交
497

498 499
                next_ptr->prev          = header_ptr;
                next_ptr->next          = header_ptr->next;
500 501
                header_ptr->next->prev = (struct rt_memheap_item *)next_ptr;
                header_ptr->next       = (struct rt_memheap_item *)next_ptr;
502 503 504 505

                /* insert next_ptr to free list */
                next_ptr->next_free = heap->free_list->next_free;
                next_ptr->prev_free = heap->free_list;
506 507
                heap->free_list->next_free->prev_free = (struct rt_memheap_item *)next_ptr;
                heap->free_list->next_free            = (struct rt_memheap_item *)next_ptr;
508 509 510 511 512 513 514 515 516 517 518 519 520 521
                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 已提交
522
        /* re-allocate a memory block */
523
        new_ptr = (void *)rt_memheap_alloc(heap, newsize);
B
Bernard Xiong 已提交
524 525 526 527 528
        if (new_ptr != RT_NULL)
        {
            rt_memcpy(new_ptr, ptr, oldsize < newsize ? oldsize : newsize);
            rt_memheap_free(ptr);
        }
B
Bernard Xiong 已提交
529

B
Bernard Xiong 已提交
530 531 532
        return new_ptr;
    }

533 534 535 536
    /* 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 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550
    /* 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,
551
                 ("split: block[0x%08x] nextm[0x%08x] prevm[0x%08x] to new[0x%08x]\n",
Y
yiyue.fang 已提交
552 553 554 555 556 557
                  header_ptr,
                  header_ptr->next,
                  header_ptr->prev,
                  new_ptr));

    /* mark the new block as a memory block and freed. */
558
    new_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
Y
yiyue.fang 已提交
559 560 561
    /* put the pool pointer into the new block. */
    new_ptr->pool_ptr = heap;

C
cliff-cmc 已提交
562 563
#ifdef RT_USING_MEMTRACE
    rt_memset(new_ptr->owner_thread_name, ' ', sizeof(new_ptr->owner_thread_name));
564
#endif /* RT_USING_MEMTRACE */
C
cliff-cmc 已提交
565

Y
yiyue.fang 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    /* 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,
582
                     ("merge: right node 0x%08x, next_free 0x%08x, prev_free 0x%08x\n",
Y
yiyue.fang 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
                      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;
598
    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("new free ptr: next_free 0x%08x, prev_free 0x%08x\n",
Y
yiyue.fang 已提交
599 600 601 602 603
                                    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 已提交
604 605 606 607

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

Y
yiyue.fang 已提交
608 609
    /* return the old memory block */
    return ptr;
B
Bernard Xiong 已提交
610 611 612
}
RTM_EXPORT(rt_memheap_realloc);

Nameless-Y's avatar
Nameless-Y 已提交
613 614 615 616 617 618
/**
 * @brief This function will release the allocated memory block by
 *        rt_malloc. The released memory block is taken back to system heap.
 *
 * @param ptr the address of memory which will be released.
 */
619
void rt_memheap_free(void *ptr)
620
{
621 622 623 624 625
    rt_err_t result;
    struct rt_memheap *heap;
    struct rt_memheap_item *header_ptr, *new_ptr;
    rt_uint32_t insert_header;

626 627
    /* NULL check */
    if (ptr == RT_NULL) return;
628

629 630 631
    /* set initial status as OK */
    insert_header = 1;
    new_ptr       = RT_NULL;
Y
yiyue.fang 已提交
632 633
    header_ptr    = (struct rt_memheap_item *)
                    ((rt_uint8_t *)ptr - RT_MEMHEAP_SIZE);
634

635
    RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("free memory: memory[0x%08x], block[0x%08x]\n",
636
                                    ptr, header_ptr));
637

638
    /* check magic */
639 640
    if (header_ptr->magic != (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED))
    {
641 642
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("bad magic:0x%08x @ memheap\n",
                                        header_ptr->magic));
643 644
    }
    RT_ASSERT(header_ptr->magic == (RT_MEMHEAP_MAGIC | RT_MEMHEAP_USED));
645 646
    /* check whether this block of memory has been over-written. */
    RT_ASSERT((header_ptr->next->magic & RT_MEMHEAP_MASK) == RT_MEMHEAP_MAGIC);
647 648 649

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

651 652 653
    RT_ASSERT(heap);
    RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);

654
    /* lock memheap */
655
    result = rt_sem_take(&(heap->lock), RT_WAITING_FOREVER);
656 657 658
    if (result != RT_EOK)
    {
        rt_set_errno(result);
Y
yiyue.fang 已提交
659

660 661
        return ;
    }
662

663
    /* Mark the memory as available. */
664
    header_ptr->magic = (RT_MEMHEAP_MAGIC | RT_MEMHEAP_FREED);
665
    /* Adjust the available number of bytes. */
666
    heap->available_size += MEMITEM_SIZE(header_ptr);
667

668 669 670
    /* Determine if the block can be merged with the previous neighbor. */
    if (!RT_MEMHEAP_IS_USED(header_ptr->prev))
    {
671
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("merge: left node 0x%08x\n",
672
                                        header_ptr->prev));
673

674
        /* adjust the available number of bytes. */
675
        heap->available_size += RT_MEMHEAP_SIZE;
676

677 678 679
        /* yes, merge block with previous neighbor. */
        (header_ptr->prev)->next = header_ptr->next;
        (header_ptr->next)->prev = header_ptr->prev;
680

681 682 683 684 685
        /* move header pointer to previous. */
        header_ptr = header_ptr->prev;
        /* don't insert header to free list */
        insert_header = 0;
    }
686

687 688 689 690
    /* 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. */
691
        heap->available_size += RT_MEMHEAP_SIZE;
692

693 694
        /* merge block with next neighbor. */
        new_ptr = header_ptr->next;
695

696
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
697
                     ("merge: right node 0x%08x, next_free 0x%08x, prev_free 0x%08x\n",
698
                      new_ptr, new_ptr->next_free, new_ptr->prev_free));
699

700 701
        new_ptr->next->prev = header_ptr;
        header_ptr->next    = new_ptr->next;
702

703 704 705 706
        /* 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;
    }
707

708 709 710 711 712 713 714
    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;
715

716
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP,
717
                     ("insert to free list: next_free 0x%08x, prev_free 0x%08x\n",
718
                      header_ptr->next_free, header_ptr->prev_free));
719
    }
720

C
cliff-cmc 已提交
721 722
#ifdef RT_USING_MEMTRACE
    rt_memset(header_ptr->owner_thread_name, ' ', sizeof(header_ptr->owner_thread_name));
723
#endif /* RT_USING_MEMTRACE */
C
cliff-cmc 已提交
724

725
    /* release lock */
726
    rt_sem_release(&(heap->lock));
727
}
728
RTM_EXPORT(rt_memheap_free);
729

730
#ifdef RT_USING_FINSH
G
guozhanxin 已提交
731
static void _memheap_dump_tag(struct rt_memheap_item *item)
732
{
G
guozhanxin 已提交
733 734
    rt_uint8_t name[2 * sizeof(void *)];
    rt_uint8_t *ptr;
735

G
guozhanxin 已提交
736 737 738 739
    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 *));
740

G
guozhanxin 已提交
741
    rt_kprintf("%.*s", 2 * sizeof(void *), name);
742
}
Nameless-Y's avatar
Nameless-Y 已提交
743 744 745 746 747 748 749
/**
 * @brief   This function will print the memheap infomation.
 *
 * @param   heap is the pointer  to the memheap to get information.
 *
 * @return  0
 */
750 751 752 753 754 755 756
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);

G
guozhanxin 已提交
757 758
    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);
759 760 761 762 763 764
    rt_kprintf("------------------------------\n");

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

G
guozhanxin 已提交
765
    end = (struct rt_memheap_item *)((rt_uint8_t *)heap->start_addr + heap->pool_size - RT_MEMHEAP_SIZE);
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790

    /* 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;
}

791
int memheaptrace(void)
792 793 794 795 796 797 798
{
    int count = rt_object_get_length(RT_Object_Class_MemHeap);
    struct rt_memheap **heaps;

    if (count > 0)
    {
        int index;
799
#if defined(RT_USING_FINSH) && defined(MSH_USING_BUILT_IN_COMMANDS)
800
        extern int list_memheap(void);
801
#endif
802

G
guozhanxin 已提交
803
        heaps = (struct rt_memheap **)rt_malloc(sizeof(struct rt_memheap *) * count);
804
        if (heaps == RT_NULL) return 0;
805
#if defined(RT_USING_FINSH) && defined(MSH_USING_BUILT_IN_COMMANDS)
806
        list_memheap();
807
#endif
808
        rt_kprintf("memheap header size: %d\n", RT_MEMHEAP_SIZE);
G
guozhanxin 已提交
809
        count = rt_object_get_pointers(RT_Object_Class_MemHeap, (rt_object_t *)heaps, count);
810 811 812 813 814 815 816 817 818 819
        for (index = 0; index < count; index++)
        {
            rt_memheap_dump(heaps[index]);
        }

        rt_free(heaps);
    }

    return 0;
}
820
MSH_CMD_EXPORT(memheaptrace, dump memory trace information);
821
#endif /* RT_USING_FINSH */
822

823 824 825
#ifdef RT_USING_MEMHEAP_AS_HEAP
static struct rt_memheap _heap;

Nameless-Y's avatar
Nameless-Y 已提交
826 827 828 829 830 831 832
/**
 * @brief   This function initializes a heap for system.
 *
 * @param   begin_addr is the start address of the memory.
 *
 * @param   end_addr is the end address of the memory.
 */
833 834
void rt_system_heap_init(void *begin_addr, void *end_addr)
{
835 836
    RT_ASSERT((rt_uint32_t)end_addr > (rt_uint32_t)begin_addr);

837 838 839 840 841
    /* initialize a default heap in the system */
    rt_memheap_init(&_heap,
                    "heap",
                    begin_addr,
                    (rt_uint32_t)end_addr - (rt_uint32_t)begin_addr);
842 843
}

Nameless-Y's avatar
Nameless-Y 已提交
844 845 846 847 848
/**
 * @brief Allocate a block of memory with a minimum of 'size' bytes.
 *
 * @param size is the minimum size of the requested block in bytes.
 */
849 850
void *rt_malloc(rt_size_t size)
{
851
    void *ptr;
B
Bernard Xiong 已提交
852

853 854 855 856 857 858 859 860 861 862
    /* 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 */
863 864
        information = rt_object_get_information(RT_Object_Class_MemHeap);
        RT_ASSERT(information != RT_NULL);
865 866 867 868 869 870 871
        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;

872 873 874
            RT_ASSERT(heap);
            RT_ASSERT(rt_object_get_type(&heap->parent) == RT_Object_Class_MemHeap);

875 876 877 878 879 880 881 882 883 884
            /* not allocate in the default system heap */
            if (heap == &_heap)
                continue;

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

885 886 887
#ifdef RT_USING_MEMTRACE
    if (ptr == RT_NULL)
    {
888
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("malloc[%d] => NULL", size));
889 890 891 892 893 894 895 896 897
    }
    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>");

898
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("malloc => 0x%08x : %d", ptr, size));
899
    }
900
#endif /* RT_USING_MEMTRACE */
901

902
    return ptr;
903 904 905
}
RTM_EXPORT(rt_malloc);

Nameless-Y's avatar
Nameless-Y 已提交
906 907 908 909 910 911
/**
 * @brief This function will release the previously allocated memory block by
 *        rt_malloc. The released memory block is taken back to system heap.
 *
 * @param rmem the address of memory which will be released.
 */
912 913
void rt_free(void *rmem)
{
914
    rt_memheap_free(rmem);
915 916 917
}
RTM_EXPORT(rt_free);

Nameless-Y's avatar
Nameless-Y 已提交
918 919 920 921 922 923 924 925 926
/**
 * @brief This function will change the size of previously allocated memory block.
 *
 * @param rmem is the pointer to memory allocated by rt_malloc.
 *
 * @param newsize is the required new size.
 *
 * @return the changed memory block address.
 */
927 928
void *rt_realloc(void *rmem, rt_size_t newsize)
{
Y
yiyue.fang 已提交
929
    void *new_ptr;
930 931
    struct rt_memheap_item *header_ptr;

Y
yiyue.fang 已提交
932 933
    if (rmem == RT_NULL)
        return rt_malloc(newsize);
934

935 936 937 938 939 940
    if (newsize == 0)
    {
        rt_free(rmem);
        return RT_NULL;
    }

941
    /* get old memory item */
Y
yiyue.fang 已提交
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
    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);
960 961

            rt_free(rmem);
Y
yiyue.fang 已提交
962 963 964
        }
    }

965 966 967
#ifdef RT_USING_MEMTRACE
    if (new_ptr == RT_NULL)
    {
968
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("realloc[%d] => NULL", newsize));
969 970 971 972 973 974 975 976 977
    }
    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>");

978 979
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("realloc => 0x%08x : %d",
                                        new_ptr, newsize));
980
    }
981
#endif /* RT_USING_MEMTRACE */
982

Y
yiyue.fang 已提交
983
    return new_ptr;
984 985 986
}
RTM_EXPORT(rt_realloc);

Nameless-Y's avatar
Nameless-Y 已提交
987 988 989 990 991 992 993 994 995 996 997 998 999
/**
 * @brief  This function will contiguously allocate enough space for count objects
 *         that are size bytes of memory each and returns a pointer to the allocated
 *         memory.
 *
 * @note   The allocated memory is filled with bytes of value zero.
 *
 * @param  count is the number of objects to allocate.
 *
 * @param  size is the size of one object to allocate.
 *
 * @return pointer to allocated memory pointer.
 */
1000 1001
void *rt_calloc(rt_size_t count, rt_size_t size)
{
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    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);
    }

1013 1014 1015
#ifdef RT_USING_MEMTRACE
    if (ptr == RT_NULL)
    {
1016 1017
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("calloc[%d x %d] => NULL",
                                        count, size));
1018 1019 1020
    }
    else
    {
1021 1022
        RT_DEBUG_LOG(RT_DEBUG_MEMHEAP, ("calloc => 0x%08x : %d",
                                        ptr, count * size));
1023
    }
1024
#endif /* RT_USING_MEMTRACE */
1025

1026
    return ptr;
1027 1028 1029
}
RTM_EXPORT(rt_calloc);

Nameless-Y's avatar
Nameless-Y 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
/**
* @brief This function will caculate the total memory, the used memory, and
*        the max used memory.
*
* @param total is a pointer to get the total size of the memory.
*
* @param used is a pointer to get the size of memory used.
*
* @param max_used is a pointer to get the maximum memory used.
*/
U
unknown 已提交
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
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;
}
1053

1054
#endif /* RT_USING_MEMHEAP_AS_HEAP */
1055

C
cliff-cmc 已提交
1056 1057
#ifdef RT_USING_MEMTRACE

Nameless-Y's avatar
Nameless-Y 已提交
1058 1059 1060 1061 1062
/**
 * @brief  This function will print the used memheap infomation.
 *
 * @param  memheap is a pointer of the memheap object.
 */
C
cliff-cmc 已提交
1063 1064 1065 1066 1067 1068 1069
void dump_used_memheap(struct rt_memheap *mh)
{
    struct rt_memheap_item *header_ptr;
    rt_uint32_t block_size;

    rt_kprintf("\nmemory heap address:\n");
    rt_kprintf("heap_ptr: 0x%08x\n", mh->start_addr);
mysterywolf's avatar
mysterywolf 已提交
1070
    rt_kprintf("free    : 0x%08x\n", mh->available_size);
C
cliff-cmc 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
    rt_kprintf("max_used: 0x%08x\n", mh->max_used_size);
    rt_kprintf("size    : 0x%08x\n", mh->pool_size);

    rt_kprintf("\n--memory used information --\n");

    header_ptr = mh->block_list;
    while (header_ptr->next != mh->block_list)
    {
        if ((header_ptr->magic & RT_MEMHEAP_MASK) != RT_MEMHEAP_MAGIC)
        {
            rt_kprintf("[0x%08x - incorrect magic: 0x%08x\n", header_ptr, header_ptr->magic);
            break;
        }

        /* get current memory block size */
        block_size = MEMITEM_SIZE(header_ptr);
        if (block_size < 0)
            break;

        if (RT_MEMHEAP_IS_USED(header_ptr))
        {
            /* dump information */
            rt_kprintf("[0x%08x - %d - %c%c%c%c] used\n", header_ptr, block_size,
G
guozhanxin 已提交
1094 1095
                       header_ptr->owner_thread_name[0], header_ptr->owner_thread_name[1],
                       header_ptr->owner_thread_name[2], header_ptr->owner_thread_name[3]);
C
cliff-cmc 已提交
1096 1097 1098 1099 1100
        }
        else
        {
            /* dump information */
            rt_kprintf("[0x%08x - %d - %c%c%c%c] free\n", header_ptr, block_size,
G
guozhanxin 已提交
1101 1102
                       header_ptr->owner_thread_name[0], header_ptr->owner_thread_name[1],
                       header_ptr->owner_thread_name[2], header_ptr->owner_thread_name[3]);
C
cliff-cmc 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        }

        /* move to next used memory block */
        header_ptr = header_ptr->next;
    }
}

void memtrace_heap()
{
    struct rt_object_information *info;
    struct rt_list_node *list;
    struct rt_memheap *mh;
    struct rt_list_node *node;

    info = rt_object_get_information(RT_Object_Class_MemHeap);
    list = &info->object_list;

    for (node = list->next; node != list; node = node->next)
    {
        mh = (struct rt_memheap *)rt_list_entry(node, struct rt_object, list);
        dump_used_memheap(mh);
    }
}

#ifdef RT_USING_FINSH
#include <finsh.h>
MSH_CMD_EXPORT(memtrace_heap, dump memory trace for heap);
1130
#endif /* RT_USING_FINSH */
C
cliff-cmc 已提交
1131

1132
#endif /* RT_USING_MEMTRACE */
C
cliff-cmc 已提交
1133

1134
#endif /* RT_USING_MEMHEAP */