xref: /linux/mm/cma.c (revision 957e3facd147510f2cf8780e38606f1d707f0e33)
1 /*
2  * Contiguous Memory Allocator
3  *
4  * Copyright (c) 2010-2011 by Samsung Electronics.
5  * Copyright IBM Corporation, 2013
6  * Copyright LG Electronics Inc., 2014
7  * Written by:
8  *	Marek Szyprowski <m.szyprowski@samsung.com>
9  *	Michal Nazarewicz <mina86@mina86.com>
10  *	Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com>
11  *	Joonsoo Kim <iamjoonsoo.kim@lge.com>
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License as
15  * published by the Free Software Foundation; either version 2 of the
16  * License or (at your optional) any later version of the license.
17  */
18 
19 #define pr_fmt(fmt) "cma: " fmt
20 
21 #ifdef CONFIG_CMA_DEBUG
22 #ifndef DEBUG
23 #  define DEBUG
24 #endif
25 #endif
26 
27 #include <linux/memblock.h>
28 #include <linux/err.h>
29 #include <linux/mm.h>
30 #include <linux/mutex.h>
31 #include <linux/sizes.h>
32 #include <linux/slab.h>
33 #include <linux/log2.h>
34 #include <linux/cma.h>
35 #include <linux/highmem.h>
36 
37 struct cma {
38 	unsigned long	base_pfn;
39 	unsigned long	count;
40 	unsigned long	*bitmap;
41 	unsigned int order_per_bit; /* Order of pages represented by one bit */
42 	struct mutex	lock;
43 };
44 
45 static struct cma cma_areas[MAX_CMA_AREAS];
46 static unsigned cma_area_count;
47 static DEFINE_MUTEX(cma_mutex);
48 
49 phys_addr_t cma_get_base(struct cma *cma)
50 {
51 	return PFN_PHYS(cma->base_pfn);
52 }
53 
54 unsigned long cma_get_size(struct cma *cma)
55 {
56 	return cma->count << PAGE_SHIFT;
57 }
58 
59 static unsigned long cma_bitmap_aligned_mask(struct cma *cma, int align_order)
60 {
61 	if (align_order <= cma->order_per_bit)
62 		return 0;
63 	return (1UL << (align_order - cma->order_per_bit)) - 1;
64 }
65 
66 static unsigned long cma_bitmap_aligned_offset(struct cma *cma, int align_order)
67 {
68 	unsigned int alignment;
69 
70 	if (align_order <= cma->order_per_bit)
71 		return 0;
72 	alignment = 1UL << (align_order - cma->order_per_bit);
73 	return ALIGN(cma->base_pfn, alignment) -
74 		(cma->base_pfn >> cma->order_per_bit);
75 }
76 
77 static unsigned long cma_bitmap_maxno(struct cma *cma)
78 {
79 	return cma->count >> cma->order_per_bit;
80 }
81 
82 static unsigned long cma_bitmap_pages_to_bits(struct cma *cma,
83 						unsigned long pages)
84 {
85 	return ALIGN(pages, 1UL << cma->order_per_bit) >> cma->order_per_bit;
86 }
87 
88 static void cma_clear_bitmap(struct cma *cma, unsigned long pfn, int count)
89 {
90 	unsigned long bitmap_no, bitmap_count;
91 
92 	bitmap_no = (pfn - cma->base_pfn) >> cma->order_per_bit;
93 	bitmap_count = cma_bitmap_pages_to_bits(cma, count);
94 
95 	mutex_lock(&cma->lock);
96 	bitmap_clear(cma->bitmap, bitmap_no, bitmap_count);
97 	mutex_unlock(&cma->lock);
98 }
99 
100 static int __init cma_activate_area(struct cma *cma)
101 {
102 	int bitmap_size = BITS_TO_LONGS(cma_bitmap_maxno(cma)) * sizeof(long);
103 	unsigned long base_pfn = cma->base_pfn, pfn = base_pfn;
104 	unsigned i = cma->count >> pageblock_order;
105 	struct zone *zone;
106 
107 	cma->bitmap = kzalloc(bitmap_size, GFP_KERNEL);
108 
109 	if (!cma->bitmap)
110 		return -ENOMEM;
111 
112 	WARN_ON_ONCE(!pfn_valid(pfn));
113 	zone = page_zone(pfn_to_page(pfn));
114 
115 	do {
116 		unsigned j;
117 
118 		base_pfn = pfn;
119 		for (j = pageblock_nr_pages; j; --j, pfn++) {
120 			WARN_ON_ONCE(!pfn_valid(pfn));
121 			/*
122 			 * alloc_contig_range requires the pfn range
123 			 * specified to be in the same zone. Make this
124 			 * simple by forcing the entire CMA resv range
125 			 * to be in the same zone.
126 			 */
127 			if (page_zone(pfn_to_page(pfn)) != zone)
128 				goto err;
129 		}
130 		init_cma_reserved_pageblock(pfn_to_page(base_pfn));
131 	} while (--i);
132 
133 	mutex_init(&cma->lock);
134 	return 0;
135 
136 err:
137 	kfree(cma->bitmap);
138 	cma->count = 0;
139 	return -EINVAL;
140 }
141 
142 static int __init cma_init_reserved_areas(void)
143 {
144 	int i;
145 
146 	for (i = 0; i < cma_area_count; i++) {
147 		int ret = cma_activate_area(&cma_areas[i]);
148 
149 		if (ret)
150 			return ret;
151 	}
152 
153 	return 0;
154 }
155 core_initcall(cma_init_reserved_areas);
156 
157 /**
158  * cma_init_reserved_mem() - create custom contiguous area from reserved memory
159  * @base: Base address of the reserved area
160  * @size: Size of the reserved area (in bytes),
161  * @order_per_bit: Order of pages represented by one bit on bitmap.
162  * @res_cma: Pointer to store the created cma region.
163  *
164  * This function creates custom contiguous area from already reserved memory.
165  */
166 int __init cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
167 				 int order_per_bit, struct cma **res_cma)
168 {
169 	struct cma *cma;
170 	phys_addr_t alignment;
171 
172 	/* Sanity checks */
173 	if (cma_area_count == ARRAY_SIZE(cma_areas)) {
174 		pr_err("Not enough slots for CMA reserved regions!\n");
175 		return -ENOSPC;
176 	}
177 
178 	if (!size || !memblock_is_region_reserved(base, size))
179 		return -EINVAL;
180 
181 	/* ensure minimal alignment requied by mm core */
182 	alignment = PAGE_SIZE << max(MAX_ORDER - 1, pageblock_order);
183 
184 	/* alignment should be aligned with order_per_bit */
185 	if (!IS_ALIGNED(alignment >> PAGE_SHIFT, 1 << order_per_bit))
186 		return -EINVAL;
187 
188 	if (ALIGN(base, alignment) != base || ALIGN(size, alignment) != size)
189 		return -EINVAL;
190 
191 	/*
192 	 * Each reserved area must be initialised later, when more kernel
193 	 * subsystems (like slab allocator) are available.
194 	 */
195 	cma = &cma_areas[cma_area_count];
196 	cma->base_pfn = PFN_DOWN(base);
197 	cma->count = size >> PAGE_SHIFT;
198 	cma->order_per_bit = order_per_bit;
199 	*res_cma = cma;
200 	cma_area_count++;
201 
202 	return 0;
203 }
204 
205 /**
206  * cma_declare_contiguous() - reserve custom contiguous area
207  * @base: Base address of the reserved area optional, use 0 for any
208  * @size: Size of the reserved area (in bytes),
209  * @limit: End address of the reserved memory (optional, 0 for any).
210  * @alignment: Alignment for the CMA area, should be power of 2 or zero
211  * @order_per_bit: Order of pages represented by one bit on bitmap.
212  * @fixed: hint about where to place the reserved area
213  * @res_cma: Pointer to store the created cma region.
214  *
215  * This function reserves memory from early allocator. It should be
216  * called by arch specific code once the early allocator (memblock or bootmem)
217  * has been activated and all other subsystems have already allocated/reserved
218  * memory. This function allows to create custom reserved areas.
219  *
220  * If @fixed is true, reserve contiguous area at exactly @base.  If false,
221  * reserve in range from @base to @limit.
222  */
223 int __init cma_declare_contiguous(phys_addr_t base,
224 			phys_addr_t size, phys_addr_t limit,
225 			phys_addr_t alignment, unsigned int order_per_bit,
226 			bool fixed, struct cma **res_cma)
227 {
228 	phys_addr_t memblock_end = memblock_end_of_DRAM();
229 	phys_addr_t highmem_start;
230 	int ret = 0;
231 
232 #ifdef CONFIG_X86
233 	/*
234 	 * high_memory isn't direct mapped memory so retrieving its physical
235 	 * address isn't appropriate.  But it would be useful to check the
236 	 * physical address of the highmem boundary so it's justfiable to get
237 	 * the physical address from it.  On x86 there is a validation check for
238 	 * this case, so the following workaround is needed to avoid it.
239 	 */
240 	highmem_start = __pa_nodebug(high_memory);
241 #else
242 	highmem_start = __pa(high_memory);
243 #endif
244 	pr_debug("%s(size %pa, base %pa, limit %pa alignment %pa)\n",
245 		__func__, &size, &base, &limit, &alignment);
246 
247 	if (cma_area_count == ARRAY_SIZE(cma_areas)) {
248 		pr_err("Not enough slots for CMA reserved regions!\n");
249 		return -ENOSPC;
250 	}
251 
252 	if (!size)
253 		return -EINVAL;
254 
255 	if (alignment && !is_power_of_2(alignment))
256 		return -EINVAL;
257 
258 	/*
259 	 * Sanitise input arguments.
260 	 * Pages both ends in CMA area could be merged into adjacent unmovable
261 	 * migratetype page by page allocator's buddy algorithm. In the case,
262 	 * you couldn't get a contiguous memory, which is not what we want.
263 	 */
264 	alignment = max(alignment,
265 		(phys_addr_t)PAGE_SIZE << max(MAX_ORDER - 1, pageblock_order));
266 	base = ALIGN(base, alignment);
267 	size = ALIGN(size, alignment);
268 	limit &= ~(alignment - 1);
269 
270 	if (!base)
271 		fixed = false;
272 
273 	/* size should be aligned with order_per_bit */
274 	if (!IS_ALIGNED(size >> PAGE_SHIFT, 1 << order_per_bit))
275 		return -EINVAL;
276 
277 	/*
278 	 * If allocating at a fixed base the request region must not cross the
279 	 * low/high memory boundary.
280 	 */
281 	if (fixed && base < highmem_start && base + size > highmem_start) {
282 		ret = -EINVAL;
283 		pr_err("Region at %pa defined on low/high memory boundary (%pa)\n",
284 			&base, &highmem_start);
285 		goto err;
286 	}
287 
288 	/*
289 	 * If the limit is unspecified or above the memblock end, its effective
290 	 * value will be the memblock end. Set it explicitly to simplify further
291 	 * checks.
292 	 */
293 	if (limit == 0 || limit > memblock_end)
294 		limit = memblock_end;
295 
296 	/* Reserve memory */
297 	if (fixed) {
298 		if (memblock_is_region_reserved(base, size) ||
299 		    memblock_reserve(base, size) < 0) {
300 			ret = -EBUSY;
301 			goto err;
302 		}
303 	} else {
304 		phys_addr_t addr = 0;
305 
306 		/*
307 		 * All pages in the reserved area must come from the same zone.
308 		 * If the requested region crosses the low/high memory boundary,
309 		 * try allocating from high memory first and fall back to low
310 		 * memory in case of failure.
311 		 */
312 		if (base < highmem_start && limit > highmem_start) {
313 			addr = memblock_alloc_range(size, alignment,
314 						    highmem_start, limit);
315 			limit = highmem_start;
316 		}
317 
318 		if (!addr) {
319 			addr = memblock_alloc_range(size, alignment, base,
320 						    limit);
321 			if (!addr) {
322 				ret = -ENOMEM;
323 				goto err;
324 			}
325 		}
326 
327 		base = addr;
328 	}
329 
330 	ret = cma_init_reserved_mem(base, size, order_per_bit, res_cma);
331 	if (ret)
332 		goto err;
333 
334 	pr_info("Reserved %ld MiB at %pa\n", (unsigned long)size / SZ_1M,
335 		&base);
336 	return 0;
337 
338 err:
339 	pr_err("Failed to reserve %ld MiB\n", (unsigned long)size / SZ_1M);
340 	return ret;
341 }
342 
343 /**
344  * cma_alloc() - allocate pages from contiguous area
345  * @cma:   Contiguous memory region for which the allocation is performed.
346  * @count: Requested number of pages.
347  * @align: Requested alignment of pages (in PAGE_SIZE order).
348  *
349  * This function allocates part of contiguous memory on specific
350  * contiguous memory area.
351  */
352 struct page *cma_alloc(struct cma *cma, int count, unsigned int align)
353 {
354 	unsigned long mask, offset, pfn, start = 0;
355 	unsigned long bitmap_maxno, bitmap_no, bitmap_count;
356 	struct page *page = NULL;
357 	int ret;
358 
359 	if (!cma || !cma->count)
360 		return NULL;
361 
362 	pr_debug("%s(cma %p, count %d, align %d)\n", __func__, (void *)cma,
363 		 count, align);
364 
365 	if (!count)
366 		return NULL;
367 
368 	mask = cma_bitmap_aligned_mask(cma, align);
369 	offset = cma_bitmap_aligned_offset(cma, align);
370 	bitmap_maxno = cma_bitmap_maxno(cma);
371 	bitmap_count = cma_bitmap_pages_to_bits(cma, count);
372 
373 	for (;;) {
374 		mutex_lock(&cma->lock);
375 		bitmap_no = bitmap_find_next_zero_area_off(cma->bitmap,
376 				bitmap_maxno, start, bitmap_count, mask,
377 				offset);
378 		if (bitmap_no >= bitmap_maxno) {
379 			mutex_unlock(&cma->lock);
380 			break;
381 		}
382 		bitmap_set(cma->bitmap, bitmap_no, bitmap_count);
383 		/*
384 		 * It's safe to drop the lock here. We've marked this region for
385 		 * our exclusive use. If the migration fails we will take the
386 		 * lock again and unmark it.
387 		 */
388 		mutex_unlock(&cma->lock);
389 
390 		pfn = cma->base_pfn + (bitmap_no << cma->order_per_bit);
391 		mutex_lock(&cma_mutex);
392 		ret = alloc_contig_range(pfn, pfn + count, MIGRATE_CMA);
393 		mutex_unlock(&cma_mutex);
394 		if (ret == 0) {
395 			page = pfn_to_page(pfn);
396 			break;
397 		}
398 
399 		cma_clear_bitmap(cma, pfn, count);
400 		if (ret != -EBUSY)
401 			break;
402 
403 		pr_debug("%s(): memory range at %p is busy, retrying\n",
404 			 __func__, pfn_to_page(pfn));
405 		/* try again with a bit different memory target */
406 		start = bitmap_no + mask + 1;
407 	}
408 
409 	pr_debug("%s(): returned %p\n", __func__, page);
410 	return page;
411 }
412 
413 /**
414  * cma_release() - release allocated pages
415  * @cma:   Contiguous memory region for which the allocation is performed.
416  * @pages: Allocated pages.
417  * @count: Number of allocated pages.
418  *
419  * This function releases memory allocated by alloc_cma().
420  * It returns false when provided pages do not belong to contiguous area and
421  * true otherwise.
422  */
423 bool cma_release(struct cma *cma, struct page *pages, int count)
424 {
425 	unsigned long pfn;
426 
427 	if (!cma || !pages)
428 		return false;
429 
430 	pr_debug("%s(page %p)\n", __func__, (void *)pages);
431 
432 	pfn = page_to_pfn(pages);
433 
434 	if (pfn < cma->base_pfn || pfn >= cma->base_pfn + cma->count)
435 		return false;
436 
437 	VM_BUG_ON(pfn + count > cma->base_pfn + cma->count);
438 
439 	free_contig_range(pfn, count);
440 	cma_clear_bitmap(cma, pfn, count);
441 
442 	return true;
443 }
444