blob: 0267fb6bec87bae60da5beb27ef11f25afd4dedf [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001// SPDX-License-Identifier: GPL-2.0+
Simon Glassc9356be2014-11-10 17:16:43 -07002/*
3 * Simple malloc implementation
4 *
5 * Copyright (c) 2014 Google, Inc
Simon Glassc9356be2014-11-10 17:16:43 -07006 */
7
Simon Glass7cbd2d22018-11-18 08:14:26 -07008#define LOG_CATEGORY LOGC_ALLOC
9
Simon Glassc9356be2014-11-10 17:16:43 -070010#include <common.h>
Simon Glassf7ae49f2020-05-10 11:40:05 -060011#include <log.h>
Simon Glassc9356be2014-11-10 17:16:43 -070012#include <malloc.h>
Joe Hershberger0eb25b62015-03-22 17:08:59 -050013#include <mapmem.h>
Simon Glass401d1c42020-10-30 21:38:53 -060014#include <asm/global_data.h>
Simon Glassc9356be2014-11-10 17:16:43 -070015#include <asm/io.h>
16
17DECLARE_GLOBAL_DATA_PTR;
18
Simon Glass7cbd2d22018-11-18 08:14:26 -070019static void *alloc_simple(size_t bytes, int align)
Simon Glassb6bfb6f2015-05-12 14:55:06 -060020{
21 ulong addr, new_ptr;
22 void *ptr;
23
Simon Glass972ea532015-08-14 13:26:43 -060024 addr = ALIGN(gd->malloc_base + gd->malloc_ptr, align);
Philipp Rosenberger596380d2015-09-08 12:41:24 +020025 new_ptr = addr + bytes - gd->malloc_base;
Simon Glass7cbd2d22018-11-18 08:14:26 -070026 log_debug("size=%zx, ptr=%lx, limit=%lx: ", bytes, new_ptr,
27 gd->malloc_limit);
Andrew F. Davis1923d542017-01-27 10:39:18 -060028 if (new_ptr > gd->malloc_limit) {
Simon Glass7cbd2d22018-11-18 08:14:26 -070029 log_err("alloc space exhausted\n");
Simon Glassb6bfb6f2015-05-12 14:55:06 -060030 return NULL;
Andrew F. Davis1923d542017-01-27 10:39:18 -060031 }
32
Simon Glassb6bfb6f2015-05-12 14:55:06 -060033 ptr = map_sysmem(addr, bytes);
34 gd->malloc_ptr = ALIGN(new_ptr, sizeof(new_ptr));
Simon Glass7cbd2d22018-11-18 08:14:26 -070035
36 return ptr;
37}
38
39void *malloc_simple(size_t bytes)
40{
41 void *ptr;
42
43 ptr = alloc_simple(bytes, 1);
44 if (!ptr)
45 return ptr;
46
47 log_debug("%lx\n", (ulong)ptr);
48
49 return ptr;
50}
51
52void *memalign_simple(size_t align, size_t bytes)
53{
54 void *ptr;
55
56 ptr = alloc_simple(bytes, align);
57 if (!ptr)
58 return ptr;
59 log_debug("aligned to %lx\n", (ulong)ptr);
Simon Glass836ac742015-09-08 17:52:46 -060060
Simon Glassb6bfb6f2015-05-12 14:55:06 -060061 return ptr;
62}
63
Hans de Goede1eb0c032015-09-13 14:45:15 +020064#if CONFIG_IS_ENABLED(SYS_MALLOC_SIMPLE)
Simon Glassc9356be2014-11-10 17:16:43 -070065void *calloc(size_t nmemb, size_t elem_size)
66{
67 size_t size = nmemb * elem_size;
68 void *ptr;
69
70 ptr = malloc(size);
Simon Glass7cbd2d22018-11-18 08:14:26 -070071 if (!ptr)
72 return ptr;
73 memset(ptr, '\0', size);
Simon Glassc9356be2014-11-10 17:16:43 -070074
75 return ptr;
76}
77#endif
Simon Glass7cbd2d22018-11-18 08:14:26 -070078
79void malloc_simple_info(void)
80{
81 log_info("malloc_simple: %lx bytes used, %lx remain\n", gd->malloc_ptr,
82 CONFIG_VAL(SYS_MALLOC_F_LEN) - gd->malloc_ptr);
83}