malloc_simple.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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/global_data.h>
  13. #include <asm/io.h>
  14. #include <valgrind/valgrind.h>
  15. DECLARE_GLOBAL_DATA_PTR;
  16. static void *alloc_simple(size_t bytes, int align)
  17. {
  18. ulong addr, new_ptr;
  19. void *ptr;
  20. addr = ALIGN(gd->malloc_base + gd->malloc_ptr, align);
  21. new_ptr = addr + bytes - gd->malloc_base;
  22. log_debug("size=%lx, ptr=%lx, limit=%lx: ", (ulong)bytes, new_ptr,
  23. gd->malloc_limit);
  24. if (new_ptr > gd->malloc_limit) {
  25. log_err("alloc space exhausted\n");
  26. return NULL;
  27. }
  28. ptr = map_sysmem(addr, bytes);
  29. gd->malloc_ptr = ALIGN(new_ptr, sizeof(new_ptr));
  30. return ptr;
  31. }
  32. void *malloc_simple(size_t bytes)
  33. {
  34. void *ptr;
  35. ptr = alloc_simple(bytes, 1);
  36. if (!ptr)
  37. return ptr;
  38. log_debug("%lx\n", (ulong)ptr);
  39. VALGRIND_MALLOCLIKE_BLOCK(ptr, bytes, 0, false);
  40. return ptr;
  41. }
  42. void *memalign_simple(size_t align, size_t bytes)
  43. {
  44. void *ptr;
  45. ptr = alloc_simple(bytes, align);
  46. if (!ptr)
  47. return ptr;
  48. log_debug("aligned to %lx\n", (ulong)ptr);
  49. VALGRIND_MALLOCLIKE_BLOCK(ptr, bytes, 0, false);
  50. return ptr;
  51. }
  52. #if CONFIG_IS_ENABLED(SYS_MALLOC_SIMPLE)
  53. void *calloc(size_t nmemb, size_t elem_size)
  54. {
  55. size_t size = nmemb * elem_size;
  56. void *ptr;
  57. ptr = malloc(size);
  58. if (!ptr)
  59. return ptr;
  60. memset(ptr, '\0', size);
  61. return ptr;
  62. }
  63. #if IS_ENABLED(CONFIG_VALGRIND)
  64. void free_simple(void *ptr)
  65. {
  66. VALGRIND_FREELIKE_BLOCK(ptr, 0);
  67. }
  68. #endif
  69. #endif
  70. void malloc_simple_info(void)
  71. {
  72. log_info("malloc_simple: %lx bytes used, %lx remain\n", gd->malloc_ptr,
  73. CONFIG_VAL(SYS_MALLOC_F_LEN) - gd->malloc_ptr);
  74. }