memory-alloc.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright 2023 Red Hat
  4. */
  5. #include <linux/delay.h>
  6. #include <linux/mm.h>
  7. #include <linux/sched/mm.h>
  8. #include <linux/slab.h>
  9. #include <linux/vmalloc.h>
  10. #include "logger.h"
  11. #include "memory-alloc.h"
  12. #include "permassert.h"
  13. /*
  14. * UDS and VDO keep track of which threads are allowed to allocate memory freely, and which threads
  15. * must be careful to not do a memory allocation that does an I/O request. The 'allocating_threads'
  16. * thread_registry and its associated methods implement this tracking.
  17. */
  18. static struct thread_registry allocating_threads;
  19. static inline bool allocations_allowed(void)
  20. {
  21. return vdo_lookup_thread(&allocating_threads) != NULL;
  22. }
  23. /*
  24. * Register the current thread as an allocating thread.
  25. *
  26. * An optional flag location can be supplied indicating whether, at any given point in time, the
  27. * threads associated with that flag should be allocating storage. If the flag is false, a message
  28. * will be logged.
  29. *
  30. * If no flag is supplied, the thread is always allowed to allocate storage without complaint.
  31. *
  32. * @new_thread: registered_thread structure to use for the current thread
  33. * @flag_ptr: Location of the allocation-allowed flag
  34. */
  35. void vdo_register_allocating_thread(struct registered_thread *new_thread,
  36. const bool *flag_ptr)
  37. {
  38. if (flag_ptr == NULL) {
  39. static const bool allocation_always_allowed = true;
  40. flag_ptr = &allocation_always_allowed;
  41. }
  42. vdo_register_thread(&allocating_threads, new_thread, flag_ptr);
  43. }
  44. /* Unregister the current thread as an allocating thread. */
  45. void vdo_unregister_allocating_thread(void)
  46. {
  47. vdo_unregister_thread(&allocating_threads);
  48. }
  49. /*
  50. * We track how much memory has been allocated and freed. When we unload the module, we log an
  51. * error if we have not freed all the memory that we allocated. Nearly all memory allocation and
  52. * freeing is done using this module.
  53. *
  54. * We do not use kernel functions like the kvasprintf() method, which allocate memory indirectly
  55. * using kmalloc.
  56. *
  57. * These data structures and methods are used to track the amount of memory used.
  58. */
  59. /*
  60. * We allocate very few large objects, and allocation/deallocation isn't done in a
  61. * performance-critical stage for us, so a linked list should be fine.
  62. */
  63. struct vmalloc_block_info {
  64. void *ptr;
  65. size_t size;
  66. struct vmalloc_block_info *next;
  67. };
  68. static struct {
  69. spinlock_t lock;
  70. size_t kmalloc_blocks;
  71. size_t kmalloc_bytes;
  72. size_t vmalloc_blocks;
  73. size_t vmalloc_bytes;
  74. size_t peak_bytes;
  75. struct vmalloc_block_info *vmalloc_list;
  76. } memory_stats __cacheline_aligned;
  77. static void update_peak_usage(void)
  78. {
  79. size_t total_bytes = memory_stats.kmalloc_bytes + memory_stats.vmalloc_bytes;
  80. if (total_bytes > memory_stats.peak_bytes)
  81. memory_stats.peak_bytes = total_bytes;
  82. }
  83. static void add_kmalloc_block(size_t size)
  84. {
  85. unsigned long flags;
  86. spin_lock_irqsave(&memory_stats.lock, flags);
  87. memory_stats.kmalloc_blocks++;
  88. memory_stats.kmalloc_bytes += size;
  89. update_peak_usage();
  90. spin_unlock_irqrestore(&memory_stats.lock, flags);
  91. }
  92. static void remove_kmalloc_block(size_t size)
  93. {
  94. unsigned long flags;
  95. spin_lock_irqsave(&memory_stats.lock, flags);
  96. memory_stats.kmalloc_blocks--;
  97. memory_stats.kmalloc_bytes -= size;
  98. spin_unlock_irqrestore(&memory_stats.lock, flags);
  99. }
  100. static void add_vmalloc_block(struct vmalloc_block_info *block)
  101. {
  102. unsigned long flags;
  103. spin_lock_irqsave(&memory_stats.lock, flags);
  104. block->next = memory_stats.vmalloc_list;
  105. memory_stats.vmalloc_list = block;
  106. memory_stats.vmalloc_blocks++;
  107. memory_stats.vmalloc_bytes += block->size;
  108. update_peak_usage();
  109. spin_unlock_irqrestore(&memory_stats.lock, flags);
  110. }
  111. static void remove_vmalloc_block(void *ptr)
  112. {
  113. struct vmalloc_block_info *block;
  114. struct vmalloc_block_info **block_ptr;
  115. unsigned long flags;
  116. spin_lock_irqsave(&memory_stats.lock, flags);
  117. for (block_ptr = &memory_stats.vmalloc_list;
  118. (block = *block_ptr) != NULL;
  119. block_ptr = &block->next) {
  120. if (block->ptr == ptr) {
  121. *block_ptr = block->next;
  122. memory_stats.vmalloc_blocks--;
  123. memory_stats.vmalloc_bytes -= block->size;
  124. break;
  125. }
  126. }
  127. spin_unlock_irqrestore(&memory_stats.lock, flags);
  128. if (block != NULL)
  129. vdo_free(block);
  130. else
  131. vdo_log_info("attempting to remove ptr %px not found in vmalloc list", ptr);
  132. }
  133. /*
  134. * Determine whether allocating a memory block should use kmalloc or __vmalloc.
  135. *
  136. * vmalloc can allocate any integral number of pages.
  137. *
  138. * kmalloc can allocate any number of bytes up to a configured limit, which defaults to 8 megabytes
  139. * on some systems. kmalloc is especially good when memory is being both allocated and freed, and
  140. * it does this efficiently in a multi CPU environment.
  141. *
  142. * kmalloc usually rounds the size of the block up to the next power of two, so when the requested
  143. * block is bigger than PAGE_SIZE / 2 bytes, kmalloc will never give you less space than the
  144. * corresponding vmalloc allocation. Sometimes vmalloc will use less overhead than kmalloc.
  145. *
  146. * The advantages of kmalloc do not help out UDS or VDO, because we allocate all our memory up
  147. * front and do not free and reallocate it. Sometimes we have problems using kmalloc, because the
  148. * Linux memory page map can become so fragmented that kmalloc will not give us a 32KB chunk. We
  149. * have used vmalloc as a backup to kmalloc in the past, and a follow-up vmalloc of 32KB will work.
  150. * But there is no strong case to be made for using kmalloc over vmalloc for these size chunks.
  151. *
  152. * The kmalloc/vmalloc boundary is set at 4KB, and kmalloc gets the 4KB requests. There is no
  153. * strong reason for favoring either kmalloc or vmalloc for 4KB requests, except that tracking
  154. * vmalloc statistics uses a linked list implementation. Using a simple test, this choice of
  155. * boundary results in 132 vmalloc calls. Using vmalloc for requests of exactly 4KB results in an
  156. * additional 6374 vmalloc calls, which is much less efficient for tracking.
  157. *
  158. * @size: How many bytes to allocate
  159. */
  160. static inline bool use_kmalloc(size_t size)
  161. {
  162. return size <= PAGE_SIZE;
  163. }
  164. /*
  165. * Allocate storage based on memory size and alignment, logging an error if the allocation fails.
  166. * The memory will be zeroed.
  167. *
  168. * @size: The size of an object
  169. * @align: The required alignment
  170. * @what: What is being allocated (for error logging)
  171. * @ptr: A pointer to hold the allocated memory
  172. *
  173. * Return: VDO_SUCCESS or an error code
  174. */
  175. int vdo_allocate_memory(size_t size, size_t align, const char *what, void *ptr)
  176. {
  177. /*
  178. * The __GFP_RETRY_MAYFAIL flag means the VM implementation will retry memory reclaim
  179. * procedures that have previously failed if there is some indication that progress has
  180. * been made elsewhere. It can wait for other tasks to attempt high level approaches to
  181. * freeing memory such as compaction (which removes fragmentation) and page-out. There is
  182. * still a definite limit to the number of retries, but it is a larger limit than with
  183. * __GFP_NORETRY. Allocations with this flag may fail, but only when there is genuinely
  184. * little unused memory. While these allocations do not directly trigger the OOM killer,
  185. * their failure indicates that the system is likely to need to use the OOM killer soon.
  186. * The caller must handle failure, but can reasonably do so by failing a higher-level
  187. * request, or completing it only in a much less efficient manner.
  188. */
  189. const gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_RETRY_MAYFAIL;
  190. unsigned int noio_flags;
  191. bool allocations_restricted = !allocations_allowed();
  192. unsigned long start_time;
  193. void *p = NULL;
  194. if (unlikely(ptr == NULL))
  195. return -EINVAL;
  196. if (size == 0) {
  197. *((void **) ptr) = NULL;
  198. return VDO_SUCCESS;
  199. }
  200. if (allocations_restricted)
  201. noio_flags = memalloc_noio_save();
  202. start_time = jiffies;
  203. if (use_kmalloc(size) && (align < PAGE_SIZE)) {
  204. p = kmalloc(size, gfp_flags | __GFP_NOWARN);
  205. if (p == NULL) {
  206. /*
  207. * It is possible for kmalloc to fail to allocate memory because there is
  208. * no page available. A short sleep may allow the page reclaimer to
  209. * free a page.
  210. */
  211. fsleep(1000);
  212. p = kmalloc(size, gfp_flags);
  213. }
  214. if (p != NULL)
  215. add_kmalloc_block(ksize(p));
  216. } else {
  217. struct vmalloc_block_info *block;
  218. if (vdo_allocate(1, struct vmalloc_block_info, __func__, &block) == VDO_SUCCESS) {
  219. /*
  220. * It is possible for __vmalloc to fail to allocate memory because there
  221. * are no pages available. A short sleep may allow the page reclaimer
  222. * to free enough pages for a small allocation.
  223. *
  224. * For larger allocations, the page_alloc code is racing against the page
  225. * reclaimer. If the page reclaimer can stay ahead of page_alloc, the
  226. * __vmalloc will succeed. But if page_alloc overtakes the page reclaimer,
  227. * the allocation fails. It is possible that more retries will succeed.
  228. */
  229. for (;;) {
  230. p = __vmalloc(size, gfp_flags | __GFP_NOWARN);
  231. if (p != NULL)
  232. break;
  233. if (jiffies_to_msecs(jiffies - start_time) > 1000) {
  234. /* Try one more time, logging a failure for this call. */
  235. p = __vmalloc(size, gfp_flags);
  236. break;
  237. }
  238. fsleep(1000);
  239. }
  240. if (p == NULL) {
  241. vdo_free(block);
  242. } else {
  243. block->ptr = p;
  244. block->size = PAGE_ALIGN(size);
  245. add_vmalloc_block(block);
  246. }
  247. }
  248. }
  249. if (allocations_restricted)
  250. memalloc_noio_restore(noio_flags);
  251. if (unlikely(p == NULL)) {
  252. vdo_log_error("Could not allocate %zu bytes for %s in %u msecs",
  253. size, what, jiffies_to_msecs(jiffies - start_time));
  254. return -ENOMEM;
  255. }
  256. *((void **) ptr) = p;
  257. return VDO_SUCCESS;
  258. }
  259. /*
  260. * Allocate storage based on memory size, failing immediately if the required memory is not
  261. * available. The memory will be zeroed.
  262. *
  263. * @size: The size of an object.
  264. * @what: What is being allocated (for error logging)
  265. *
  266. * Return: pointer to the allocated memory, or NULL if the required space is not available.
  267. */
  268. void *vdo_allocate_memory_nowait(size_t size, const char *what __maybe_unused)
  269. {
  270. void *p = kmalloc(size, GFP_NOWAIT | __GFP_ZERO);
  271. if (p != NULL)
  272. add_kmalloc_block(ksize(p));
  273. return p;
  274. }
  275. void vdo_free(void *ptr)
  276. {
  277. if (ptr != NULL) {
  278. if (is_vmalloc_addr(ptr)) {
  279. remove_vmalloc_block(ptr);
  280. vfree(ptr);
  281. } else {
  282. remove_kmalloc_block(ksize(ptr));
  283. kfree(ptr);
  284. }
  285. }
  286. }
  287. /*
  288. * Reallocate dynamically allocated memory. There are no alignment guarantees for the reallocated
  289. * memory. If the new memory is larger than the old memory, the new space will be zeroed.
  290. *
  291. * @ptr: The memory to reallocate.
  292. * @old_size: The old size of the memory
  293. * @size: The new size to allocate
  294. * @what: What is being allocated (for error logging)
  295. * @new_ptr: A pointer to hold the reallocated pointer
  296. *
  297. * Return: VDO_SUCCESS or an error code
  298. */
  299. int vdo_reallocate_memory(void *ptr, size_t old_size, size_t size, const char *what,
  300. void *new_ptr)
  301. {
  302. int result;
  303. if (size == 0) {
  304. vdo_free(ptr);
  305. *(void **) new_ptr = NULL;
  306. return VDO_SUCCESS;
  307. }
  308. result = vdo_allocate(size, char, what, new_ptr);
  309. if (result != VDO_SUCCESS)
  310. return result;
  311. if (ptr != NULL) {
  312. if (old_size < size)
  313. size = old_size;
  314. memcpy(*((void **) new_ptr), ptr, size);
  315. vdo_free(ptr);
  316. }
  317. return VDO_SUCCESS;
  318. }
  319. int vdo_duplicate_string(const char *string, const char *what, char **new_string)
  320. {
  321. int result;
  322. u8 *dup;
  323. result = vdo_allocate(strlen(string) + 1, u8, what, &dup);
  324. if (result != VDO_SUCCESS)
  325. return result;
  326. memcpy(dup, string, strlen(string) + 1);
  327. *new_string = dup;
  328. return VDO_SUCCESS;
  329. }
  330. void vdo_memory_init(void)
  331. {
  332. spin_lock_init(&memory_stats.lock);
  333. vdo_initialize_thread_registry(&allocating_threads);
  334. }
  335. void vdo_memory_exit(void)
  336. {
  337. VDO_ASSERT_LOG_ONLY(memory_stats.kmalloc_bytes == 0,
  338. "kmalloc memory used (%zd bytes in %zd blocks) is returned to the kernel",
  339. memory_stats.kmalloc_bytes, memory_stats.kmalloc_blocks);
  340. VDO_ASSERT_LOG_ONLY(memory_stats.vmalloc_bytes == 0,
  341. "vmalloc memory used (%zd bytes in %zd blocks) is returned to the kernel",
  342. memory_stats.vmalloc_bytes, memory_stats.vmalloc_blocks);
  343. vdo_log_debug("peak usage %zd bytes", memory_stats.peak_bytes);
  344. }
  345. void vdo_get_memory_stats(u64 *bytes_used, u64 *peak_bytes_used)
  346. {
  347. unsigned long flags;
  348. spin_lock_irqsave(&memory_stats.lock, flags);
  349. *bytes_used = memory_stats.kmalloc_bytes + memory_stats.vmalloc_bytes;
  350. *peak_bytes_used = memory_stats.peak_bytes;
  351. spin_unlock_irqrestore(&memory_stats.lock, flags);
  352. }
  353. /*
  354. * Report stats on any allocated memory that we're tracking. Not all allocation types are
  355. * guaranteed to be tracked in bytes (e.g., bios).
  356. */
  357. void vdo_report_memory_usage(void)
  358. {
  359. unsigned long flags;
  360. u64 kmalloc_blocks;
  361. u64 kmalloc_bytes;
  362. u64 vmalloc_blocks;
  363. u64 vmalloc_bytes;
  364. u64 peak_usage;
  365. u64 total_bytes;
  366. spin_lock_irqsave(&memory_stats.lock, flags);
  367. kmalloc_blocks = memory_stats.kmalloc_blocks;
  368. kmalloc_bytes = memory_stats.kmalloc_bytes;
  369. vmalloc_blocks = memory_stats.vmalloc_blocks;
  370. vmalloc_bytes = memory_stats.vmalloc_bytes;
  371. peak_usage = memory_stats.peak_bytes;
  372. spin_unlock_irqrestore(&memory_stats.lock, flags);
  373. total_bytes = kmalloc_bytes + vmalloc_bytes;
  374. vdo_log_info("current module memory tracking (actual allocation sizes, not requested):");
  375. vdo_log_info(" %llu bytes in %llu kmalloc blocks",
  376. (unsigned long long) kmalloc_bytes,
  377. (unsigned long long) kmalloc_blocks);
  378. vdo_log_info(" %llu bytes in %llu vmalloc blocks",
  379. (unsigned long long) vmalloc_bytes,
  380. (unsigned long long) vmalloc_blocks);
  381. vdo_log_info(" total %llu bytes, peak usage %llu bytes",
  382. (unsigned long long) total_bytes, (unsigned long long) peak_usage);
  383. }