1 // SPDX-License-Identifier: GPL-2.0
3 * drivers/staging/android/ion/ion_mem_pool.c
5 * Copyright (C) 2011 Google, Inc.
8 #include <linux/list.h>
9 #include <linux/slab.h>
10 #include <linux/swap.h>
11 #include <linux/sched/signal.h>
15 static inline struct page *ion_page_pool_alloc_pages(struct ion_page_pool *pool)
17 if (fatal_signal_pending(current))
19 return alloc_pages(pool->gfp_mask, pool->order);
22 static void ion_page_pool_free_pages(struct ion_page_pool *pool,
25 __free_pages(page, pool->order);
28 static void ion_page_pool_add(struct ion_page_pool *pool, struct page *page)
30 mutex_lock(&pool->mutex);
31 if (PageHighMem(page)) {
32 list_add_tail(&page->lru, &pool->high_items);
35 list_add_tail(&page->lru, &pool->low_items);
39 mod_node_page_state(page_pgdat(page), NR_INDIRECTLY_RECLAIMABLE_BYTES,
40 (1 << (PAGE_SHIFT + pool->order)));
41 mutex_unlock(&pool->mutex);
44 static struct page *ion_page_pool_remove(struct ion_page_pool *pool, bool high)
49 BUG_ON(!pool->high_count);
50 page = list_first_entry(&pool->high_items, struct page, lru);
53 BUG_ON(!pool->low_count);
54 page = list_first_entry(&pool->low_items, struct page, lru);
59 mod_node_page_state(page_pgdat(page), NR_INDIRECTLY_RECLAIMABLE_BYTES,
60 -(1 << (PAGE_SHIFT + pool->order)));
64 struct page *ion_page_pool_alloc(struct ion_page_pool *pool)
66 struct page *page = NULL;
70 mutex_lock(&pool->mutex);
72 page = ion_page_pool_remove(pool, true);
73 else if (pool->low_count)
74 page = ion_page_pool_remove(pool, false);
75 mutex_unlock(&pool->mutex);
78 page = ion_page_pool_alloc_pages(pool);
83 void ion_page_pool_free(struct ion_page_pool *pool, struct page *page)
85 BUG_ON(pool->order != compound_order(page));
87 ion_page_pool_add(pool, page);
90 static int ion_page_pool_total(struct ion_page_pool *pool, bool high)
92 int count = pool->low_count;
95 count += pool->high_count;
97 return count << pool->order;
100 int ion_page_pool_shrink(struct ion_page_pool *pool, gfp_t gfp_mask,
106 if (current_is_kswapd())
109 high = !!(gfp_mask & __GFP_HIGHMEM);
112 return ion_page_pool_total(pool, high);
114 while (freed < nr_to_scan) {
117 mutex_lock(&pool->mutex);
118 if (pool->low_count) {
119 page = ion_page_pool_remove(pool, false);
120 } else if (high && pool->high_count) {
121 page = ion_page_pool_remove(pool, true);
123 mutex_unlock(&pool->mutex);
126 mutex_unlock(&pool->mutex);
127 ion_page_pool_free_pages(pool, page);
128 freed += (1 << pool->order);
134 struct ion_page_pool *ion_page_pool_create(gfp_t gfp_mask, unsigned int order)
136 struct ion_page_pool *pool = kmalloc(sizeof(*pool), GFP_KERNEL);
140 pool->high_count = 0;
142 INIT_LIST_HEAD(&pool->low_items);
143 INIT_LIST_HEAD(&pool->high_items);
144 pool->gfp_mask = gfp_mask | __GFP_COMP;
146 mutex_init(&pool->mutex);
147 plist_node_init(&pool->list, order);
152 void ion_page_pool_destroy(struct ion_page_pool *pool)