malloc_simple.c 1.4 KB

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