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