malloc_simple.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Simple malloc implementation
  4. *
  5. * Copyright (c) 2014 Google, Inc
  6. */
  7. #define LOG_CATEGORY LOGC_ALLOC
  8. #include <common.h>
  9. #include <log.h>
  10. #include <malloc.h>
  11. #include <mapmem.h>
  12. #include <asm/io.h>
  13. DECLARE_GLOBAL_DATA_PTR;
  14. static void *alloc_simple(size_t bytes, int align)
  15. {
  16. ulong addr, new_ptr;
  17. void *ptr;
  18. addr = ALIGN(gd->malloc_base + gd->malloc_ptr, align);
  19. new_ptr = addr + bytes - gd->malloc_base;
  20. log_debug("size=%zx, ptr=%lx, limit=%lx: ", bytes, new_ptr,
  21. gd->malloc_limit);
  22. if (new_ptr > gd->malloc_limit) {
  23. log_err("alloc space exhausted\n");
  24. return NULL;
  25. }
  26. ptr = map_sysmem(addr, bytes);
  27. gd->malloc_ptr = ALIGN(new_ptr, sizeof(new_ptr));
  28. return ptr;
  29. }
  30. void *malloc_simple(size_t bytes)
  31. {
  32. void *ptr;
  33. ptr = alloc_simple(bytes, 1);
  34. if (!ptr)
  35. return ptr;
  36. log_debug("%lx\n", (ulong)ptr);
  37. return ptr;
  38. }
  39. void *memalign_simple(size_t align, size_t bytes)
  40. {
  41. void *ptr;
  42. ptr = alloc_simple(bytes, align);
  43. if (!ptr)
  44. return ptr;
  45. log_debug("aligned to %lx\n", (ulong)ptr);
  46. return ptr;
  47. }
  48. #if CONFIG_IS_ENABLED(SYS_MALLOC_SIMPLE)
  49. void *calloc(size_t nmemb, size_t elem_size)
  50. {
  51. size_t size = nmemb * elem_size;
  52. void *ptr;
  53. ptr = malloc(size);
  54. if (!ptr)
  55. return ptr;
  56. memset(ptr, '\0', size);
  57. return ptr;
  58. }
  59. #endif
  60. void malloc_simple_info(void)
  61. {
  62. log_info("malloc_simple: %lx bytes used, %lx remain\n", gd->malloc_ptr,
  63. CONFIG_VAL(SYS_MALLOC_F_LEN) - gd->malloc_ptr);
  64. }