mempool.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * linux/mm/mempool.c
  4. *
  5. * memory buffer pool support. Such pools are mostly used
  6. * for guaranteed, deadlock-free memory allocations during
  7. * extreme VM load.
  8. *
  9. * started by Ingo Molnar, Copyright (C) 2001
  10. * debugging by David Rientjes, Copyright (C) 2015
  11. */
  12. #include <linux/mm.h>
  13. #include <linux/slab.h>
  14. #include <linux/highmem.h>
  15. #include <linux/kasan.h>
  16. #include <linux/kmemleak.h>
  17. #include <linux/export.h>
  18. #include <linux/mempool.h>
  19. #include <linux/writeback.h>
  20. #include "slab.h"
  21. #ifdef CONFIG_SLUB_DEBUG_ON
  22. static void poison_error(mempool_t *pool, void *element, size_t size,
  23. size_t byte)
  24. {
  25. const int nr = pool->curr_nr;
  26. const int start = max_t(int, byte - (BITS_PER_LONG / 8), 0);
  27. const int end = min_t(int, byte + (BITS_PER_LONG / 8), size);
  28. int i;
  29. pr_err("BUG: mempool element poison mismatch\n");
  30. pr_err("Mempool %p size %zu\n", pool, size);
  31. pr_err(" nr=%d @ %p: %s0x", nr, element, start > 0 ? "... " : "");
  32. for (i = start; i < end; i++)
  33. pr_cont("%x ", *(u8 *)(element + i));
  34. pr_cont("%s\n", end < size ? "..." : "");
  35. dump_stack();
  36. }
  37. static void __check_element(mempool_t *pool, void *element, size_t size)
  38. {
  39. u8 *obj = element;
  40. size_t i;
  41. for (i = 0; i < size; i++) {
  42. u8 exp = (i < size - 1) ? POISON_FREE : POISON_END;
  43. if (obj[i] != exp) {
  44. poison_error(pool, element, size, i);
  45. return;
  46. }
  47. }
  48. memset(obj, POISON_INUSE, size);
  49. }
  50. static void check_element(mempool_t *pool, void *element)
  51. {
  52. /* Skip checking: KASAN might save its metadata in the element. */
  53. if (kasan_enabled())
  54. return;
  55. /* Mempools backed by slab allocator */
  56. if (pool->free == mempool_kfree) {
  57. __check_element(pool, element, (size_t)pool->pool_data);
  58. } else if (pool->free == mempool_free_slab) {
  59. __check_element(pool, element, kmem_cache_size(pool->pool_data));
  60. } else if (pool->free == mempool_free_pages) {
  61. /* Mempools backed by page allocator */
  62. int order = (int)(long)pool->pool_data;
  63. void *addr = kmap_local_page((struct page *)element);
  64. __check_element(pool, addr, 1UL << (PAGE_SHIFT + order));
  65. kunmap_local(addr);
  66. }
  67. }
  68. static void __poison_element(void *element, size_t size)
  69. {
  70. u8 *obj = element;
  71. memset(obj, POISON_FREE, size - 1);
  72. obj[size - 1] = POISON_END;
  73. }
  74. static void poison_element(mempool_t *pool, void *element)
  75. {
  76. /* Skip poisoning: KASAN might save its metadata in the element. */
  77. if (kasan_enabled())
  78. return;
  79. /* Mempools backed by slab allocator */
  80. if (pool->alloc == mempool_kmalloc) {
  81. __poison_element(element, (size_t)pool->pool_data);
  82. } else if (pool->alloc == mempool_alloc_slab) {
  83. __poison_element(element, kmem_cache_size(pool->pool_data));
  84. } else if (pool->alloc == mempool_alloc_pages) {
  85. /* Mempools backed by page allocator */
  86. int order = (int)(long)pool->pool_data;
  87. void *addr = kmap_local_page((struct page *)element);
  88. __poison_element(addr, 1UL << (PAGE_SHIFT + order));
  89. kunmap_local(addr);
  90. }
  91. }
  92. #else /* CONFIG_SLUB_DEBUG_ON */
  93. static inline void check_element(mempool_t *pool, void *element)
  94. {
  95. }
  96. static inline void poison_element(mempool_t *pool, void *element)
  97. {
  98. }
  99. #endif /* CONFIG_SLUB_DEBUG_ON */
  100. static __always_inline bool kasan_poison_element(mempool_t *pool, void *element)
  101. {
  102. if (pool->alloc == mempool_alloc_slab || pool->alloc == mempool_kmalloc)
  103. return kasan_mempool_poison_object(element);
  104. else if (pool->alloc == mempool_alloc_pages)
  105. return kasan_mempool_poison_pages(element,
  106. (unsigned long)pool->pool_data);
  107. return true;
  108. }
  109. static void kasan_unpoison_element(mempool_t *pool, void *element)
  110. {
  111. if (pool->alloc == mempool_kmalloc)
  112. kasan_mempool_unpoison_object(element, (size_t)pool->pool_data);
  113. else if (pool->alloc == mempool_alloc_slab)
  114. kasan_mempool_unpoison_object(element,
  115. kmem_cache_size(pool->pool_data));
  116. else if (pool->alloc == mempool_alloc_pages)
  117. kasan_mempool_unpoison_pages(element,
  118. (unsigned long)pool->pool_data);
  119. }
  120. static __always_inline void add_element(mempool_t *pool, void *element)
  121. {
  122. BUG_ON(pool->curr_nr >= pool->min_nr);
  123. poison_element(pool, element);
  124. if (kasan_poison_element(pool, element))
  125. pool->elements[pool->curr_nr++] = element;
  126. }
  127. static void *remove_element(mempool_t *pool)
  128. {
  129. void *element = pool->elements[--pool->curr_nr];
  130. BUG_ON(pool->curr_nr < 0);
  131. kasan_unpoison_element(pool, element);
  132. check_element(pool, element);
  133. return element;
  134. }
  135. /**
  136. * mempool_exit - exit a mempool initialized with mempool_init()
  137. * @pool: pointer to the memory pool which was initialized with
  138. * mempool_init().
  139. *
  140. * Free all reserved elements in @pool and @pool itself. This function
  141. * only sleeps if the free_fn() function sleeps.
  142. *
  143. * May be called on a zeroed but uninitialized mempool (i.e. allocated with
  144. * kzalloc()).
  145. */
  146. void mempool_exit(mempool_t *pool)
  147. {
  148. while (pool->curr_nr) {
  149. void *element = remove_element(pool);
  150. pool->free(element, pool->pool_data);
  151. }
  152. kfree(pool->elements);
  153. pool->elements = NULL;
  154. }
  155. EXPORT_SYMBOL(mempool_exit);
  156. /**
  157. * mempool_destroy - deallocate a memory pool
  158. * @pool: pointer to the memory pool which was allocated via
  159. * mempool_create().
  160. *
  161. * Free all reserved elements in @pool and @pool itself. This function
  162. * only sleeps if the free_fn() function sleeps.
  163. */
  164. void mempool_destroy(mempool_t *pool)
  165. {
  166. if (unlikely(!pool))
  167. return;
  168. mempool_exit(pool);
  169. kfree(pool);
  170. }
  171. EXPORT_SYMBOL(mempool_destroy);
  172. int mempool_init_node(mempool_t *pool, int min_nr, mempool_alloc_t *alloc_fn,
  173. mempool_free_t *free_fn, void *pool_data,
  174. gfp_t gfp_mask, int node_id)
  175. {
  176. spin_lock_init(&pool->lock);
  177. pool->min_nr = min_nr;
  178. pool->pool_data = pool_data;
  179. pool->alloc = alloc_fn;
  180. pool->free = free_fn;
  181. init_waitqueue_head(&pool->wait);
  182. pool->elements = kmalloc_array_node(min_nr, sizeof(void *),
  183. gfp_mask, node_id);
  184. if (!pool->elements)
  185. return -ENOMEM;
  186. /*
  187. * First pre-allocate the guaranteed number of buffers.
  188. */
  189. while (pool->curr_nr < pool->min_nr) {
  190. void *element;
  191. element = pool->alloc(gfp_mask, pool->pool_data);
  192. if (unlikely(!element)) {
  193. mempool_exit(pool);
  194. return -ENOMEM;
  195. }
  196. add_element(pool, element);
  197. }
  198. return 0;
  199. }
  200. EXPORT_SYMBOL(mempool_init_node);
  201. /**
  202. * mempool_init - initialize a memory pool
  203. * @pool: pointer to the memory pool that should be initialized
  204. * @min_nr: the minimum number of elements guaranteed to be
  205. * allocated for this pool.
  206. * @alloc_fn: user-defined element-allocation function.
  207. * @free_fn: user-defined element-freeing function.
  208. * @pool_data: optional private data available to the user-defined functions.
  209. *
  210. * Like mempool_create(), but initializes the pool in (i.e. embedded in another
  211. * structure).
  212. *
  213. * Return: %0 on success, negative error code otherwise.
  214. */
  215. int mempool_init_noprof(mempool_t *pool, int min_nr, mempool_alloc_t *alloc_fn,
  216. mempool_free_t *free_fn, void *pool_data)
  217. {
  218. return mempool_init_node(pool, min_nr, alloc_fn, free_fn,
  219. pool_data, GFP_KERNEL, NUMA_NO_NODE);
  220. }
  221. EXPORT_SYMBOL(mempool_init_noprof);
  222. /**
  223. * mempool_create_node - create a memory pool
  224. * @min_nr: the minimum number of elements guaranteed to be
  225. * allocated for this pool.
  226. * @alloc_fn: user-defined element-allocation function.
  227. * @free_fn: user-defined element-freeing function.
  228. * @pool_data: optional private data available to the user-defined functions.
  229. * @gfp_mask: memory allocation flags
  230. * @node_id: numa node to allocate on
  231. *
  232. * this function creates and allocates a guaranteed size, preallocated
  233. * memory pool. The pool can be used from the mempool_alloc() and mempool_free()
  234. * functions. This function might sleep. Both the alloc_fn() and the free_fn()
  235. * functions might sleep - as long as the mempool_alloc() function is not called
  236. * from IRQ contexts.
  237. *
  238. * Return: pointer to the created memory pool object or %NULL on error.
  239. */
  240. mempool_t *mempool_create_node_noprof(int min_nr, mempool_alloc_t *alloc_fn,
  241. mempool_free_t *free_fn, void *pool_data,
  242. gfp_t gfp_mask, int node_id)
  243. {
  244. mempool_t *pool;
  245. pool = kmalloc_node_noprof(sizeof(*pool), gfp_mask | __GFP_ZERO, node_id);
  246. if (!pool)
  247. return NULL;
  248. if (mempool_init_node(pool, min_nr, alloc_fn, free_fn, pool_data,
  249. gfp_mask, node_id)) {
  250. kfree(pool);
  251. return NULL;
  252. }
  253. return pool;
  254. }
  255. EXPORT_SYMBOL(mempool_create_node_noprof);
  256. /**
  257. * mempool_resize - resize an existing memory pool
  258. * @pool: pointer to the memory pool which was allocated via
  259. * mempool_create().
  260. * @new_min_nr: the new minimum number of elements guaranteed to be
  261. * allocated for this pool.
  262. *
  263. * This function shrinks/grows the pool. In the case of growing,
  264. * it cannot be guaranteed that the pool will be grown to the new
  265. * size immediately, but new mempool_free() calls will refill it.
  266. * This function may sleep.
  267. *
  268. * Note, the caller must guarantee that no mempool_destroy is called
  269. * while this function is running. mempool_alloc() & mempool_free()
  270. * might be called (eg. from IRQ contexts) while this function executes.
  271. *
  272. * Return: %0 on success, negative error code otherwise.
  273. */
  274. int mempool_resize(mempool_t *pool, int new_min_nr)
  275. {
  276. void *element;
  277. void **new_elements;
  278. unsigned long flags;
  279. BUG_ON(new_min_nr <= 0);
  280. might_sleep();
  281. spin_lock_irqsave(&pool->lock, flags);
  282. if (new_min_nr <= pool->min_nr) {
  283. while (new_min_nr < pool->curr_nr) {
  284. element = remove_element(pool);
  285. spin_unlock_irqrestore(&pool->lock, flags);
  286. pool->free(element, pool->pool_data);
  287. spin_lock_irqsave(&pool->lock, flags);
  288. }
  289. pool->min_nr = new_min_nr;
  290. goto out_unlock;
  291. }
  292. spin_unlock_irqrestore(&pool->lock, flags);
  293. /* Grow the pool */
  294. new_elements = kmalloc_array(new_min_nr, sizeof(*new_elements),
  295. GFP_KERNEL);
  296. if (!new_elements)
  297. return -ENOMEM;
  298. spin_lock_irqsave(&pool->lock, flags);
  299. if (unlikely(new_min_nr <= pool->min_nr)) {
  300. /* Raced, other resize will do our work */
  301. spin_unlock_irqrestore(&pool->lock, flags);
  302. kfree(new_elements);
  303. goto out;
  304. }
  305. memcpy(new_elements, pool->elements,
  306. pool->curr_nr * sizeof(*new_elements));
  307. kfree(pool->elements);
  308. pool->elements = new_elements;
  309. pool->min_nr = new_min_nr;
  310. while (pool->curr_nr < pool->min_nr) {
  311. spin_unlock_irqrestore(&pool->lock, flags);
  312. element = pool->alloc(GFP_KERNEL, pool->pool_data);
  313. if (!element)
  314. goto out;
  315. spin_lock_irqsave(&pool->lock, flags);
  316. if (pool->curr_nr < pool->min_nr) {
  317. add_element(pool, element);
  318. } else {
  319. spin_unlock_irqrestore(&pool->lock, flags);
  320. pool->free(element, pool->pool_data); /* Raced */
  321. goto out;
  322. }
  323. }
  324. out_unlock:
  325. spin_unlock_irqrestore(&pool->lock, flags);
  326. out:
  327. return 0;
  328. }
  329. EXPORT_SYMBOL(mempool_resize);
  330. /**
  331. * mempool_alloc - allocate an element from a specific memory pool
  332. * @pool: pointer to the memory pool which was allocated via
  333. * mempool_create().
  334. * @gfp_mask: the usual allocation bitmask.
  335. *
  336. * this function only sleeps if the alloc_fn() function sleeps or
  337. * returns NULL. Note that due to preallocation, this function
  338. * *never* fails when called from process contexts. (it might
  339. * fail if called from an IRQ context.)
  340. * Note: using __GFP_ZERO is not supported.
  341. *
  342. * Return: pointer to the allocated element or %NULL on error.
  343. */
  344. void *mempool_alloc_noprof(mempool_t *pool, gfp_t gfp_mask)
  345. {
  346. void *element;
  347. unsigned long flags;
  348. wait_queue_entry_t wait;
  349. gfp_t gfp_temp;
  350. VM_WARN_ON_ONCE(gfp_mask & __GFP_ZERO);
  351. might_alloc(gfp_mask);
  352. gfp_mask |= __GFP_NOMEMALLOC; /* don't allocate emergency reserves */
  353. gfp_mask |= __GFP_NORETRY; /* don't loop in __alloc_pages */
  354. gfp_mask |= __GFP_NOWARN; /* failures are OK */
  355. gfp_temp = gfp_mask & ~(__GFP_DIRECT_RECLAIM|__GFP_IO);
  356. repeat_alloc:
  357. element = pool->alloc(gfp_temp, pool->pool_data);
  358. if (likely(element != NULL))
  359. return element;
  360. spin_lock_irqsave(&pool->lock, flags);
  361. if (likely(pool->curr_nr)) {
  362. element = remove_element(pool);
  363. spin_unlock_irqrestore(&pool->lock, flags);
  364. /* paired with rmb in mempool_free(), read comment there */
  365. smp_wmb();
  366. /*
  367. * Update the allocation stack trace as this is more useful
  368. * for debugging.
  369. */
  370. kmemleak_update_trace(element);
  371. return element;
  372. }
  373. /*
  374. * We use gfp mask w/o direct reclaim or IO for the first round. If
  375. * alloc failed with that and @pool was empty, retry immediately.
  376. */
  377. if (gfp_temp != gfp_mask) {
  378. spin_unlock_irqrestore(&pool->lock, flags);
  379. gfp_temp = gfp_mask;
  380. goto repeat_alloc;
  381. }
  382. /* We must not sleep if !__GFP_DIRECT_RECLAIM */
  383. if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) {
  384. spin_unlock_irqrestore(&pool->lock, flags);
  385. return NULL;
  386. }
  387. /* Let's wait for someone else to return an element to @pool */
  388. init_wait(&wait);
  389. prepare_to_wait(&pool->wait, &wait, TASK_UNINTERRUPTIBLE);
  390. spin_unlock_irqrestore(&pool->lock, flags);
  391. /*
  392. * FIXME: this should be io_schedule(). The timeout is there as a
  393. * workaround for some DM problems in 2.6.18.
  394. */
  395. io_schedule_timeout(5*HZ);
  396. finish_wait(&pool->wait, &wait);
  397. goto repeat_alloc;
  398. }
  399. EXPORT_SYMBOL(mempool_alloc_noprof);
  400. /**
  401. * mempool_alloc_preallocated - allocate an element from preallocated elements
  402. * belonging to a specific memory pool
  403. * @pool: pointer to the memory pool which was allocated via
  404. * mempool_create().
  405. *
  406. * This function is similar to mempool_alloc, but it only attempts allocating
  407. * an element from the preallocated elements. It does not sleep and immediately
  408. * returns if no preallocated elements are available.
  409. *
  410. * Return: pointer to the allocated element or %NULL if no elements are
  411. * available.
  412. */
  413. void *mempool_alloc_preallocated(mempool_t *pool)
  414. {
  415. void *element;
  416. unsigned long flags;
  417. spin_lock_irqsave(&pool->lock, flags);
  418. if (likely(pool->curr_nr)) {
  419. element = remove_element(pool);
  420. spin_unlock_irqrestore(&pool->lock, flags);
  421. /* paired with rmb in mempool_free(), read comment there */
  422. smp_wmb();
  423. /*
  424. * Update the allocation stack trace as this is more useful
  425. * for debugging.
  426. */
  427. kmemleak_update_trace(element);
  428. return element;
  429. }
  430. spin_unlock_irqrestore(&pool->lock, flags);
  431. return NULL;
  432. }
  433. EXPORT_SYMBOL(mempool_alloc_preallocated);
  434. /**
  435. * mempool_free - return an element to the pool.
  436. * @element: pool element pointer.
  437. * @pool: pointer to the memory pool which was allocated via
  438. * mempool_create().
  439. *
  440. * this function only sleeps if the free_fn() function sleeps.
  441. */
  442. void mempool_free(void *element, mempool_t *pool)
  443. {
  444. unsigned long flags;
  445. if (unlikely(element == NULL))
  446. return;
  447. /*
  448. * Paired with the wmb in mempool_alloc(). The preceding read is
  449. * for @element and the following @pool->curr_nr. This ensures
  450. * that the visible value of @pool->curr_nr is from after the
  451. * allocation of @element. This is necessary for fringe cases
  452. * where @element was passed to this task without going through
  453. * barriers.
  454. *
  455. * For example, assume @p is %NULL at the beginning and one task
  456. * performs "p = mempool_alloc(...);" while another task is doing
  457. * "while (!p) cpu_relax(); mempool_free(p, ...);". This function
  458. * may end up using curr_nr value which is from before allocation
  459. * of @p without the following rmb.
  460. */
  461. smp_rmb();
  462. /*
  463. * For correctness, we need a test which is guaranteed to trigger
  464. * if curr_nr + #allocated == min_nr. Testing curr_nr < min_nr
  465. * without locking achieves that and refilling as soon as possible
  466. * is desirable.
  467. *
  468. * Because curr_nr visible here is always a value after the
  469. * allocation of @element, any task which decremented curr_nr below
  470. * min_nr is guaranteed to see curr_nr < min_nr unless curr_nr gets
  471. * incremented to min_nr afterwards. If curr_nr gets incremented
  472. * to min_nr after the allocation of @element, the elements
  473. * allocated after that are subject to the same guarantee.
  474. *
  475. * Waiters happen iff curr_nr is 0 and the above guarantee also
  476. * ensures that there will be frees which return elements to the
  477. * pool waking up the waiters.
  478. */
  479. if (unlikely(READ_ONCE(pool->curr_nr) < pool->min_nr)) {
  480. spin_lock_irqsave(&pool->lock, flags);
  481. if (likely(pool->curr_nr < pool->min_nr)) {
  482. add_element(pool, element);
  483. spin_unlock_irqrestore(&pool->lock, flags);
  484. wake_up(&pool->wait);
  485. return;
  486. }
  487. spin_unlock_irqrestore(&pool->lock, flags);
  488. }
  489. pool->free(element, pool->pool_data);
  490. }
  491. EXPORT_SYMBOL(mempool_free);
  492. /*
  493. * A commonly used alloc and free fn.
  494. */
  495. void *mempool_alloc_slab(gfp_t gfp_mask, void *pool_data)
  496. {
  497. struct kmem_cache *mem = pool_data;
  498. VM_BUG_ON(mem->ctor);
  499. return kmem_cache_alloc_noprof(mem, gfp_mask);
  500. }
  501. EXPORT_SYMBOL(mempool_alloc_slab);
  502. void mempool_free_slab(void *element, void *pool_data)
  503. {
  504. struct kmem_cache *mem = pool_data;
  505. kmem_cache_free(mem, element);
  506. }
  507. EXPORT_SYMBOL(mempool_free_slab);
  508. /*
  509. * A commonly used alloc and free fn that kmalloc/kfrees the amount of memory
  510. * specified by pool_data
  511. */
  512. void *mempool_kmalloc(gfp_t gfp_mask, void *pool_data)
  513. {
  514. size_t size = (size_t)pool_data;
  515. return kmalloc_noprof(size, gfp_mask);
  516. }
  517. EXPORT_SYMBOL(mempool_kmalloc);
  518. void mempool_kfree(void *element, void *pool_data)
  519. {
  520. kfree(element);
  521. }
  522. EXPORT_SYMBOL(mempool_kfree);
  523. void *mempool_kvmalloc(gfp_t gfp_mask, void *pool_data)
  524. {
  525. size_t size = (size_t)pool_data;
  526. return kvmalloc(size, gfp_mask);
  527. }
  528. EXPORT_SYMBOL(mempool_kvmalloc);
  529. void mempool_kvfree(void *element, void *pool_data)
  530. {
  531. kvfree(element);
  532. }
  533. EXPORT_SYMBOL(mempool_kvfree);
  534. /*
  535. * A simple mempool-backed page allocator that allocates pages
  536. * of the order specified by pool_data.
  537. */
  538. void *mempool_alloc_pages(gfp_t gfp_mask, void *pool_data)
  539. {
  540. int order = (int)(long)pool_data;
  541. return alloc_pages_noprof(gfp_mask, order);
  542. }
  543. EXPORT_SYMBOL(mempool_alloc_pages);
  544. void mempool_free_pages(void *element, void *pool_data)
  545. {
  546. int order = (int)(long)pool_data;
  547. __free_pages(element, order);
  548. }
  549. EXPORT_SYMBOL(mempool_free_pages);