cma.c 29 KB

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