You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.9 KiB

  1. /*
  2. * This file is part of the coreboot project.
  3. *
  4. * Copyright 2015 Google Inc.
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; version 2 of the License.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #ifndef _MEM_POOL_H_
  16. #define _MEM_POOL_H_
  17. #include <stddef.h>
  18. #include <stdint.h>
  19. /*
  20. * The memory pool allows one to allocate memory from a fixed size buffer
  21. * that also allows freeing semantics for reuse. However, the current
  22. * limitation is that the most recent allocation is the only one that
  23. * can be freed. If one tries to free any allocation that isn't the
  24. * most recently allocated it will result in a leak within the memory pool.
  25. *
  26. * The memory returned by allocations are at least 8 byte aligned. Note
  27. * that this requires the backing buffer to start on at least an 8 byte
  28. * alignment.
  29. */
  30. struct mem_pool {
  31. uint8_t *buf;
  32. size_t size;
  33. uint8_t *last_alloc;
  34. size_t free_offset;
  35. };
  36. #define MEM_POOL_INIT(buf_, size_) \
  37. { \
  38. .buf = (buf_), \
  39. .size = (size_), \
  40. .last_alloc = NULL, \
  41. .free_offset = 0, \
  42. }
  43. static inline void mem_pool_reset(struct mem_pool *mp)
  44. {
  45. mp->last_alloc = NULL;
  46. mp->free_offset = 0;
  47. }
  48. /* Initialize a memory pool. */
  49. static inline void mem_pool_init(struct mem_pool *mp, void *buf, size_t sz)
  50. {
  51. mp->buf = buf;
  52. mp->size = sz;
  53. mem_pool_reset(mp);
  54. }
  55. /* Allocate requested size from the memory pool. NULL returned on error. */
  56. void *mem_pool_alloc(struct mem_pool *mp, size_t sz);
  57. /* Free allocation from memory pool. */
  58. void mem_pool_free(struct mem_pool *mp, void *alloc);
  59. #endif /* _MEM_POOL_H_ */