1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Contiguous Memory Allocator
4 *
5 * Copyright (c) 2010-2011 by Samsung Electronics.
6 * Copyright IBM Corporation, 2013
7 * Copyright LG Electronics Inc., 2014
8 * Written by:
9 * Marek Szyprowski <m.szyprowski@samsung.com>
10 * Michal Nazarewicz <mina86@mina86.com>
11 * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com>
12 * Joonsoo Kim <iamjoonsoo.kim@lge.com>
13 */
14
15 #define pr_fmt(fmt) "cma: " fmt
16
17 #define CREATE_TRACE_POINTS
18
19 #include <linux/memblock.h>
20 #include <linux/err.h>
21 #include <linux/list.h>
22 #include <linux/mm.h>
23 #include <linux/sizes.h>
24 #include <linux/slab.h>
25 #include <linux/string.h>
26 #include <linux/string_choices.h>
27 #include <linux/log2.h>
28 #include <linux/cma.h>
29 #include <linux/highmem.h>
30 #include <linux/io.h>
31 #include <linux/kmemleak.h>
32 #include <trace/events/cma.h>
33
34 #include "internal.h"
35 #include "cma.h"
36
37 struct cma cma_areas[MAX_CMA_AREAS];
38 unsigned int cma_area_count;
39
cma_get_base(const struct cma * cma)40 phys_addr_t cma_get_base(const struct cma *cma)
41 {
42 WARN_ON_ONCE(cma->nranges != 1);
43 return PFN_PHYS(cma->ranges[0].base_pfn);
44 }
45
cma_get_size(const struct cma * cma)46 unsigned long cma_get_size(const struct cma *cma)
47 {
48 return cma->count << PAGE_SHIFT;
49 }
50
cma_get_name(const struct cma * cma)51 const char *cma_get_name(const struct cma *cma)
52 {
53 return cma->name;
54 }
55 EXPORT_SYMBOL_GPL(cma_get_name);
56
cma_bitmap_aligned_mask(const struct cma * cma,unsigned int align_order)57 static unsigned long cma_bitmap_aligned_mask(const struct cma *cma,
58 unsigned int align_order)
59 {
60 if (align_order <= cma->order_per_bit)
61 return 0;
62 return (1UL << (align_order - cma->order_per_bit)) - 1;
63 }
64
65 /*
66 * Find the offset of the base PFN from the specified align_order.
67 * The value returned is represented in order_per_bits.
68 */
cma_bitmap_aligned_offset(const struct cma * cma,const struct cma_memrange * cmr,unsigned int align_order)69 static unsigned long cma_bitmap_aligned_offset(const struct cma *cma,
70 const struct cma_memrange *cmr,
71 unsigned int align_order)
72 {
73 return (cmr->base_pfn & ((1UL << align_order) - 1))
74 >> cma->order_per_bit;
75 }
76
cma_bitmap_pages_to_bits(const struct cma * cma,unsigned long pages)77 static unsigned long cma_bitmap_pages_to_bits(const struct cma *cma,
78 unsigned long pages)
79 {
80 return ALIGN(pages, 1UL << cma->order_per_bit) >> cma->order_per_bit;
81 }
82
cma_clear_bitmap(struct cma * cma,const struct cma_memrange * cmr,unsigned long pfn,unsigned long count)83 static void cma_clear_bitmap(struct cma *cma, const struct cma_memrange *cmr,
84 unsigned long pfn, unsigned long count)
85 {
86 unsigned long bitmap_no, bitmap_count;
87 unsigned long flags;
88
89 bitmap_no = (pfn - cmr->base_pfn) >> cma->order_per_bit;
90 bitmap_count = cma_bitmap_pages_to_bits(cma, count);
91
92 spin_lock_irqsave(&cma->lock, flags);
93 bitmap_clear(cmr->bitmap, bitmap_no, bitmap_count);
94 cma->available_count += count;
95 spin_unlock_irqrestore(&cma->lock, flags);
96 }
97
98 /*
99 * Check if a CMA area contains no ranges that intersect with
100 * multiple zones. Store the result in the flags in case
101 * this gets called more than once.
102 */
cma_validate_zones(struct cma * cma)103 bool cma_validate_zones(struct cma *cma)
104 {
105 int r;
106 unsigned long base_pfn;
107 struct cma_memrange *cmr;
108 bool valid_bit_set;
109
110 /*
111 * If already validated, return result of previous check.
112 * Either the valid or invalid bit will be set if this
113 * check has already been done. If neither is set, the
114 * check has not been performed yet.
115 */
116 valid_bit_set = test_bit(CMA_ZONES_VALID, &cma->flags);
117 if (valid_bit_set || test_bit(CMA_ZONES_INVALID, &cma->flags))
118 return valid_bit_set;
119
120 for (r = 0; r < cma->nranges; r++) {
121 cmr = &cma->ranges[r];
122 base_pfn = cmr->base_pfn;
123
124 /*
125 * alloc_contig_range() requires the pfn range specified
126 * to be in the same zone. Simplify by forcing the entire
127 * CMA resv range to be in the same zone.
128 */
129 WARN_ON_ONCE(!pfn_valid(base_pfn));
130 if (pfn_range_intersects_zones(cma->nid, base_pfn, cmr->count)) {
131 set_bit(CMA_ZONES_INVALID, &cma->flags);
132 return false;
133 }
134 }
135
136 set_bit(CMA_ZONES_VALID, &cma->flags);
137
138 return true;
139 }
140
cma_activate_area(struct cma * cma)141 static void __init cma_activate_area(struct cma *cma)
142 {
143 unsigned long pfn, end_pfn, early_pfn[CMA_MAX_RANGES];
144 int allocrange, r;
145 struct cma_memrange *cmr;
146 unsigned long bitmap_count, count;
147
148 for (allocrange = 0; allocrange < cma->nranges; allocrange++) {
149 cmr = &cma->ranges[allocrange];
150 early_pfn[allocrange] = cmr->early_pfn;
151 cmr->bitmap = bitmap_zalloc(cma_bitmap_maxno(cma, cmr),
152 GFP_KERNEL);
153 if (!cmr->bitmap)
154 goto cleanup;
155 }
156
157 if (!cma_validate_zones(cma))
158 goto cleanup;
159
160 for (r = 0; r < cma->nranges; r++) {
161 cmr = &cma->ranges[r];
162 if (early_pfn[r] != cmr->base_pfn) {
163 count = early_pfn[r] - cmr->base_pfn;
164 bitmap_count = cma_bitmap_pages_to_bits(cma, count);
165 bitmap_set(cmr->bitmap, 0, bitmap_count);
166 }
167
168 for (pfn = early_pfn[r]; pfn < cmr->base_pfn + cmr->count;
169 pfn += pageblock_nr_pages)
170 init_cma_reserved_pageblock(pfn_to_page(pfn));
171 }
172
173 spin_lock_init(&cma->lock);
174
175 mutex_init(&cma->alloc_mutex);
176
177 #ifdef CONFIG_CMA_DEBUGFS
178 INIT_HLIST_HEAD(&cma->mem_head);
179 spin_lock_init(&cma->mem_head_lock);
180 #endif
181 set_bit(CMA_ACTIVATED, &cma->flags);
182
183 return;
184
185 cleanup:
186 for (r = 0; r < allocrange; r++)
187 bitmap_free(cma->ranges[r].bitmap);
188
189 /* Expose all pages to the buddy, they are useless for CMA. */
190 if (!test_bit(CMA_RESERVE_PAGES_ON_ERROR, &cma->flags)) {
191 for (r = 0; r < cma->nranges; r++) {
192 unsigned long start_pfn;
193
194 cmr = &cma->ranges[r];
195 start_pfn = r <= allocrange ? early_pfn[r] : cmr->early_pfn;
196 end_pfn = cmr->base_pfn + cmr->count;
197 for (pfn = start_pfn; pfn < end_pfn; pfn++)
198 free_reserved_page(pfn_to_page(pfn));
199 }
200 }
201 totalcma_pages -= cma->count;
202 cma->available_count = cma->count = 0;
203 pr_err("CMA area %s could not be activated\n", cma->name);
204 }
205
cma_init_reserved_areas(void)206 static int __init cma_init_reserved_areas(void)
207 {
208 int i;
209
210 for (i = 0; i < cma_area_count; i++)
211 cma_activate_area(&cma_areas[i]);
212
213 return 0;
214 }
215 core_initcall(cma_init_reserved_areas);
216
cma_reserve_pages_on_error(struct cma * cma)217 void __init cma_reserve_pages_on_error(struct cma *cma)
218 {
219 set_bit(CMA_RESERVE_PAGES_ON_ERROR, &cma->flags);
220 }
221
cma_new_area(const char * name,phys_addr_t size,unsigned int order_per_bit,struct cma ** res_cma)222 static int __init cma_new_area(const char *name, phys_addr_t size,
223 unsigned int order_per_bit,
224 struct cma **res_cma)
225 {
226 struct cma *cma;
227
228 if (cma_area_count == ARRAY_SIZE(cma_areas)) {
229 pr_err("Not enough slots for CMA reserved regions!\n");
230 return -ENOSPC;
231 }
232
233 /*
234 * Each reserved area must be initialised later, when more kernel
235 * subsystems (like slab allocator) are available.
236 */
237 cma = &cma_areas[cma_area_count];
238 cma_area_count++;
239
240 if (name)
241 strscpy(cma->name, name);
242 else
243 snprintf(cma->name, CMA_MAX_NAME, "cma%d\n", cma_area_count);
244
245 cma->available_count = cma->count = size >> PAGE_SHIFT;
246 cma->order_per_bit = order_per_bit;
247 *res_cma = cma;
248 totalcma_pages += cma->count;
249
250 return 0;
251 }
252
cma_drop_area(struct cma * cma)253 static void __init cma_drop_area(struct cma *cma)
254 {
255 totalcma_pages -= cma->count;
256 cma_area_count--;
257 }
258
259 /**
260 * cma_init_reserved_mem() - create custom contiguous area from reserved memory
261 * @base: Base address of the reserved area
262 * @size: Size of the reserved area (in bytes),
263 * @order_per_bit: Order of pages represented by one bit on bitmap.
264 * @name: The name of the area. If this parameter is NULL, the name of
265 * the area will be set to "cmaN", where N is a running counter of
266 * used areas.
267 * @res_cma: Pointer to store the created cma region.
268 *
269 * This function creates custom contiguous area from already reserved memory.
270 */
cma_init_reserved_mem(phys_addr_t base,phys_addr_t size,unsigned int order_per_bit,const char * name,struct cma ** res_cma)271 int __init cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
272 unsigned int order_per_bit,
273 const char *name,
274 struct cma **res_cma)
275 {
276 struct cma *cma;
277 int ret;
278
279 /* Sanity checks */
280 if (!size || !memblock_is_region_reserved(base, size))
281 return -EINVAL;
282
283 /*
284 * CMA uses CMA_MIN_ALIGNMENT_BYTES as alignment requirement which
285 * needs pageblock_order to be initialized. Let's enforce it.
286 */
287 if (!pageblock_order) {
288 pr_err("pageblock_order not yet initialized. Called during early boot?\n");
289 return -EINVAL;
290 }
291
292 /* ensure minimal alignment required by mm core */
293 if (!IS_ALIGNED(base | size, CMA_MIN_ALIGNMENT_BYTES))
294 return -EINVAL;
295
296 ret = cma_new_area(name, size, order_per_bit, &cma);
297 if (ret != 0)
298 return ret;
299
300 cma->ranges[0].base_pfn = PFN_DOWN(base);
301 cma->ranges[0].early_pfn = PFN_DOWN(base);
302 cma->ranges[0].count = cma->count;
303 cma->nranges = 1;
304 cma->nid = NUMA_NO_NODE;
305
306 *res_cma = cma;
307
308 return 0;
309 }
310
311 /*
312 * Structure used while walking physical memory ranges and finding out
313 * which one(s) to use for a CMA area.
314 */
315 struct cma_init_memrange {
316 phys_addr_t base;
317 phys_addr_t size;
318 struct list_head list;
319 };
320
321 /*
322 * Work array used during CMA initialization.
323 */
324 static struct cma_init_memrange memranges[CMA_MAX_RANGES] __initdata;
325
revsizecmp(struct cma_init_memrange * mlp,struct cma_init_memrange * mrp)326 static bool __init revsizecmp(struct cma_init_memrange *mlp,
327 struct cma_init_memrange *mrp)
328 {
329 return mlp->size > mrp->size;
330 }
331
basecmp(struct cma_init_memrange * mlp,struct cma_init_memrange * mrp)332 static bool __init basecmp(struct cma_init_memrange *mlp,
333 struct cma_init_memrange *mrp)
334 {
335 return mlp->base < mrp->base;
336 }
337
338 /*
339 * Helper function to create sorted lists.
340 */
list_insert_sorted(struct list_head * ranges,struct cma_init_memrange * mrp,bool (* cmp)(struct cma_init_memrange * lh,struct cma_init_memrange * rh))341 static void __init list_insert_sorted(
342 struct list_head *ranges,
343 struct cma_init_memrange *mrp,
344 bool (*cmp)(struct cma_init_memrange *lh, struct cma_init_memrange *rh))
345 {
346 struct list_head *mp;
347 struct cma_init_memrange *mlp;
348
349 if (list_empty(ranges))
350 list_add(&mrp->list, ranges);
351 else {
352 list_for_each(mp, ranges) {
353 mlp = list_entry(mp, struct cma_init_memrange, list);
354 if (cmp(mlp, mrp))
355 break;
356 }
357 __list_add(&mrp->list, mlp->list.prev, &mlp->list);
358 }
359 }
360
cma_fixed_reserve(phys_addr_t base,phys_addr_t size)361 static int __init cma_fixed_reserve(phys_addr_t base, phys_addr_t size)
362 {
363 if (IS_ENABLED(CONFIG_HIGHMEM)) {
364 phys_addr_t highmem_start = __pa(high_memory - 1) + 1;
365
366 /*
367 * If allocating at a fixed base the request region must not
368 * cross the low/high memory boundary.
369 */
370 if (base < highmem_start && base + size > highmem_start) {
371 pr_err("Region at %pa defined on low/high memory boundary (%pa)\n",
372 &base, &highmem_start);
373 return -EINVAL;
374 }
375 }
376
377 if (memblock_is_region_reserved(base, size) ||
378 memblock_reserve(base, size) < 0) {
379 return -EBUSY;
380 }
381
382 return 0;
383 }
384
cma_alloc_mem(phys_addr_t base,phys_addr_t size,phys_addr_t align,phys_addr_t limit,int nid)385 static phys_addr_t __init cma_alloc_mem(phys_addr_t base, phys_addr_t size,
386 phys_addr_t align, phys_addr_t limit, int nid)
387 {
388 phys_addr_t addr = 0;
389
390 /*
391 * If there is enough memory, try a bottom-up allocation first.
392 * It will place the new cma area close to the start of the node
393 * and guarantee that the compaction is moving pages out of the
394 * cma area and not into it.
395 * Avoid using first 4GB to not interfere with constrained zones
396 * like DMA/DMA32.
397 */
398 #ifdef CONFIG_PHYS_ADDR_T_64BIT
399 if (!memblock_bottom_up() && limit >= SZ_4G + size) {
400 memblock_set_bottom_up(true);
401 addr = memblock_alloc_range_nid(size, align, SZ_4G, limit,
402 nid, true);
403 memblock_set_bottom_up(false);
404 }
405 #endif
406
407 /*
408 * On systems with HIGHMEM try allocating from there before consuming
409 * memory in lower zones.
410 */
411 if (!addr && IS_ENABLED(CONFIG_HIGHMEM)) {
412 phys_addr_t highmem = __pa(high_memory - 1) + 1;
413
414 /*
415 * All pages in the reserved area must come from the same zone.
416 * If the requested region crosses the low/high memory boundary,
417 * try allocating from high memory first and fall back to low
418 * memory in case of failure.
419 */
420 if (base < highmem && limit > highmem) {
421 addr = memblock_alloc_range_nid(size, align, highmem,
422 limit, nid, true);
423 limit = highmem;
424 }
425 }
426
427 if (!addr)
428 addr = memblock_alloc_range_nid(size, align, base, limit, nid,
429 true);
430
431 return addr;
432 }
433
__cma_declare_contiguous_nid(phys_addr_t * basep,phys_addr_t size,phys_addr_t limit,phys_addr_t alignment,unsigned int order_per_bit,bool fixed,const char * name,struct cma ** res_cma,int nid)434 static int __init __cma_declare_contiguous_nid(phys_addr_t *basep,
435 phys_addr_t size, phys_addr_t limit,
436 phys_addr_t alignment, unsigned int order_per_bit,
437 bool fixed, const char *name, struct cma **res_cma,
438 int nid)
439 {
440 phys_addr_t memblock_end = memblock_end_of_DRAM();
441 phys_addr_t base = *basep;
442 int ret;
443
444 pr_debug("%s(size %pa, base %pa, limit %pa alignment %pa)\n",
445 __func__, &size, &base, &limit, &alignment);
446
447 if (cma_area_count == ARRAY_SIZE(cma_areas)) {
448 pr_err("Not enough slots for CMA reserved regions!\n");
449 return -ENOSPC;
450 }
451
452 if (!size)
453 return -EINVAL;
454
455 if (alignment && !is_power_of_2(alignment))
456 return -EINVAL;
457
458 if (!IS_ENABLED(CONFIG_NUMA))
459 nid = NUMA_NO_NODE;
460
461 /* Sanitise input arguments. */
462 alignment = max_t(phys_addr_t, alignment, CMA_MIN_ALIGNMENT_BYTES);
463 if (fixed && base & (alignment - 1)) {
464 pr_err("Region at %pa must be aligned to %pa bytes\n",
465 &base, &alignment);
466 return -EINVAL;
467 }
468 base = ALIGN(base, alignment);
469 size = ALIGN(size, alignment);
470 limit &= ~(alignment - 1);
471
472 if (!base)
473 fixed = false;
474
475 /* size should be aligned with order_per_bit */
476 if (!IS_ALIGNED(size >> PAGE_SHIFT, 1 << order_per_bit))
477 return -EINVAL;
478
479
480 /*
481 * If the limit is unspecified or above the memblock end, its effective
482 * value will be the memblock end. Set it explicitly to simplify further
483 * checks.
484 */
485 if (limit == 0 || limit > memblock_end)
486 limit = memblock_end;
487
488 if (base + size > limit) {
489 pr_err("Size (%pa) of region at %pa exceeds limit (%pa)\n",
490 &size, &base, &limit);
491 return -EINVAL;
492 }
493
494 /* Reserve memory */
495 if (fixed) {
496 ret = cma_fixed_reserve(base, size);
497 if (ret)
498 return ret;
499 } else {
500 base = cma_alloc_mem(base, size, alignment, limit, nid);
501 if (!base)
502 return -ENOMEM;
503
504 /*
505 * kmemleak scans/reads tracked objects for pointers to other
506 * objects but this address isn't mapped and accessible
507 */
508 kmemleak_ignore_phys(base);
509 }
510
511 ret = cma_init_reserved_mem(base, size, order_per_bit, name, res_cma);
512 if (ret) {
513 memblock_phys_free(base, size);
514 return ret;
515 }
516
517 (*res_cma)->nid = nid;
518 *basep = base;
519
520 return 0;
521 }
522
523 /*
524 * Create CMA areas with a total size of @total_size. A normal allocation
525 * for one area is tried first. If that fails, the biggest memblock
526 * ranges above 4G are selected, and allocated bottom up.
527 *
528 * The complexity here is not great, but this function will only be
529 * called during boot, and the lists operated on have fewer than
530 * CMA_MAX_RANGES elements (default value: 8).
531 */
cma_declare_contiguous_multi(phys_addr_t total_size,phys_addr_t align,unsigned int order_per_bit,const char * name,struct cma ** res_cma,int nid)532 int __init cma_declare_contiguous_multi(phys_addr_t total_size,
533 phys_addr_t align, unsigned int order_per_bit,
534 const char *name, struct cma **res_cma, int nid)
535 {
536 phys_addr_t start = 0, end;
537 phys_addr_t size, sizesum, sizeleft;
538 struct cma_init_memrange *mrp, *mlp, *failed;
539 struct cma_memrange *cmrp;
540 LIST_HEAD(ranges);
541 LIST_HEAD(final_ranges);
542 struct list_head *mp, *next;
543 int ret, nr = 1;
544 u64 i;
545 struct cma *cma;
546
547 /*
548 * First, try it the normal way, producing just one range.
549 */
550 ret = __cma_declare_contiguous_nid(&start, total_size, 0, align,
551 order_per_bit, false, name, res_cma, nid);
552 if (ret != -ENOMEM)
553 goto out;
554
555 /*
556 * Couldn't find one range that fits our needs, so try multiple
557 * ranges.
558 *
559 * No need to do the alignment checks here, the call to
560 * cma_declare_contiguous_nid above would have caught
561 * any issues. With the checks, we know that:
562 *
563 * - @align is a power of 2
564 * - @align is >= pageblock alignment
565 * - @size is aligned to @align and to @order_per_bit
566 *
567 * So, as long as we create ranges that have a base
568 * aligned to @align, and a size that is aligned to
569 * both @align and @order_to_bit, things will work out.
570 */
571 nr = 0;
572 sizesum = 0;
573 failed = NULL;
574
575 ret = cma_new_area(name, total_size, order_per_bit, &cma);
576 if (ret != 0)
577 goto out;
578
579 align = max_t(phys_addr_t, align, CMA_MIN_ALIGNMENT_BYTES);
580 /*
581 * Create a list of ranges above 4G, largest range first.
582 */
583 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &start, &end, NULL) {
584 if (upper_32_bits(start) == 0)
585 continue;
586
587 start = ALIGN(start, align);
588 if (start >= end)
589 continue;
590
591 end = ALIGN_DOWN(end, align);
592 if (end <= start)
593 continue;
594
595 size = end - start;
596 size = ALIGN_DOWN(size, (PAGE_SIZE << order_per_bit));
597 if (!size)
598 continue;
599 sizesum += size;
600
601 pr_debug("consider %016llx - %016llx\n", (u64)start, (u64)end);
602
603 /*
604 * If we don't yet have used the maximum number of
605 * areas, grab a new one.
606 *
607 * If we can't use anymore, see if this range is not
608 * smaller than the smallest one already recorded. If
609 * not, re-use the smallest element.
610 */
611 if (nr < CMA_MAX_RANGES)
612 mrp = &memranges[nr++];
613 else {
614 mrp = list_last_entry(&ranges,
615 struct cma_init_memrange, list);
616 if (size < mrp->size)
617 continue;
618 list_del(&mrp->list);
619 sizesum -= mrp->size;
620 pr_debug("deleted %016llx - %016llx from the list\n",
621 (u64)mrp->base, (u64)mrp->base + size);
622 }
623 mrp->base = start;
624 mrp->size = size;
625
626 /*
627 * Now do a sorted insert.
628 */
629 list_insert_sorted(&ranges, mrp, revsizecmp);
630 pr_debug("added %016llx - %016llx to the list\n",
631 (u64)mrp->base, (u64)mrp->base + size);
632 pr_debug("total size now %llu\n", (u64)sizesum);
633 }
634
635 /*
636 * There is not enough room in the CMA_MAX_RANGES largest
637 * ranges, so bail out.
638 */
639 if (sizesum < total_size) {
640 cma_drop_area(cma);
641 ret = -ENOMEM;
642 goto out;
643 }
644
645 /*
646 * Found ranges that provide enough combined space.
647 * Now, sorted them by address, smallest first, because we
648 * want to mimic a bottom-up memblock allocation.
649 */
650 sizesum = 0;
651 list_for_each_safe(mp, next, &ranges) {
652 mlp = list_entry(mp, struct cma_init_memrange, list);
653 list_del(mp);
654 list_insert_sorted(&final_ranges, mlp, basecmp);
655 sizesum += mlp->size;
656 if (sizesum >= total_size)
657 break;
658 }
659
660 /*
661 * Walk the final list, and add a CMA range for
662 * each range, possibly not using the last one fully.
663 */
664 nr = 0;
665 sizeleft = total_size;
666 list_for_each(mp, &final_ranges) {
667 mlp = list_entry(mp, struct cma_init_memrange, list);
668 size = min(sizeleft, mlp->size);
669 if (memblock_reserve(mlp->base, size)) {
670 /*
671 * Unexpected error. Could go on to
672 * the next one, but just abort to
673 * be safe.
674 */
675 failed = mlp;
676 break;
677 }
678
679 pr_debug("created region %d: %016llx - %016llx\n",
680 nr, (u64)mlp->base, (u64)mlp->base + size);
681 cmrp = &cma->ranges[nr++];
682 cmrp->base_pfn = PHYS_PFN(mlp->base);
683 cmrp->early_pfn = cmrp->base_pfn;
684 cmrp->count = size >> PAGE_SHIFT;
685
686 sizeleft -= size;
687 if (sizeleft == 0)
688 break;
689 }
690
691 if (failed) {
692 list_for_each(mp, &final_ranges) {
693 mlp = list_entry(mp, struct cma_init_memrange, list);
694 if (mlp == failed)
695 break;
696 memblock_phys_free(mlp->base, mlp->size);
697 }
698 cma_drop_area(cma);
699 ret = -ENOMEM;
700 goto out;
701 }
702
703 cma->nranges = nr;
704 cma->nid = nid;
705 *res_cma = cma;
706
707 out:
708 if (ret != 0)
709 pr_err("Failed to reserve %lu MiB\n",
710 (unsigned long)total_size / SZ_1M);
711 else
712 pr_info("Reserved %lu MiB in %d range%s\n",
713 (unsigned long)total_size / SZ_1M, nr, str_plural(nr));
714 return ret;
715 }
716
717 /**
718 * cma_declare_contiguous_nid() - reserve custom contiguous area
719 * @base: Base address of the reserved area optional, use 0 for any
720 * @size: Size of the reserved area (in bytes),
721 * @limit: End address of the reserved memory (optional, 0 for any).
722 * @alignment: Alignment for the CMA area, should be power of 2 or zero
723 * @order_per_bit: Order of pages represented by one bit on bitmap.
724 * @fixed: hint about where to place the reserved area
725 * @name: The name of the area. See function cma_init_reserved_mem()
726 * @res_cma: Pointer to store the created cma region.
727 * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
728 *
729 * This function reserves memory from early allocator. It should be
730 * called by arch specific code once the early allocator (memblock or bootmem)
731 * has been activated and all other subsystems have already allocated/reserved
732 * memory. This function allows to create custom reserved areas.
733 *
734 * If @fixed is true, reserve contiguous area at exactly @base. If false,
735 * reserve in range from @base to @limit.
736 */
cma_declare_contiguous_nid(phys_addr_t base,phys_addr_t size,phys_addr_t limit,phys_addr_t alignment,unsigned int order_per_bit,bool fixed,const char * name,struct cma ** res_cma,int nid)737 int __init cma_declare_contiguous_nid(phys_addr_t base,
738 phys_addr_t size, phys_addr_t limit,
739 phys_addr_t alignment, unsigned int order_per_bit,
740 bool fixed, const char *name, struct cma **res_cma,
741 int nid)
742 {
743 int ret;
744
745 ret = __cma_declare_contiguous_nid(&base, size, limit, alignment,
746 order_per_bit, fixed, name, res_cma, nid);
747 if (ret != 0)
748 pr_err("Failed to reserve %ld MiB\n",
749 (unsigned long)size / SZ_1M);
750 else
751 pr_info("Reserved %ld MiB at %pa\n",
752 (unsigned long)size / SZ_1M, &base);
753
754 return ret;
755 }
756
cma_debug_show_areas(struct cma * cma)757 static void cma_debug_show_areas(struct cma *cma)
758 {
759 unsigned long start, end;
760 unsigned long nr_part;
761 unsigned long nbits;
762 int r;
763 struct cma_memrange *cmr;
764
765 spin_lock_irq(&cma->lock);
766 pr_info("number of available pages: ");
767 for (r = 0; r < cma->nranges; r++) {
768 cmr = &cma->ranges[r];
769
770 nbits = cma_bitmap_maxno(cma, cmr);
771
772 pr_info("range %d: ", r);
773 for_each_clear_bitrange(start, end, cmr->bitmap, nbits) {
774 nr_part = (end - start) << cma->order_per_bit;
775 pr_cont("%s%lu@%lu", start ? "+" : "", nr_part, start);
776 }
777 pr_info("\n");
778 }
779 pr_cont("=> %lu free of %lu total pages\n", cma->available_count,
780 cma->count);
781 spin_unlock_irq(&cma->lock);
782 }
783
cma_range_alloc(struct cma * cma,struct cma_memrange * cmr,unsigned long count,unsigned int align,struct page ** pagep,gfp_t gfp)784 static int cma_range_alloc(struct cma *cma, struct cma_memrange *cmr,
785 unsigned long count, unsigned int align,
786 struct page **pagep, gfp_t gfp)
787 {
788 unsigned long bitmap_maxno, bitmap_no, bitmap_count;
789 unsigned long start, pfn, mask, offset;
790 int ret = -EBUSY;
791 struct page *page = NULL;
792
793 mask = cma_bitmap_aligned_mask(cma, align);
794 offset = cma_bitmap_aligned_offset(cma, cmr, align);
795 bitmap_maxno = cma_bitmap_maxno(cma, cmr);
796 bitmap_count = cma_bitmap_pages_to_bits(cma, count);
797
798 if (bitmap_count > bitmap_maxno)
799 goto out;
800
801 for (start = 0; ; start = bitmap_no + mask + 1) {
802 spin_lock_irq(&cma->lock);
803 /*
804 * If the request is larger than the available number
805 * of pages, stop right away.
806 */
807 if (count > cma->available_count) {
808 spin_unlock_irq(&cma->lock);
809 break;
810 }
811 bitmap_no = bitmap_find_next_zero_area_off(cmr->bitmap,
812 bitmap_maxno, start, bitmap_count, mask,
813 offset);
814 if (bitmap_no >= bitmap_maxno) {
815 spin_unlock_irq(&cma->lock);
816 break;
817 }
818
819 pfn = cmr->base_pfn + (bitmap_no << cma->order_per_bit);
820 page = pfn_to_page(pfn);
821
822 /*
823 * Do not hand out page ranges that are not contiguous, so
824 * callers can just iterate the pages without having to worry
825 * about these corner cases.
826 */
827 if (!page_range_contiguous(page, count)) {
828 spin_unlock_irq(&cma->lock);
829 pr_warn_ratelimited("%s: %s: skipping incompatible area [0x%lx-0x%lx]",
830 __func__, cma->name, pfn, pfn + count - 1);
831 continue;
832 }
833
834 bitmap_set(cmr->bitmap, bitmap_no, bitmap_count);
835 cma->available_count -= count;
836 /*
837 * It's safe to drop the lock here. We've marked this region for
838 * our exclusive use. If the migration fails we will take the
839 * lock again and unmark it.
840 */
841 spin_unlock_irq(&cma->lock);
842
843 mutex_lock(&cma->alloc_mutex);
844 ret = alloc_contig_frozen_range(pfn, pfn + count, ACR_FLAGS_CMA, gfp);
845 mutex_unlock(&cma->alloc_mutex);
846 if (!ret)
847 break;
848
849 cma_clear_bitmap(cma, cmr, pfn, count);
850 if (ret != -EBUSY)
851 break;
852
853 pr_debug("%s(): memory range at pfn 0x%lx %p is busy, retrying\n",
854 __func__, pfn, page);
855
856 trace_cma_alloc_busy_retry(cma->name, pfn, page, count, align);
857 }
858 out:
859 if (!ret)
860 *pagep = page;
861 return ret;
862 }
863
__cma_alloc_frozen(struct cma * cma,unsigned long count,unsigned int align,gfp_t gfp)864 static struct page *__cma_alloc_frozen(struct cma *cma,
865 unsigned long count, unsigned int align, gfp_t gfp)
866 {
867 struct page *page = NULL;
868 int ret = -ENOMEM, r;
869 unsigned long i;
870 const char *name = cma ? cma->name : NULL;
871
872 if (!cma || !cma->count)
873 return page;
874
875 pr_debug("%s(cma %p, name: %s, count %lu, align %d)\n", __func__,
876 (void *)cma, cma->name, count, align);
877
878 if (!count)
879 return page;
880
881 trace_cma_alloc_start(name, count, cma->available_count, cma->count, align);
882
883 for (r = 0; r < cma->nranges; r++) {
884 page = NULL;
885
886 ret = cma_range_alloc(cma, &cma->ranges[r], count, align,
887 &page, gfp);
888 if (ret != -EBUSY || page)
889 break;
890 }
891
892 /*
893 * CMA can allocate multiple page blocks, which results in different
894 * blocks being marked with different tags. Reset the tags to ignore
895 * those page blocks.
896 */
897 if (page) {
898 for (i = 0; i < count; i++)
899 page_kasan_tag_reset(page + i);
900 }
901
902 if (ret && !(gfp & __GFP_NOWARN)) {
903 pr_err_ratelimited("%s: %s: alloc failed, req-size: %lu pages, ret: %d\n",
904 __func__, cma->name, count, ret);
905 cma_debug_show_areas(cma);
906 }
907
908 pr_debug("%s(): returned %p\n", __func__, page);
909 trace_cma_alloc_finish(name, page ? page_to_pfn(page) : 0,
910 page, count, align, ret);
911 if (page) {
912 count_vm_event(CMA_ALLOC_SUCCESS);
913 cma_sysfs_account_success_pages(cma, count);
914 } else {
915 count_vm_event(CMA_ALLOC_FAIL);
916 cma_sysfs_account_fail_pages(cma, count);
917 }
918
919 return page;
920 }
921
cma_alloc_frozen(struct cma * cma,unsigned long count,unsigned int align,bool no_warn)922 struct page *cma_alloc_frozen(struct cma *cma, unsigned long count,
923 unsigned int align, bool no_warn)
924 {
925 gfp_t gfp = GFP_KERNEL | (no_warn ? __GFP_NOWARN : 0);
926
927 return __cma_alloc_frozen(cma, count, align, gfp);
928 }
929
cma_alloc_frozen_compound(struct cma * cma,unsigned int order)930 struct page *cma_alloc_frozen_compound(struct cma *cma, unsigned int order)
931 {
932 gfp_t gfp = GFP_KERNEL | __GFP_COMP | __GFP_NOWARN;
933
934 return __cma_alloc_frozen(cma, 1 << order, order, gfp);
935 }
936
937 /**
938 * cma_alloc() - allocate pages from contiguous area
939 * @cma: Contiguous memory region for which the allocation is performed.
940 * @count: Requested number of pages.
941 * @align: Requested alignment of pages (in PAGE_SIZE order).
942 * @no_warn: Avoid printing message about failed allocation
943 *
944 * This function allocates part of contiguous memory on specific
945 * contiguous memory area.
946 */
cma_alloc(struct cma * cma,unsigned long count,unsigned int align,bool no_warn)947 struct page *cma_alloc(struct cma *cma, unsigned long count,
948 unsigned int align, bool no_warn)
949 {
950 struct page *page;
951
952 page = cma_alloc_frozen(cma, count, align, no_warn);
953 if (page)
954 set_pages_refcounted(page, count);
955
956 return page;
957 }
958 EXPORT_SYMBOL_GPL(cma_alloc);
959
find_cma_memrange(struct cma * cma,const struct page * pages,unsigned long count)960 static struct cma_memrange *find_cma_memrange(struct cma *cma,
961 const struct page *pages, unsigned long count)
962 {
963 struct cma_memrange *cmr = NULL;
964 unsigned long pfn, end_pfn;
965 int r;
966
967 pr_debug("%s(page %p, count %lu)\n", __func__, (void *)pages, count);
968
969 if (!cma || !pages || count > cma->count)
970 return NULL;
971
972 pfn = page_to_pfn(pages);
973
974 for (r = 0; r < cma->nranges; r++) {
975 cmr = &cma->ranges[r];
976 end_pfn = cmr->base_pfn + cmr->count;
977 if (pfn >= cmr->base_pfn && pfn < end_pfn) {
978 if (pfn + count <= end_pfn)
979 break;
980
981 VM_WARN_ON_ONCE(1);
982 }
983 }
984
985 if (r == cma->nranges) {
986 pr_debug("%s(page %p, count %lu, no cma range matches the page range)\n",
987 __func__, (void *)pages, count);
988 return NULL;
989 }
990
991 return cmr;
992 }
993
__cma_release_frozen(struct cma * cma,struct cma_memrange * cmr,const struct page * pages,unsigned long count)994 static void __cma_release_frozen(struct cma *cma, struct cma_memrange *cmr,
995 const struct page *pages, unsigned long count)
996 {
997 unsigned long pfn = page_to_pfn(pages);
998
999 pr_debug("%s(page %p, count %lu)\n", __func__, (void *)pages, count);
1000
1001 free_contig_frozen_range(pfn, count);
1002 cma_clear_bitmap(cma, cmr, pfn, count);
1003 cma_sysfs_account_release_pages(cma, count);
1004 trace_cma_release(cma->name, pfn, pages, count);
1005 }
1006
1007 /**
1008 * cma_release() - release allocated pages
1009 * @cma: Contiguous memory region for which the allocation is performed.
1010 * @pages: Allocated pages.
1011 * @count: Number of allocated pages.
1012 *
1013 * This function releases memory allocated by cma_alloc().
1014 * It returns false when provided pages do not belong to contiguous area and
1015 * true otherwise.
1016 */
cma_release(struct cma * cma,const struct page * pages,unsigned long count)1017 bool cma_release(struct cma *cma, const struct page *pages,
1018 unsigned long count)
1019 {
1020 struct cma_memrange *cmr;
1021 unsigned long ret = 0;
1022 unsigned long i, pfn;
1023
1024 cmr = find_cma_memrange(cma, pages, count);
1025 if (!cmr)
1026 return false;
1027
1028 pfn = page_to_pfn(pages);
1029 for (i = 0; i < count; i++, pfn++)
1030 ret += !put_page_testzero(pfn_to_page(pfn));
1031
1032 WARN(ret, "%lu pages are still in use!\n", ret);
1033
1034 __cma_release_frozen(cma, cmr, pages, count);
1035
1036 return true;
1037 }
1038 EXPORT_SYMBOL_GPL(cma_release);
1039
cma_release_frozen(struct cma * cma,const struct page * pages,unsigned long count)1040 bool cma_release_frozen(struct cma *cma, const struct page *pages,
1041 unsigned long count)
1042 {
1043 struct cma_memrange *cmr;
1044
1045 cmr = find_cma_memrange(cma, pages, count);
1046 if (!cmr)
1047 return false;
1048
1049 __cma_release_frozen(cma, cmr, pages, count);
1050
1051 return true;
1052 }
1053
cma_for_each_area(int (* it)(struct cma * cma,void * data),void * data)1054 int cma_for_each_area(int (*it)(struct cma *cma, void *data), void *data)
1055 {
1056 int i;
1057
1058 for (i = 0; i < cma_area_count; i++) {
1059 int ret = it(&cma_areas[i], data);
1060
1061 if (ret)
1062 return ret;
1063 }
1064
1065 return 0;
1066 }
1067
cma_intersects(struct cma * cma,unsigned long start,unsigned long end)1068 bool cma_intersects(struct cma *cma, unsigned long start, unsigned long end)
1069 {
1070 int r;
1071 struct cma_memrange *cmr;
1072 unsigned long rstart, rend;
1073
1074 for (r = 0; r < cma->nranges; r++) {
1075 cmr = &cma->ranges[r];
1076
1077 rstart = PFN_PHYS(cmr->base_pfn);
1078 rend = PFN_PHYS(cmr->base_pfn + cmr->count);
1079 if (end < rstart)
1080 continue;
1081 if (start >= rend)
1082 continue;
1083 return true;
1084 }
1085
1086 return false;
1087 }
1088
1089 /*
1090 * Very basic function to reserve memory from a CMA area that has not
1091 * yet been activated. This is expected to be called early, when the
1092 * system is single-threaded, so there is no locking. The alignment
1093 * checking is restrictive - only pageblock-aligned areas
1094 * (CMA_MIN_ALIGNMENT_BYTES) may be reserved through this function.
1095 * This keeps things simple, and is enough for the current use case.
1096 *
1097 * The CMA bitmaps have not yet been allocated, so just start
1098 * reserving from the bottom up, using a PFN to keep track
1099 * of what has been reserved. Unreserving is not possible.
1100 *
1101 * The caller is responsible for initializing the page structures
1102 * in the area properly, since this just points to memblock-allocated
1103 * memory. The caller should subsequently use init_cma_pageblock to
1104 * set the migrate type and CMA stats the pageblocks that were reserved.
1105 *
1106 * If the CMA area fails to activate later, memory obtained through
1107 * this interface is not handed to the page allocator, this is
1108 * the responsibility of the caller (e.g. like normal memblock-allocated
1109 * memory).
1110 */
cma_reserve_early(struct cma * cma,unsigned long size)1111 void __init *cma_reserve_early(struct cma *cma, unsigned long size)
1112 {
1113 int r;
1114 struct cma_memrange *cmr;
1115 unsigned long available;
1116 void *ret = NULL;
1117
1118 if (!cma || !cma->count)
1119 return NULL;
1120 /*
1121 * Can only be called early in init.
1122 */
1123 if (test_bit(CMA_ACTIVATED, &cma->flags))
1124 return NULL;
1125
1126 if (!IS_ALIGNED(size, CMA_MIN_ALIGNMENT_BYTES))
1127 return NULL;
1128
1129 if (!IS_ALIGNED(size, (PAGE_SIZE << cma->order_per_bit)))
1130 return NULL;
1131
1132 size >>= PAGE_SHIFT;
1133
1134 if (size > cma->available_count)
1135 return NULL;
1136
1137 for (r = 0; r < cma->nranges; r++) {
1138 cmr = &cma->ranges[r];
1139 available = cmr->count - (cmr->early_pfn - cmr->base_pfn);
1140 if (size <= available) {
1141 ret = phys_to_virt(PFN_PHYS(cmr->early_pfn));
1142 cmr->early_pfn += size;
1143 cma->available_count -= size;
1144 return ret;
1145 }
1146 }
1147
1148 return ret;
1149 }
1150