mempool.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. #if defined(CONFIG_DEBUG_SLAB) || defined(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. /* Mempools backed by slab allocator */
  53. if (pool->free == mempool_free_slab || pool->free == mempool_kfree) {
  54. __check_element(pool, element, ksize(element));
  55. } else if (pool->free == mempool_free_pages) {
  56. /* Mempools backed by page allocator */
  57. int order = (int)(long)pool->pool_data;
  58. void *addr = kmap_atomic((struct page *)element);
  59. __check_element(pool, addr, 1UL << (PAGE_SHIFT + order));
  60. kunmap_atomic(addr);
  61. }
  62. }
  63. static void __poison_element(void *element, size_t size)
  64. {
  65. u8 *obj = element;
  66. memset(obj, POISON_FREE, size - 1);
  67. obj[size - 1] = POISON_END;
  68. }
  69. static void poison_element(mempool_t *pool, void *element)
  70. {
  71. /* Mempools backed by slab allocator */
  72. if (pool->alloc == mempool_alloc_slab || pool->alloc == mempool_kmalloc) {
  73. __poison_element(element, ksize(element));
  74. } else if (pool->alloc == mempool_alloc_pages) {
  75. /* Mempools backed by page allocator */
  76. int order = (int)(long)pool->pool_data;
  77. void *addr = kmap_atomic((struct page *)element);
  78. __poison_element(addr, 1UL << (PAGE_SHIFT + order));
  79. kunmap_atomic(addr);
  80. }
  81. }
  82. #else /* CONFIG_DEBUG_SLAB || CONFIG_SLUB_DEBUG_ON */
  83. static inline void check_element(mempool_t *pool, void *element)
  84. {
  85. }
  86. static inline void poison_element(mempool_t *pool, void *element)
  87. {
  88. }
  89. #endif /* CONFIG_DEBUG_SLAB || CONFIG_SLUB_DEBUG_ON */
  90. static __always_inline void kasan_poison_element(mempool_t *pool, void *element)
  91. {
  92. if (pool->alloc == mempool_alloc_slab || pool->alloc == mempool_kmalloc)
  93. kasan_slab_free_mempool(element);
  94. else if (pool->alloc == mempool_alloc_pages)
  95. kasan_poison_pages(element, (unsigned long)pool->pool_data,
  96. false);
  97. }
  98. static void kasan_unpoison_element(mempool_t *pool, void *element)
  99. {
  100. if (pool->alloc == mempool_alloc_slab || pool->alloc == mempool_kmalloc)
  101. kasan_unpoison_range(element, __ksize(element));
  102. else if (pool->alloc == mempool_alloc_pages)
  103. kasan_unpoison_pages(element, (unsigned long)pool->pool_data,
  104. false);
  105. }
  106. static __always_inline void add_element(mempool_t *pool, void *element)
  107. {
  108. BUG_ON(pool->curr_nr >= pool->min_nr);
  109. poison_element(pool, element);
  110. kasan_poison_element(pool, element);
  111. pool->elements[pool->curr_nr++] = element;
  112. }
  113. static void *remove_element(mempool_t *pool)
  114. {
  115. void *element = pool->elements[--pool->curr_nr];
  116. BUG_ON(pool->curr_nr < 0);
  117. kasan_unpoison_element(pool, element);
  118. check_element(pool, element);
  119. return element;
  120. }
  121. /**
  122. * mempool_exit - exit a mempool initialized with mempool_init()
  123. * @pool: pointer to the memory pool which was initialized with
  124. * mempool_init().
  125. *
  126. * Free all reserved elements in @pool and @pool itself. This function
  127. * only sleeps if the free_fn() function sleeps.
  128. *
  129. * May be called on a zeroed but uninitialized mempool (i.e. allocated with
  130. * kzalloc()).
  131. */
  132. void mempool_exit(mempool_t *pool)
  133. {
  134. while (pool->curr_nr) {
  135. void *element = remove_element(pool);
  136. pool->free(element, pool->pool_data);
  137. }
  138. kfree(pool->elements);
  139. pool->elements = NULL;
  140. }
  141. EXPORT_SYMBOL(mempool_exit);
  142. /**
  143. * mempool_destroy - deallocate a memory pool
  144. * @pool: pointer to the memory pool which was allocated via
  145. * mempool_create().
  146. *
  147. * Free all reserved elements in @pool and @pool itself. This function
  148. * only sleeps if the free_fn() function sleeps.
  149. */
  150. void mempool_destroy(mempool_t *pool)
  151. {
  152. if (unlikely(!pool))
  153. return;
  154. mempool_exit(pool);
  155. kfree(pool);
  156. }
  157. EXPORT_SYMBOL(mempool_destroy);
  158. int mempool_init_node(mempool_t *pool, int min_nr, mempool_alloc_t *alloc_fn,
  159. mempool_free_t *free_fn, void *pool_data,
  160. gfp_t gfp_mask, int node_id)
  161. {
  162. spin_lock_init(&pool->lock);
  163. pool->min_nr = min_nr;
  164. pool->pool_data = pool_data;
  165. pool->alloc = alloc_fn;
  166. pool->free = free_fn;
  167. init_waitqueue_head(&pool->wait);
  168. pool->elements = kmalloc_array_node(min_nr, sizeof(void *),
  169. gfp_mask, node_id);
  170. if (!pool->elements)
  171. return -ENOMEM;
  172. /*
  173. * First pre-allocate the guaranteed number of buffers.
  174. */
  175. while (pool->curr_nr < pool->min_nr) {
  176. void *element;
  177. element = pool->alloc(gfp_mask, pool->pool_data);
  178. if (unlikely(!element)) {
  179. mempool_exit(pool);
  180. return -ENOMEM;
  181. }
  182. add_element(pool, element);
  183. }
  184. return 0;
  185. }
  186. EXPORT_SYMBOL(mempool_init_node);
  187. /**
  188. * mempool_init - initialize a memory pool
  189. * @pool: pointer to the memory pool that should be initialized
  190. * @min_nr: the minimum number of elements guaranteed to be
  191. * allocated for this pool.
  192. * @alloc_fn: user-defined element-allocation function.
  193. * @free_fn: user-defined element-freeing function.
  194. * @pool_data: optional private data available to the user-defined functions.
  195. *
  196. * Like mempool_create(), but initializes the pool in (i.e. embedded in another
  197. * structure).
  198. *
  199. * Return: %0 on success, negative error code otherwise.
  200. */
  201. int mempool_init(mempool_t *pool, int min_nr, mempool_alloc_t *alloc_fn,
  202. mempool_free_t *free_fn, void *pool_data)
  203. {
  204. return mempool_init_node(pool, min_nr, alloc_fn, free_fn,
  205. pool_data, GFP_KERNEL, NUMA_NO_NODE);
  206. }
  207. EXPORT_SYMBOL(mempool_init);
  208. /**
  209. * mempool_create - create a memory pool
  210. * @min_nr: the minimum number of elements guaranteed to be
  211. * allocated for this pool.
  212. * @alloc_fn: user-defined element-allocation function.
  213. * @free_fn: user-defined element-freeing function.
  214. * @pool_data: optional private data available to the user-defined functions.
  215. *
  216. * this function creates and allocates a guaranteed size, preallocated
  217. * memory pool. The pool can be used from the mempool_alloc() and mempool_free()
  218. * functions. This function might sleep. Both the alloc_fn() and the free_fn()
  219. * functions might sleep - as long as the mempool_alloc() function is not called
  220. * from IRQ contexts.
  221. *
  222. * Return: pointer to the created memory pool object or %NULL on error.
  223. */
  224. mempool_t *mempool_create(int min_nr, mempool_alloc_t *alloc_fn,
  225. mempool_free_t *free_fn, void *pool_data)
  226. {
  227. return mempool_create_node(min_nr, alloc_fn, free_fn, pool_data,
  228. GFP_KERNEL, NUMA_NO_NODE);
  229. }
  230. EXPORT_SYMBOL(mempool_create);
  231. mempool_t *mempool_create_node(int min_nr, mempool_alloc_t *alloc_fn,
  232. mempool_free_t *free_fn, void *pool_data,
  233. gfp_t gfp_mask, int node_id)
  234. {
  235. mempool_t *pool;
  236. pool = kzalloc_node(sizeof(*pool), gfp_mask, node_id);
  237. if (!pool)
  238. return NULL;
  239. if (mempool_init_node(pool, min_nr, alloc_fn, free_fn, pool_data,
  240. gfp_mask, node_id)) {
  241. kfree(pool);
  242. return NULL;
  243. }
  244. return pool;
  245. }
  246. EXPORT_SYMBOL(mempool_create_node);
  247. /**
  248. * mempool_resize - resize an existing memory pool
  249. * @pool: pointer to the memory pool which was allocated via
  250. * mempool_create().
  251. * @new_min_nr: the new minimum number of elements guaranteed to be
  252. * allocated for this pool.
  253. *
  254. * This function shrinks/grows the pool. In the case of growing,
  255. * it cannot be guaranteed that the pool will be grown to the new
  256. * size immediately, but new mempool_free() calls will refill it.
  257. * This function may sleep.
  258. *
  259. * Note, the caller must guarantee that no mempool_destroy is called
  260. * while this function is running. mempool_alloc() & mempool_free()
  261. * might be called (eg. from IRQ contexts) while this function executes.
  262. *
  263. * Return: %0 on success, negative error code otherwise.
  264. */
  265. int mempool_resize(mempool_t *pool, int new_min_nr)
  266. {
  267. void *element;
  268. void **new_elements;
  269. unsigned long flags;
  270. BUG_ON(new_min_nr <= 0);
  271. might_sleep();
  272. spin_lock_irqsave(&pool->lock, flags);
  273. if (new_min_nr <= pool->min_nr) {
  274. while (new_min_nr < pool->curr_nr) {
  275. element = remove_element(pool);
  276. spin_unlock_irqrestore(&pool->lock, flags);
  277. pool->free(element, pool->pool_data);
  278. spin_lock_irqsave(&pool->lock, flags);
  279. }
  280. pool->min_nr = new_min_nr;
  281. goto out_unlock;
  282. }
  283. spin_unlock_irqrestore(&pool->lock, flags);
  284. /* Grow the pool */
  285. new_elements = kmalloc_array(new_min_nr, sizeof(*new_elements),
  286. GFP_KERNEL);
  287. if (!new_elements)
  288. return -ENOMEM;
  289. spin_lock_irqsave(&pool->lock, flags);
  290. if (unlikely(new_min_nr <= pool->min_nr)) {
  291. /* Raced, other resize will do our work */
  292. spin_unlock_irqrestore(&pool->lock, flags);
  293. kfree(new_elements);
  294. goto out;
  295. }
  296. memcpy(new_elements, pool->elements,
  297. pool->curr_nr * sizeof(*new_elements));
  298. kfree(pool->elements);
  299. pool->elements = new_elements;
  300. pool->min_nr = new_min_nr;
  301. while (pool->curr_nr < pool->min_nr) {
  302. spin_unlock_irqrestore(&pool->lock, flags);
  303. element = pool->alloc(GFP_KERNEL, pool->pool_data);
  304. if (!element)
  305. goto out;
  306. spin_lock_irqsave(&pool->lock, flags);
  307. if (pool->curr_nr < pool->min_nr) {
  308. add_element(pool, element);
  309. } else {
  310. spin_unlock_irqrestore(&pool->lock, flags);
  311. pool->free(element, pool->pool_data); /* Raced */
  312. goto out;
  313. }
  314. }
  315. out_unlock:
  316. spin_unlock_irqrestore(&pool->lock, flags);
  317. out:
  318. return 0;
  319. }
  320. EXPORT_SYMBOL(mempool_resize);
  321. /**
  322. * mempool_alloc - allocate an element from a specific memory pool
  323. * @pool: pointer to the memory pool which was allocated via
  324. * mempool_create().
  325. * @gfp_mask: the usual allocation bitmask.
  326. *
  327. * this function only sleeps if the alloc_fn() function sleeps or
  328. * returns NULL. Note that due to preallocation, this function
  329. * *never* fails when called from process contexts. (it might
  330. * fail if called from an IRQ context.)
  331. * Note: using __GFP_ZERO is not supported.
  332. *
  333. * Return: pointer to the allocated element or %NULL on error.
  334. */
  335. void *mempool_alloc(mempool_t *pool, gfp_t gfp_mask)
  336. {
  337. void *element;
  338. unsigned long flags;
  339. wait_queue_entry_t wait;
  340. gfp_t gfp_temp;
  341. VM_WARN_ON_ONCE(gfp_mask & __GFP_ZERO);
  342. might_alloc(gfp_mask);
  343. gfp_mask |= __GFP_NOMEMALLOC; /* don't allocate emergency reserves */
  344. gfp_mask |= __GFP_NORETRY; /* don't loop in __alloc_pages */
  345. gfp_mask |= __GFP_NOWARN; /* failures are OK */
  346. gfp_temp = gfp_mask & ~(__GFP_DIRECT_RECLAIM|__GFP_IO);
  347. repeat_alloc:
  348. element = pool->alloc(gfp_temp, pool->pool_data);
  349. if (likely(element != NULL))
  350. return element;
  351. spin_lock_irqsave(&pool->lock, flags);
  352. if (likely(pool->curr_nr)) {
  353. element = remove_element(pool);
  354. spin_unlock_irqrestore(&pool->lock, flags);
  355. /* paired with rmb in mempool_free(), read comment there */
  356. smp_wmb();
  357. /*
  358. * Update the allocation stack trace as this is more useful
  359. * for debugging.
  360. */
  361. kmemleak_update_trace(element);
  362. return element;
  363. }
  364. /*
  365. * We use gfp mask w/o direct reclaim or IO for the first round. If
  366. * alloc failed with that and @pool was empty, retry immediately.
  367. */
  368. if (gfp_temp != gfp_mask) {
  369. spin_unlock_irqrestore(&pool->lock, flags);
  370. gfp_temp = gfp_mask;
  371. goto repeat_alloc;
  372. }
  373. /* We must not sleep if !__GFP_DIRECT_RECLAIM */
  374. if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) {
  375. spin_unlock_irqrestore(&pool->lock, flags);
  376. return NULL;
  377. }
  378. /* Let's wait for someone else to return an element to @pool */
  379. init_wait(&wait);
  380. prepare_to_wait(&pool->wait, &wait, TASK_UNINTERRUPTIBLE);
  381. spin_unlock_irqrestore(&pool->lock, flags);
  382. /*
  383. * FIXME: this should be io_schedule(). The timeout is there as a
  384. * workaround for some DM problems in 2.6.18.
  385. */
  386. io_schedule_timeout(5*HZ);
  387. finish_wait(&pool->wait, &wait);
  388. goto repeat_alloc;
  389. }
  390. EXPORT_SYMBOL(mempool_alloc);
  391. /**
  392. * mempool_free - return an element to the pool.
  393. * @element: pool element pointer.
  394. * @pool: pointer to the memory pool which was allocated via
  395. * mempool_create().
  396. *
  397. * this function only sleeps if the free_fn() function sleeps.
  398. */
  399. void mempool_free(void *element, mempool_t *pool)
  400. {
  401. unsigned long flags;
  402. if (unlikely(element == NULL))
  403. return;
  404. /*
  405. * Paired with the wmb in mempool_alloc(). The preceding read is
  406. * for @element and the following @pool->curr_nr. This ensures
  407. * that the visible value of @pool->curr_nr is from after the
  408. * allocation of @element. This is necessary for fringe cases
  409. * where @element was passed to this task without going through
  410. * barriers.
  411. *
  412. * For example, assume @p is %NULL at the beginning and one task
  413. * performs "p = mempool_alloc(...);" while another task is doing
  414. * "while (!p) cpu_relax(); mempool_free(p, ...);". This function
  415. * may end up using curr_nr value which is from before allocation
  416. * of @p without the following rmb.
  417. */
  418. smp_rmb();
  419. /*
  420. * For correctness, we need a test which is guaranteed to trigger
  421. * if curr_nr + #allocated == min_nr. Testing curr_nr < min_nr
  422. * without locking achieves that and refilling as soon as possible
  423. * is desirable.
  424. *
  425. * Because curr_nr visible here is always a value after the
  426. * allocation of @element, any task which decremented curr_nr below
  427. * min_nr is guaranteed to see curr_nr < min_nr unless curr_nr gets
  428. * incremented to min_nr afterwards. If curr_nr gets incremented
  429. * to min_nr after the allocation of @element, the elements
  430. * allocated after that are subject to the same guarantee.
  431. *
  432. * Waiters happen iff curr_nr is 0 and the above guarantee also
  433. * ensures that there will be frees which return elements to the
  434. * pool waking up the waiters.
  435. */
  436. if (unlikely(READ_ONCE(pool->curr_nr) < pool->min_nr)) {
  437. spin_lock_irqsave(&pool->lock, flags);
  438. if (likely(pool->curr_nr < pool->min_nr)) {
  439. add_element(pool, element);
  440. spin_unlock_irqrestore(&pool->lock, flags);
  441. wake_up(&pool->wait);
  442. return;
  443. }
  444. spin_unlock_irqrestore(&pool->lock, flags);
  445. }
  446. pool->free(element, pool->pool_data);
  447. }
  448. EXPORT_SYMBOL(mempool_free);
  449. /*
  450. * A commonly used alloc and free fn.
  451. */
  452. void *mempool_alloc_slab(gfp_t gfp_mask, void *pool_data)
  453. {
  454. struct kmem_cache *mem = pool_data;
  455. VM_BUG_ON(mem->ctor);
  456. return kmem_cache_alloc(mem, gfp_mask);
  457. }
  458. EXPORT_SYMBOL(mempool_alloc_slab);
  459. void mempool_free_slab(void *element, void *pool_data)
  460. {
  461. struct kmem_cache *mem = pool_data;
  462. kmem_cache_free(mem, element);
  463. }
  464. EXPORT_SYMBOL(mempool_free_slab);
  465. /*
  466. * A commonly used alloc and free fn that kmalloc/kfrees the amount of memory
  467. * specified by pool_data
  468. */
  469. void *mempool_kmalloc(gfp_t gfp_mask, void *pool_data)
  470. {
  471. size_t size = (size_t)pool_data;
  472. return kmalloc(size, gfp_mask);
  473. }
  474. EXPORT_SYMBOL(mempool_kmalloc);
  475. void mempool_kfree(void *element, void *pool_data)
  476. {
  477. kfree(element);
  478. }
  479. EXPORT_SYMBOL(mempool_kfree);
  480. /*
  481. * A simple mempool-backed page allocator that allocates pages
  482. * of the order specified by pool_data.
  483. */
  484. void *mempool_alloc_pages(gfp_t gfp_mask, void *pool_data)
  485. {
  486. int order = (int)(long)pool_data;
  487. return alloc_pages(gfp_mask, order);
  488. }
  489. EXPORT_SYMBOL(mempool_alloc_pages);
  490. void mempool_free_pages(void *element, void *pool_data)
  491. {
  492. int order = (int)(long)pool_data;
  493. __free_pages(element, order);
  494. }
  495. EXPORT_SYMBOL(mempool_free_pages);