xref: /linux/kernel/dma/contiguous.c (revision 27e2e9b9b49c5d5260969168b86cd238254b9105)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Contiguous Memory Allocator for DMA mapping framework
4  * Copyright (c) 2010-2011 by Samsung Electronics.
5  * Written by:
6  *	Marek Szyprowski <m.szyprowski@samsung.com>
7  *	Michal Nazarewicz <mina86@mina86.com>
8  *
9  * Contiguous Memory Allocator
10  *
11  *   The Contiguous Memory Allocator (CMA) makes it possible to
12  *   allocate big contiguous chunks of memory after the system has
13  *   booted.
14  *
15  * Why is it needed?
16  *
17  *   Various devices on embedded systems have no scatter-getter and/or
18  *   IO map support and require contiguous blocks of memory to
19  *   operate.  They include devices such as cameras, hardware video
20  *   coders, etc.
21  *
22  *   Such devices often require big memory buffers (a full HD frame
23  *   is, for instance, more than 2 mega pixels large, i.e. more than 6
24  *   MB of memory), which makes mechanisms such as kmalloc() or
25  *   alloc_page() ineffective.
26  *
27  *   At the same time, a solution where a big memory region is
28  *   reserved for a device is suboptimal since often more memory is
29  *   reserved then strictly required and, moreover, the memory is
30  *   inaccessible to page system even if device drivers don't use it.
31  *
32  *   CMA tries to solve this issue by operating on memory regions
33  *   where only movable pages can be allocated from.  This way, kernel
34  *   can use the memory for pagecache and when device driver requests
35  *   it, allocated pages can be migrated.
36  */
37 
38 #define pr_fmt(fmt) "cma: " fmt
39 
40 #include <asm/page.h>
41 
42 #include <linux/memblock.h>
43 #include <linux/err.h>
44 #include <linux/sizes.h>
45 #include <linux/dma-map-ops.h>
46 #include <linux/cma.h>
47 #include <linux/nospec.h>
48 
49 #ifdef CONFIG_CMA_SIZE_MBYTES
50 #define CMA_SIZE_MBYTES CONFIG_CMA_SIZE_MBYTES
51 #else
52 #define CMA_SIZE_MBYTES 0
53 #endif
54 
55 static struct cma *dma_contiguous_areas[MAX_CMA_AREAS];
56 static unsigned int dma_contiguous_areas_num;
57 
58 static int dma_contiguous_insert_area(struct cma *cma)
59 {
60 	if (dma_contiguous_areas_num >= ARRAY_SIZE(dma_contiguous_areas))
61 		return -EINVAL;
62 
63 	dma_contiguous_areas[dma_contiguous_areas_num++] = cma;
64 
65 	return 0;
66 }
67 
68 /**
69  * dma_contiguous_get_area_by_idx() - Get contiguous area at given index
70  * @idx: index of the area we query
71  *
72  * Queries for the contiguous area located at index @idx.
73  *
74  * Returns:
75  * A pointer to the requested contiguous area, or NULL otherwise.
76  */
77 struct cma *dma_contiguous_get_area_by_idx(unsigned int idx)
78 {
79 	if (idx >= dma_contiguous_areas_num)
80 		return NULL;
81 
82 	return dma_contiguous_areas[idx];
83 }
84 EXPORT_SYMBOL_GPL(dma_contiguous_get_area_by_idx);
85 
86 static struct cma *dma_contiguous_default_area;
87 
88 /*
89  * Default global CMA area size can be defined in kernel's .config.
90  * This is useful mainly for distro maintainers to create a kernel
91  * that works correctly for most supported systems.
92  * The size can be set in bytes or as a percentage of the total memory
93  * in the system.
94  *
95  * Users, who want to set the size of global CMA area for their system
96  * should use cma= kernel parameter.
97  */
98 #define size_bytes ((phys_addr_t)CMA_SIZE_MBYTES * SZ_1M)
99 static phys_addr_t  size_cmdline __initdata = -1;
100 static phys_addr_t base_cmdline __initdata;
101 static phys_addr_t limit_cmdline __initdata;
102 
103 static int __init early_cma(char *p)
104 {
105 	if (!p) {
106 		pr_err("Config string not provided\n");
107 		return -EINVAL;
108 	}
109 
110 	size_cmdline = memparse(p, &p);
111 	if (*p != '@')
112 		return 0;
113 	base_cmdline = memparse(p + 1, &p);
114 	if (*p != '-') {
115 		limit_cmdline = base_cmdline + size_cmdline;
116 		return 0;
117 	}
118 	limit_cmdline = memparse(p + 1, &p);
119 
120 	return 0;
121 }
122 early_param("cma", early_cma);
123 
124 struct cma *dev_get_cma_area(struct device *dev)
125 {
126 	if (dev && dev->cma_area)
127 		return dev->cma_area;
128 
129 	return dma_contiguous_default_area;
130 }
131 EXPORT_SYMBOL_GPL(dev_get_cma_area);
132 
133 #ifdef CONFIG_DMA_NUMA_CMA
134 
135 static struct cma *dma_contiguous_numa_area[MAX_NUMNODES];
136 static phys_addr_t numa_cma_size[MAX_NUMNODES] __initdata;
137 static struct cma *dma_contiguous_pernuma_area[MAX_NUMNODES];
138 static phys_addr_t pernuma_size_bytes __initdata;
139 
140 static int __init early_numa_cma(char *p)
141 {
142 	int nid, count = 0;
143 	unsigned long tmp;
144 	char *s = p;
145 
146 	while (*s) {
147 		if (sscanf(s, "%lu%n", &tmp, &count) != 1)
148 			break;
149 
150 		if (s[count] == ':') {
151 			if (tmp >= MAX_NUMNODES)
152 				break;
153 			nid = array_index_nospec(tmp, MAX_NUMNODES);
154 
155 			s += count + 1;
156 			tmp = memparse(s, &s);
157 			numa_cma_size[nid] = tmp;
158 
159 			if (*s == ',')
160 				s++;
161 			else
162 				break;
163 		} else
164 			break;
165 	}
166 
167 	return 0;
168 }
169 early_param("numa_cma", early_numa_cma);
170 
171 static int __init early_cma_pernuma(char *p)
172 {
173 	pernuma_size_bytes = memparse(p, &p);
174 	return 0;
175 }
176 early_param("cma_pernuma", early_cma_pernuma);
177 #endif
178 
179 #ifdef CONFIG_CMA_SIZE_PERCENTAGE
180 
181 static phys_addr_t __init __maybe_unused cma_early_percent_memory(void)
182 {
183 	unsigned long total_pages = PHYS_PFN(memblock_phys_mem_size());
184 
185 	return (total_pages * CONFIG_CMA_SIZE_PERCENTAGE / 100) << PAGE_SHIFT;
186 }
187 
188 #else
189 
190 static inline __maybe_unused phys_addr_t cma_early_percent_memory(void)
191 {
192 	return 0;
193 }
194 
195 #endif
196 
197 #ifdef CONFIG_DMA_NUMA_CMA
198 static void __init dma_numa_cma_reserve(void)
199 {
200 	int nid;
201 
202 	for_each_node(nid) {
203 		int ret;
204 		char name[CMA_MAX_NAME];
205 		struct cma **cma;
206 
207 		if (!node_online(nid)) {
208 			if (pernuma_size_bytes || numa_cma_size[nid])
209 				pr_warn("invalid node %d specified\n", nid);
210 			continue;
211 		}
212 
213 		if (pernuma_size_bytes) {
214 
215 			cma = &dma_contiguous_pernuma_area[nid];
216 			snprintf(name, sizeof(name), "pernuma%d", nid);
217 			ret = cma_declare_contiguous_nid(0, pernuma_size_bytes, 0, 0,
218 							 0, false, name, cma, nid);
219 			if (ret)
220 				pr_warn("%s: reservation failed: err %d, node %d", __func__,
221 					ret, nid);
222 		}
223 
224 		if (numa_cma_size[nid]) {
225 
226 			cma = &dma_contiguous_numa_area[nid];
227 			snprintf(name, sizeof(name), "numa%d", nid);
228 			ret = cma_declare_contiguous_nid(0, numa_cma_size[nid], 0, 0, 0, false,
229 							 name, cma, nid);
230 			if (ret)
231 				pr_warn("%s: reservation failed: err %d, node %d", __func__,
232 					ret, nid);
233 		}
234 	}
235 }
236 #else
237 static inline void __init dma_numa_cma_reserve(void)
238 {
239 }
240 #endif
241 
242 /**
243  * dma_contiguous_reserve() - reserve area(s) for contiguous memory handling
244  * @limit: End address of the reserved memory (optional, 0 for any).
245  *
246  * This function reserves memory from early allocator. It should be
247  * called by arch specific code once the early allocator (memblock or bootmem)
248  * has been activated and all other subsystems have already allocated/reserved
249  * memory.
250  */
251 void __init dma_contiguous_reserve(phys_addr_t limit)
252 {
253 	phys_addr_t selected_size = 0;
254 	phys_addr_t selected_base = 0;
255 	phys_addr_t selected_limit = limit;
256 	bool fixed = false;
257 
258 	dma_numa_cma_reserve();
259 
260 	pr_debug("%s(limit %08lx)\n", __func__, (unsigned long)limit);
261 
262 	if (size_cmdline != -1) {
263 		selected_size = size_cmdline;
264 		selected_base = base_cmdline;
265 
266 		/* Hornor the user setup dma address limit */
267 		selected_limit = limit_cmdline ?: limit;
268 
269 		if (base_cmdline + size_cmdline == limit_cmdline)
270 			fixed = true;
271 	} else {
272 #ifdef CONFIG_CMA_SIZE_SEL_MBYTES
273 		selected_size = size_bytes;
274 #elif defined(CONFIG_CMA_SIZE_SEL_PERCENTAGE)
275 		selected_size = cma_early_percent_memory();
276 #elif defined(CONFIG_CMA_SIZE_SEL_MIN)
277 		selected_size = min(size_bytes, cma_early_percent_memory());
278 #elif defined(CONFIG_CMA_SIZE_SEL_MAX)
279 		selected_size = max(size_bytes, cma_early_percent_memory());
280 #endif
281 	}
282 
283 	if (selected_size && !dma_contiguous_default_area) {
284 		int ret;
285 
286 		pr_debug("%s: reserving %ld MiB for global area\n", __func__,
287 			 (unsigned long)selected_size / SZ_1M);
288 
289 		ret = dma_contiguous_reserve_area(selected_size, selected_base,
290 						  selected_limit,
291 						  &dma_contiguous_default_area,
292 						  fixed);
293 		if (ret)
294 			return;
295 
296 		/*
297 		 * We need to insert the new area in our list to avoid
298 		 * any inconsistencies between having the default area
299 		 * listed in the DT or not.
300 		 *
301 		 * The DT case is handled by rmem_cma_setup() and will
302 		 * always insert all its areas in our list. However, if
303 		 * it didn't run (because OF_RESERVED_MEM isn't set, or
304 		 * there's no DT region specified), then we don't have a
305 		 * default area yet, and no area in our list.
306 		 *
307 		 * This block creates the default area in such a case,
308 		 * but we also need to insert it in our list to avoid
309 		 * having a default area but an empty list.
310 		 */
311 		ret = dma_contiguous_insert_area(dma_contiguous_default_area);
312 		if (ret)
313 			pr_warn("Couldn't queue default CMA region for heap creation.");
314 	}
315 }
316 
317 void __weak
318 dma_contiguous_early_fixup(phys_addr_t base, unsigned long size)
319 {
320 }
321 
322 /**
323  * dma_contiguous_reserve_area() - reserve custom contiguous area
324  * @size: Size of the reserved area (in bytes),
325  * @base: Base address of the reserved area optional, use 0 for any
326  * @limit: End address of the reserved memory (optional, 0 for any).
327  * @res_cma: Pointer to store the created cma region.
328  * @fixed: hint about where to place the reserved area
329  *
330  * This function reserves memory from early allocator. It should be
331  * called by arch specific code once the early allocator (memblock or bootmem)
332  * has been activated and all other subsystems have already allocated/reserved
333  * memory. This function allows to create custom reserved areas for specific
334  * devices.
335  *
336  * If @fixed is true, reserve contiguous area at exactly @base.  If false,
337  * reserve in range from @base to @limit.
338  */
339 int __init dma_contiguous_reserve_area(phys_addr_t size, phys_addr_t base,
340 				       phys_addr_t limit, struct cma **res_cma,
341 				       bool fixed)
342 {
343 	int ret;
344 
345 	ret = cma_declare_contiguous(base, size, limit, 0, 0, fixed,
346 					"reserved", res_cma);
347 	if (ret)
348 		return ret;
349 
350 	/* Architecture specific contiguous memory fixup. */
351 	dma_contiguous_early_fixup(cma_get_base(*res_cma),
352 				cma_get_size(*res_cma));
353 
354 	return 0;
355 }
356 
357 /**
358  * dma_alloc_from_contiguous() - allocate pages from contiguous area
359  * @dev:   Pointer to device for which the allocation is performed.
360  * @count: Requested number of pages.
361  * @align: Requested alignment of pages (in PAGE_SIZE order).
362  * @no_warn: Avoid printing message about failed allocation.
363  *
364  * This function allocates memory buffer for specified device. It uses
365  * device specific contiguous memory area if available or the default
366  * global one. Requires architecture specific dev_get_cma_area() helper
367  * function.
368  */
369 struct page *dma_alloc_from_contiguous(struct device *dev, size_t count,
370 				       unsigned int align, bool no_warn)
371 {
372 	if (align > CONFIG_CMA_ALIGNMENT)
373 		align = CONFIG_CMA_ALIGNMENT;
374 
375 	return cma_alloc(dev_get_cma_area(dev), count, align, no_warn);
376 }
377 
378 /**
379  * dma_release_from_contiguous() - release allocated pages
380  * @dev:   Pointer to device for which the pages were allocated.
381  * @pages: Allocated pages.
382  * @count: Number of allocated pages.
383  *
384  * This function releases memory allocated by dma_alloc_from_contiguous().
385  * It returns false when provided pages do not belong to contiguous area and
386  * true otherwise.
387  */
388 bool dma_release_from_contiguous(struct device *dev, struct page *pages,
389 				 int count)
390 {
391 	return cma_release(dev_get_cma_area(dev), pages, count);
392 }
393 
394 static struct page *cma_alloc_aligned(struct cma *cma, size_t size, gfp_t gfp)
395 {
396 	unsigned int align = min(get_order(size), CONFIG_CMA_ALIGNMENT);
397 
398 	return cma_alloc(cma, size >> PAGE_SHIFT, align, gfp & __GFP_NOWARN);
399 }
400 
401 /**
402  * dma_alloc_contiguous() - allocate contiguous pages
403  * @dev:   Pointer to device for which the allocation is performed.
404  * @size:  Requested allocation size.
405  * @gfp:   Allocation flags.
406  *
407  * tries to use device specific contiguous memory area if available, or it
408  * tries to use per-numa cma, if the allocation fails, it will fallback to
409  * try default global one.
410  *
411  * Note that it bypass one-page size of allocations from the per-numa and
412  * global area as the addresses within one page are always contiguous, so
413  * there is no need to waste CMA pages for that kind; it also helps reduce
414  * fragmentations.
415  */
416 struct page *dma_alloc_contiguous(struct device *dev, size_t size, gfp_t gfp)
417 {
418 #ifdef CONFIG_DMA_NUMA_CMA
419 	int nid = dev_to_node(dev);
420 #endif
421 
422 	/* CMA can be used only in the context which permits sleeping */
423 	if (!gfpflags_allow_blocking(gfp))
424 		return NULL;
425 	if (dev->cma_area)
426 		return cma_alloc_aligned(dev->cma_area, size, gfp);
427 	if (size <= PAGE_SIZE)
428 		return NULL;
429 
430 #ifdef CONFIG_DMA_NUMA_CMA
431 	if (nid != NUMA_NO_NODE && !(gfp & (GFP_DMA | GFP_DMA32))) {
432 		struct cma *cma = dma_contiguous_pernuma_area[nid];
433 		struct page *page;
434 
435 		if (cma) {
436 			page = cma_alloc_aligned(cma, size, gfp);
437 			if (page)
438 				return page;
439 		}
440 
441 		cma = dma_contiguous_numa_area[nid];
442 		if (cma) {
443 			page = cma_alloc_aligned(cma, size, gfp);
444 			if (page)
445 				return page;
446 		}
447 	}
448 #endif
449 	if (!dma_contiguous_default_area)
450 		return NULL;
451 
452 	return cma_alloc_aligned(dma_contiguous_default_area, size, gfp);
453 }
454 
455 /**
456  * dma_free_contiguous() - release allocated pages
457  * @dev:   Pointer to device for which the pages were allocated.
458  * @page:  Pointer to the allocated pages.
459  * @size:  Size of allocated pages.
460  *
461  * This function releases memory allocated by dma_alloc_contiguous(). As the
462  * cma_release returns false when provided pages do not belong to contiguous
463  * area and true otherwise, this function then does a fallback __free_pages()
464  * upon a false-return.
465  */
466 void dma_free_contiguous(struct device *dev, struct page *page, size_t size)
467 {
468 	unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
469 
470 	/* if dev has its own cma, free page from there */
471 	if (dev->cma_area) {
472 		if (cma_release(dev->cma_area, page, count))
473 			return;
474 	} else {
475 		/*
476 		 * otherwise, page is from either per-numa cma or default cma
477 		 */
478 #ifdef CONFIG_DMA_NUMA_CMA
479 		if (cma_release(dma_contiguous_pernuma_area[page_to_nid(page)],
480 					page, count))
481 			return;
482 		if (cma_release(dma_contiguous_numa_area[page_to_nid(page)],
483 					page, count))
484 			return;
485 #endif
486 		if (cma_release(dma_contiguous_default_area, page, count))
487 			return;
488 	}
489 
490 	/* not in any cma, free from buddy */
491 	__free_pages(page, get_order(size));
492 }
493 
494 /*
495  * Support for reserved memory regions defined in device tree
496  */
497 #ifdef CONFIG_OF_RESERVED_MEM
498 #include <linux/of.h>
499 #include <linux/of_fdt.h>
500 #include <linux/of_reserved_mem.h>
501 
502 #undef pr_fmt
503 #define pr_fmt(fmt) fmt
504 
505 static int rmem_cma_device_init(struct reserved_mem *rmem, struct device *dev)
506 {
507 	dev->cma_area = rmem->priv;
508 	return 0;
509 }
510 
511 static void rmem_cma_device_release(struct reserved_mem *rmem,
512 				    struct device *dev)
513 {
514 	dev->cma_area = NULL;
515 }
516 
517 static int __init __rmem_cma_verify_node(unsigned long node)
518 {
519 	if (!of_get_flat_dt_prop(node, "reusable", NULL) ||
520 	    of_get_flat_dt_prop(node, "no-map", NULL))
521 		return -ENODEV;
522 
523 	if (size_cmdline != -1 &&
524 	    of_get_flat_dt_prop(node, "linux,cma-default", NULL)) {
525 		pr_err("Skipping dt linux,cma-default node in favor for \"cma=\" kernel param.\n");
526 		return -EBUSY;
527 	}
528 	return 0;
529 }
530 
531 static int __init rmem_cma_validate(unsigned long node, phys_addr_t *align)
532 {
533 	int ret = __rmem_cma_verify_node(node);
534 
535 	if (ret)
536 		return ret;
537 
538 	if (align)
539 		*align = max_t(phys_addr_t, *align, CMA_MIN_ALIGNMENT_BYTES);
540 
541 	return 0;
542 }
543 
544 static int __init rmem_cma_fixup(unsigned long node, phys_addr_t base,
545 				    phys_addr_t size)
546 {
547 	int ret = __rmem_cma_verify_node(node);
548 
549 	if (ret)
550 		return ret;
551 
552 	/* Architecture specific contiguous memory fixup. */
553 	dma_contiguous_early_fixup(base, size);
554 	return 0;
555 }
556 
557 static int __init rmem_cma_setup(unsigned long node, struct reserved_mem *rmem)
558 {
559 	bool default_cma = of_get_flat_dt_prop(node, "linux,cma-default", NULL);
560 	struct cma *cma;
561 	int ret;
562 
563 	ret = __rmem_cma_verify_node(node);
564 	if (ret)
565 		return ret;
566 
567 	if (!IS_ALIGNED(rmem->base | rmem->size, CMA_MIN_ALIGNMENT_BYTES)) {
568 		pr_err("Reserved memory: incorrect alignment of CMA region\n");
569 		return -EINVAL;
570 	}
571 
572 	ret = cma_init_reserved_mem(rmem->base, rmem->size, 0, rmem->name, &cma);
573 	if (ret) {
574 		pr_err("Reserved memory: unable to setup CMA region\n");
575 		return ret;
576 	}
577 
578 	if (default_cma)
579 		dma_contiguous_default_area = cma;
580 
581 	rmem->priv = cma;
582 
583 	pr_info("Reserved memory: created CMA memory pool at %pa, size %ld MiB\n",
584 		&rmem->base, (unsigned long)rmem->size / SZ_1M);
585 
586 	ret = dma_contiguous_insert_area(cma);
587 	if (ret)
588 		pr_warn("Couldn't store CMA reserved area.");
589 
590 	return 0;
591 }
592 
593 static const struct reserved_mem_ops rmem_cma_ops = {
594 	.node_validate  = rmem_cma_validate,
595 	.node_fixup	= rmem_cma_fixup,
596 	.node_init	= rmem_cma_setup,
597 	.device_init	= rmem_cma_device_init,
598 	.device_release = rmem_cma_device_release,
599 };
600 
601 RESERVEDMEM_OF_DECLARE(cma, "shared-dma-pool", &rmem_cma_ops);
602 #endif
603