xref: /linux/kernel/dma/contiguous.c (revision bba2c3615bd6cfee7456d1130f2e6b01b3f4e9ba)
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 phys_addr_t pernuma_size_bytes __initdata;
138 static bool numa_cma_configured __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 	numa_cma_configured = true;
168 	return 0;
169 }
170 early_param("numa_cma", early_numa_cma);
171 
172 static int __init early_cma_pernuma(char *p)
173 {
174 	pernuma_size_bytes = memparse(p, &p);
175 	numa_cma_configured = true;
176 	return 0;
177 }
178 early_param("cma_pernuma", early_cma_pernuma);
179 #endif
180 
181 #ifdef CONFIG_CMA_SIZE_PERCENTAGE
182 
183 static phys_addr_t __init __maybe_unused cma_early_percent_memory(void)
184 {
185 	unsigned long total_pages = PHYS_PFN(memblock_phys_mem_size());
186 
187 	return (total_pages * CONFIG_CMA_SIZE_PERCENTAGE / 100) << PAGE_SHIFT;
188 }
189 
190 #else
191 
192 static inline __maybe_unused phys_addr_t cma_early_percent_memory(void)
193 {
194 	return 0;
195 }
196 
197 #endif
198 
199 #ifdef CONFIG_DMA_NUMA_CMA
200 static void __init dma_numa_cma_reserve(void)
201 {
202 	int nid;
203 
204 	if (IS_ENABLED(CONFIG_CMA_SIZE_PERNUMA) &&
205 	    !numa_cma_configured && dma_contiguous_default_area &&
206 	    nr_online_nodes > 1)
207 		pernuma_size_bytes = cma_get_size(dma_contiguous_default_area);
208 
209 	for_each_node(nid) {
210 		int size, ret;
211 		char name[CMA_MAX_NAME];
212 		struct cma **cma;
213 
214 		if (!node_online(nid)) {
215 			if (pernuma_size_bytes || numa_cma_size[nid])
216 				pr_warn("invalid node %d specified\n", nid);
217 			continue;
218 		}
219 
220 		/* per-node numa setting has the priority */
221 		size = numa_cma_size[nid] ?: pernuma_size_bytes;
222 		if (!size)
223 			continue;
224 
225 		cma = &dma_contiguous_numa_area[nid];
226 		snprintf(name, sizeof(name), "numa%d", nid);
227 		ret = cma_declare_contiguous_nid(0, size, 0, 0, 0, false, name, cma, nid);
228 		if (ret)
229 			pr_warn("%s: reservation failed: err %d, node %d", __func__,
230 				ret, nid);
231 	}
232 }
233 #else
234 static inline void __init dma_numa_cma_reserve(void)
235 {
236 }
237 #endif
238 
239 /**
240  * dma_contiguous_reserve() - reserve area(s) for contiguous memory handling
241  * @limit: End address of the reserved memory (optional, 0 for any).
242  *
243  * This function reserves memory from early allocator. It should be
244  * called by arch specific code once the early allocator (memblock or bootmem)
245  * has been activated and all other subsystems have already allocated/reserved
246  * memory.
247  */
248 void __init dma_contiguous_reserve(phys_addr_t limit)
249 {
250 	phys_addr_t selected_size = 0;
251 	phys_addr_t selected_base = 0;
252 	phys_addr_t selected_limit = limit;
253 	bool fixed = false;
254 
255 	pr_debug("%s(limit %08lx)\n", __func__, (unsigned long)limit);
256 
257 	if (size_cmdline != -1) {
258 		selected_size = size_cmdline;
259 		selected_base = base_cmdline;
260 
261 		/* Hornor the user setup dma address limit */
262 		selected_limit = limit_cmdline ?: limit;
263 
264 		if (base_cmdline + size_cmdline == limit_cmdline)
265 			fixed = true;
266 	} else {
267 #ifdef CONFIG_CMA_SIZE_SEL_MBYTES
268 		selected_size = size_bytes;
269 #elif defined(CONFIG_CMA_SIZE_SEL_PERCENTAGE)
270 		selected_size = cma_early_percent_memory();
271 #elif defined(CONFIG_CMA_SIZE_SEL_MIN)
272 		selected_size = min(size_bytes, cma_early_percent_memory());
273 #elif defined(CONFIG_CMA_SIZE_SEL_MAX)
274 		selected_size = max(size_bytes, cma_early_percent_memory());
275 #endif
276 	}
277 
278 	if (selected_size && !dma_contiguous_default_area) {
279 		int ret;
280 
281 		pr_debug("%s: reserving %ld MiB for global area\n", __func__,
282 			 (unsigned long)selected_size / SZ_1M);
283 
284 		ret = dma_contiguous_reserve_area(selected_size, selected_base,
285 						  selected_limit,
286 						  &dma_contiguous_default_area,
287 						  fixed);
288 		if (ret)
289 			return;
290 
291 		/*
292 		 * We need to insert the new area in our list to avoid
293 		 * any inconsistencies between having the default area
294 		 * listed in the DT or not.
295 		 *
296 		 * The DT case is handled by rmem_cma_setup() and will
297 		 * always insert all its areas in our list. However, if
298 		 * it didn't run (because OF_RESERVED_MEM isn't set, or
299 		 * there's no DT region specified), then we don't have a
300 		 * default area yet, and no area in our list.
301 		 *
302 		 * This block creates the default area in such a case,
303 		 * but we also need to insert it in our list to avoid
304 		 * having a default area but an empty list.
305 		 */
306 		ret = dma_contiguous_insert_area(dma_contiguous_default_area);
307 		if (ret)
308 			pr_warn("Couldn't queue default CMA region for heap creation.");
309 	}
310 
311 	dma_numa_cma_reserve();
312 }
313 
314 void __weak
315 dma_contiguous_early_fixup(phys_addr_t base, unsigned long size)
316 {
317 }
318 
319 /**
320  * dma_contiguous_reserve_area() - reserve custom contiguous area
321  * @size: Size of the reserved area (in bytes),
322  * @base: Base address of the reserved area optional, use 0 for any
323  * @limit: End address of the reserved memory (optional, 0 for any).
324  * @res_cma: Pointer to store the created cma region.
325  * @fixed: hint about where to place the reserved area
326  *
327  * This function reserves memory from early allocator. It should be
328  * called by arch specific code once the early allocator (memblock or bootmem)
329  * has been activated and all other subsystems have already allocated/reserved
330  * memory. This function allows to create custom reserved areas for specific
331  * devices.
332  *
333  * If @fixed is true, reserve contiguous area at exactly @base.  If false,
334  * reserve in range from @base to @limit.
335  */
336 int __init dma_contiguous_reserve_area(phys_addr_t size, phys_addr_t base,
337 				       phys_addr_t limit, struct cma **res_cma,
338 				       bool fixed)
339 {
340 	int ret;
341 
342 	ret = cma_declare_contiguous(base, size, limit, 0, 0, fixed,
343 					"reserved", res_cma);
344 	if (ret)
345 		return ret;
346 
347 	/* Architecture specific contiguous memory fixup. */
348 	dma_contiguous_early_fixup(cma_get_base(*res_cma),
349 				cma_get_size(*res_cma));
350 
351 	return 0;
352 }
353 
354 /**
355  * dma_alloc_from_contiguous() - allocate pages from contiguous area
356  * @dev:   Pointer to device for which the allocation is performed.
357  * @count: Requested number of pages.
358  * @align: Requested alignment of pages (in PAGE_SIZE order).
359  * @no_warn: Avoid printing message about failed allocation.
360  *
361  * This function allocates memory buffer for specified device. It uses
362  * device specific contiguous memory area if available or the default
363  * global one. Requires architecture specific dev_get_cma_area() helper
364  * function.
365  */
366 struct page *dma_alloc_from_contiguous(struct device *dev, size_t count,
367 				       unsigned int align, bool no_warn)
368 {
369 	if (align > CONFIG_CMA_ALIGNMENT)
370 		align = CONFIG_CMA_ALIGNMENT;
371 
372 	return cma_alloc(dev_get_cma_area(dev), count, align, no_warn);
373 }
374 
375 /**
376  * dma_release_from_contiguous() - release allocated pages
377  * @dev:   Pointer to device for which the pages were allocated.
378  * @pages: Allocated pages.
379  * @count: Number of allocated pages.
380  *
381  * This function releases memory allocated by dma_alloc_from_contiguous().
382  * It returns false when provided pages do not belong to contiguous area and
383  * true otherwise.
384  */
385 bool dma_release_from_contiguous(struct device *dev, struct page *pages,
386 				 int count)
387 {
388 	return cma_release(dev_get_cma_area(dev), pages, count);
389 }
390 
391 static struct page *cma_alloc_aligned(struct cma *cma, size_t size, gfp_t gfp)
392 {
393 	unsigned int align = min(get_order(size), CONFIG_CMA_ALIGNMENT);
394 
395 	return cma_alloc(cma, size >> PAGE_SHIFT, align, gfp & __GFP_NOWARN);
396 }
397 
398 /**
399  * dma_alloc_contiguous() - allocate contiguous pages
400  * @dev:   Pointer to device for which the allocation is performed.
401  * @size:  Requested allocation size.
402  * @gfp:   Allocation flags.
403  *
404  * tries to use device specific contiguous memory area if available, or it
405  * tries to use per-numa cma, if the allocation fails, it will fallback to
406  * try default global one.
407  *
408  * Note that it bypass one-page size of allocations from the per-numa and
409  * global area as the addresses within one page are always contiguous, so
410  * there is no need to waste CMA pages for that kind; it also helps reduce
411  * fragmentations.
412  */
413 struct page *dma_alloc_contiguous(struct device *dev, size_t size, gfp_t gfp)
414 {
415 #ifdef CONFIG_DMA_NUMA_CMA
416 	int nid = dev_to_node(dev);
417 #endif
418 
419 	/* CMA can be used only in the context which permits sleeping */
420 	if (!gfpflags_allow_blocking(gfp))
421 		return NULL;
422 	if (dev->cma_area)
423 		return cma_alloc_aligned(dev->cma_area, size, gfp);
424 	if (size <= PAGE_SIZE)
425 		return NULL;
426 
427 #ifdef CONFIG_DMA_NUMA_CMA
428 	if (nid != NUMA_NO_NODE && !(gfp & (GFP_DMA | GFP_DMA32))) {
429 		struct cma *cma = dma_contiguous_numa_area[nid];
430 		struct page *page;
431 		if (cma) {
432 			page = cma_alloc_aligned(cma, size, gfp);
433 			if (page)
434 				return page;
435 		}
436 	}
437 #endif
438 	if (!dma_contiguous_default_area)
439 		return NULL;
440 
441 	return cma_alloc_aligned(dma_contiguous_default_area, size, gfp);
442 }
443 
444 /**
445  * dma_free_contiguous() - release allocated pages
446  * @dev:   Pointer to device for which the pages were allocated.
447  * @page:  Pointer to the allocated pages.
448  * @size:  Size of allocated pages.
449  *
450  * This function releases memory allocated by dma_alloc_contiguous(). As the
451  * cma_release returns false when provided pages do not belong to contiguous
452  * area and true otherwise, this function then does a fallback __free_pages()
453  * upon a false-return.
454  */
455 void dma_free_contiguous(struct device *dev, struct page *page, size_t size)
456 {
457 	unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
458 
459 	/* if dev has its own cma, free page from there */
460 	if (dev->cma_area) {
461 		if (cma_release(dev->cma_area, page, count))
462 			return;
463 	} else {
464 		/*
465 		 * otherwise, page is from either per-numa cma or default cma
466 		 */
467 #ifdef CONFIG_DMA_NUMA_CMA
468 		if (cma_release(dma_contiguous_numa_area[page_to_nid(page)],
469 					page, count))
470 			return;
471 #endif
472 		if (cma_release(dma_contiguous_default_area, page, count))
473 			return;
474 	}
475 
476 	/* not in any cma, free from buddy */
477 	__free_pages(page, get_order(size));
478 }
479 
480 /*
481  * Support for reserved memory regions defined in device tree
482  */
483 #ifdef CONFIG_OF_RESERVED_MEM
484 #include <linux/of.h>
485 #include <linux/of_fdt.h>
486 #include <linux/of_reserved_mem.h>
487 
488 #undef pr_fmt
489 #define pr_fmt(fmt) fmt
490 
491 static int rmem_cma_device_init(struct reserved_mem *rmem, struct device *dev)
492 {
493 	dev->cma_area = rmem->priv;
494 	return 0;
495 }
496 
497 static void rmem_cma_device_release(struct reserved_mem *rmem,
498 				    struct device *dev)
499 {
500 	dev->cma_area = NULL;
501 }
502 
503 static int __init __rmem_cma_verify_node(unsigned long node)
504 {
505 	if (!of_get_flat_dt_prop(node, "reusable", NULL) ||
506 	    of_get_flat_dt_prop(node, "no-map", NULL))
507 		return -ENODEV;
508 
509 	if (size_cmdline != -1 &&
510 	    of_get_flat_dt_prop(node, "linux,cma-default", NULL)) {
511 		pr_err("Skipping dt linux,cma-default node in favor for \"cma=\" kernel param.\n");
512 		return -EBUSY;
513 	}
514 	return 0;
515 }
516 
517 static int __init rmem_cma_validate(unsigned long node, phys_addr_t *align)
518 {
519 	int ret = __rmem_cma_verify_node(node);
520 
521 	if (ret)
522 		return ret;
523 
524 	if (align)
525 		*align = max_t(phys_addr_t, *align, CMA_MIN_ALIGNMENT_BYTES);
526 
527 	return 0;
528 }
529 
530 static int __init rmem_cma_fixup(unsigned long node, phys_addr_t base,
531 				    phys_addr_t size)
532 {
533 	int ret = __rmem_cma_verify_node(node);
534 
535 	if (ret)
536 		return ret;
537 
538 	/* Architecture specific contiguous memory fixup. */
539 	dma_contiguous_early_fixup(base, size);
540 	return 0;
541 }
542 
543 static int __init rmem_cma_setup(unsigned long node, struct reserved_mem *rmem)
544 {
545 	bool default_cma = of_get_flat_dt_prop(node, "linux,cma-default", NULL);
546 	struct cma *cma;
547 	int ret;
548 
549 	ret = __rmem_cma_verify_node(node);
550 	if (ret)
551 		return ret;
552 
553 	if (!IS_ALIGNED(rmem->base | rmem->size, CMA_MIN_ALIGNMENT_BYTES)) {
554 		pr_err("Reserved memory: incorrect alignment of CMA region\n");
555 		return -EINVAL;
556 	}
557 
558 	ret = cma_init_reserved_mem(rmem->base, rmem->size, 0, rmem->name, &cma);
559 	if (ret) {
560 		pr_err("Reserved memory: unable to setup CMA region\n");
561 		return ret;
562 	}
563 
564 	if (default_cma)
565 		dma_contiguous_default_area = cma;
566 
567 	rmem->priv = cma;
568 
569 	pr_info("Reserved memory: created CMA memory pool at %pa, size %ld MiB\n",
570 		&rmem->base, (unsigned long)rmem->size / SZ_1M);
571 
572 	ret = dma_contiguous_insert_area(cma);
573 	if (ret)
574 		pr_warn("Couldn't store CMA reserved area.");
575 
576 	return 0;
577 }
578 
579 static const struct reserved_mem_ops rmem_cma_ops = {
580 	.node_validate  = rmem_cma_validate,
581 	.node_fixup	= rmem_cma_fixup,
582 	.node_init	= rmem_cma_setup,
583 	.device_init	= rmem_cma_device_init,
584 	.device_release = rmem_cma_device_release,
585 };
586 
587 RESERVEDMEM_OF_DECLARE(cma, "shared-dma-pool", &rmem_cma_ops);
588 #endif
589