malloc_simple.c 1.5 KB

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