blob: 0f6bcbcc712d895dbc2235e8029c4fe09f2f4058 [file] [log] [blame]
Simon Glassc9356be2014-11-10 17:16:43 -07001/*
2 * Simple malloc implementation
3 *
4 * Copyright (c) 2014 Google, Inc
5 *
6 * SPDX-License-Identifier: GPL-2.0+
7 */
8
9#include <common.h>
10#include <malloc.h>
Joe Hershberger0eb25b62015-03-22 17:08:59 -050011#include <mapmem.h>
Simon Glassc9356be2014-11-10 17:16:43 -070012#include <asm/io.h>
13
14DECLARE_GLOBAL_DATA_PTR;
15
16void *malloc_simple(size_t bytes)
17{
18 ulong new_ptr;
19 void *ptr;
20
21 new_ptr = gd->malloc_ptr + bytes;
Simon Glass9a01cca2016-03-06 19:27:55 -070022 debug("%s: size=%zx, ptr=%lx, limit=%lx: ", __func__, bytes, new_ptr,
Simon Glass836ac742015-09-08 17:52:46 -060023 gd->malloc_limit);
Simon Glass9a01cca2016-03-06 19:27:55 -070024 if (new_ptr > gd->malloc_limit) {
25 debug("space exhausted\n");
Hans de Goede2c857172015-02-04 13:05:50 +010026 return NULL;
Simon Glass9a01cca2016-03-06 19:27:55 -070027 }
Simon Glassc9356be2014-11-10 17:16:43 -070028 ptr = map_sysmem(gd->malloc_base + gd->malloc_ptr, bytes);
29 gd->malloc_ptr = ALIGN(new_ptr, sizeof(new_ptr));
Simon Glass9a01cca2016-03-06 19:27:55 -070030 debug("%lx\n", (ulong)ptr);
Simon Glass836ac742015-09-08 17:52:46 -060031
Simon Glassc9356be2014-11-10 17:16:43 -070032 return ptr;
33}
34
Simon Glassb6bfb6f2015-05-12 14:55:06 -060035void *memalign_simple(size_t align, size_t bytes)
36{
37 ulong addr, new_ptr;
38 void *ptr;
39
Simon Glass972ea532015-08-14 13:26:43 -060040 addr = ALIGN(gd->malloc_base + gd->malloc_ptr, align);
Philipp Rosenberger596380d2015-09-08 12:41:24 +020041 new_ptr = addr + bytes - gd->malloc_base;
Simon Glassb6bfb6f2015-05-12 14:55:06 -060042 if (new_ptr > gd->malloc_limit)
43 return NULL;
44 ptr = map_sysmem(addr, bytes);
45 gd->malloc_ptr = ALIGN(new_ptr, sizeof(new_ptr));
Simon Glass836ac742015-09-08 17:52:46 -060046
Simon Glassb6bfb6f2015-05-12 14:55:06 -060047 return ptr;
48}
49
Hans de Goede1eb0c032015-09-13 14:45:15 +020050#if CONFIG_IS_ENABLED(SYS_MALLOC_SIMPLE)
Simon Glassc9356be2014-11-10 17:16:43 -070051void *calloc(size_t nmemb, size_t elem_size)
52{
53 size_t size = nmemb * elem_size;
54 void *ptr;
55
56 ptr = malloc(size);
57 memset(ptr, '\0', size);
58
59 return ptr;
60}
61#endif