cma.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. * Contiguous Memory Allocator
  3. *
  4. * Copyright (c) 2010-2011 by Samsung Electronics.
  5. * Copyright IBM Corporation, 2013
  6. * Copyright LG Electronics Inc., 2014
  7. * Written by:
  8. * Marek Szyprowski <[email protected]>
  9. * Michal Nazarewicz <[email protected]>
  10. * Aneesh Kumar K.V <[email protected]>
  11. * Joonsoo Kim <[email protected]>
  12. *
  13. * This program is free software; you can redistribute it and/or
  14. * modify it under the terms of the GNU General Public License as
  15. * published by the Free Software Foundation; either version 2 of the
  16. * License or (at your optional) any later version of the license.
  17. */
  18. #define pr_fmt(fmt) "cma: " fmt
  19. #ifdef CONFIG_CMA_DEBUG
  20. #ifndef DEBUG
  21. # define DEBUG
  22. #endif
  23. #endif
  24. #define CREATE_TRACE_POINTS
  25. #include <linux/memblock.h>
  26. #include <linux/err.h>
  27. #include <linux/mm.h>
  28. #include <linux/mutex.h>
  29. #include <linux/sizes.h>
  30. #include <linux/slab.h>
  31. #include <linux/log2.h>
  32. #include <linux/cma.h>
  33. #include <linux/highmem.h>
  34. #include <linux/io.h>
  35. #include <linux/delay.h>
  36. #include <linux/show_mem_notifier.h>
  37. #include <trace/events/cma.h>
  38. #include "cma.h"
  39. struct cma cma_areas[MAX_CMA_AREAS];
  40. unsigned cma_area_count;
  41. static DEFINE_MUTEX(cma_mutex);
  42. phys_addr_t cma_get_base(const struct cma *cma)
  43. {
  44. return PFN_PHYS(cma->base_pfn);
  45. }
  46. unsigned long cma_get_size(const struct cma *cma)
  47. {
  48. return cma->count << PAGE_SHIFT;
  49. }
  50. const char *cma_get_name(const struct cma *cma)
  51. {
  52. return cma->name ? cma->name : "(undefined)";
  53. }
  54. static unsigned long cma_bitmap_aligned_mask(const struct cma *cma,
  55. unsigned int align_order)
  56. {
  57. if (align_order <= cma->order_per_bit)
  58. return 0;
  59. return (1UL << (align_order - cma->order_per_bit)) - 1;
  60. }
  61. /*
  62. * Find the offset of the base PFN from the specified align_order.
  63. * The value returned is represented in order_per_bits.
  64. */
  65. static unsigned long cma_bitmap_aligned_offset(const struct cma *cma,
  66. unsigned int align_order)
  67. {
  68. return (cma->base_pfn & ((1UL << align_order) - 1))
  69. >> cma->order_per_bit;
  70. }
  71. static unsigned long cma_bitmap_pages_to_bits(const struct cma *cma,
  72. unsigned long pages)
  73. {
  74. return ALIGN(pages, 1UL << cma->order_per_bit) >> cma->order_per_bit;
  75. }
  76. static void cma_clear_bitmap(struct cma *cma, unsigned long pfn,
  77. unsigned int count)
  78. {
  79. unsigned long bitmap_no, bitmap_count;
  80. bitmap_no = (pfn - cma->base_pfn) >> cma->order_per_bit;
  81. bitmap_count = cma_bitmap_pages_to_bits(cma, count);
  82. mutex_lock(&cma->lock);
  83. bitmap_clear(cma->bitmap, bitmap_no, bitmap_count);
  84. mutex_unlock(&cma->lock);
  85. }
  86. static int cma_showmem_notifier(struct notifier_block *nb,
  87. unsigned long action, void *data)
  88. {
  89. int i;
  90. unsigned long used;
  91. struct cma *cma;
  92. for (i = 0; i < cma_area_count; i++) {
  93. cma = &cma_areas[i];
  94. used = bitmap_weight(cma->bitmap,
  95. (int)cma_bitmap_maxno(cma));
  96. used <<= cma->order_per_bit;
  97. pr_info("cma-%d pages: => %lu used of %lu total pages\n",
  98. i, used, cma->count);
  99. }
  100. return 0;
  101. }
  102. static struct notifier_block cma_nb = {
  103. .notifier_call = cma_showmem_notifier,
  104. };
  105. static int __init cma_activate_area(struct cma *cma)
  106. {
  107. int bitmap_size = BITS_TO_LONGS(cma_bitmap_maxno(cma)) * sizeof(long);
  108. unsigned long base_pfn = cma->base_pfn, pfn = base_pfn;
  109. unsigned i = cma->count >> pageblock_order;
  110. struct zone *zone;
  111. cma->bitmap = kzalloc(bitmap_size, GFP_KERNEL);
  112. if (!cma->bitmap) {
  113. cma->count = 0;
  114. return -ENOMEM;
  115. }
  116. WARN_ON_ONCE(!pfn_valid(pfn));
  117. zone = page_zone(pfn_to_page(pfn));
  118. do {
  119. unsigned j;
  120. base_pfn = pfn;
  121. for (j = pageblock_nr_pages; j; --j, pfn++) {
  122. WARN_ON_ONCE(!pfn_valid(pfn));
  123. /*
  124. * alloc_contig_range requires the pfn range
  125. * specified to be in the same zone. Make this
  126. * simple by forcing the entire CMA resv range
  127. * to be in the same zone.
  128. */
  129. if (page_zone(pfn_to_page(pfn)) != zone)
  130. goto err;
  131. }
  132. init_cma_reserved_pageblock(pfn_to_page(base_pfn));
  133. } while (--i);
  134. mutex_init(&cma->lock);
  135. #ifdef CONFIG_CMA_DEBUGFS
  136. INIT_HLIST_HEAD(&cma->mem_head);
  137. spin_lock_init(&cma->mem_head_lock);
  138. #endif
  139. if (!PageHighMem(pfn_to_page(cma->base_pfn)))
  140. kmemleak_free_part(__va(cma->base_pfn << PAGE_SHIFT),
  141. cma->count << PAGE_SHIFT);
  142. return 0;
  143. err:
  144. kfree(cma->bitmap);
  145. cma->count = 0;
  146. return -EINVAL;
  147. }
  148. static int __init cma_init_reserved_areas(void)
  149. {
  150. int i;
  151. for (i = 0; i < cma_area_count; i++) {
  152. int ret = cma_activate_area(&cma_areas[i]);
  153. if (ret)
  154. return ret;
  155. }
  156. show_mem_notifier_register(&cma_nb);
  157. return 0;
  158. }
  159. core_initcall(cma_init_reserved_areas);
  160. /**
  161. * cma_init_reserved_mem() - create custom contiguous area from reserved memory
  162. * @base: Base address of the reserved area
  163. * @size: Size of the reserved area (in bytes),
  164. * @order_per_bit: Order of pages represented by one bit on bitmap.
  165. * @res_cma: Pointer to store the created cma region.
  166. *
  167. * This function creates custom contiguous area from already reserved memory.
  168. */
  169. int __init cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
  170. unsigned int order_per_bit,
  171. const char *name,
  172. struct cma **res_cma)
  173. {
  174. struct cma *cma;
  175. phys_addr_t alignment;
  176. /* Sanity checks */
  177. if (cma_area_count == ARRAY_SIZE(cma_areas)) {
  178. pr_err("Not enough slots for CMA reserved regions!\n");
  179. return -ENOSPC;
  180. }
  181. if (!size || !memblock_is_region_reserved(base, size))
  182. return -EINVAL;
  183. /* ensure minimal alignment required by mm core */
  184. alignment = PAGE_SIZE <<
  185. max_t(unsigned long, MAX_ORDER - 1, pageblock_order);
  186. /* alignment should be aligned with order_per_bit */
  187. if (!IS_ALIGNED(alignment >> PAGE_SHIFT, 1 << order_per_bit))
  188. return -EINVAL;
  189. if (ALIGN(base, alignment) != base || ALIGN(size, alignment) != size)
  190. return -EINVAL;
  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. if (name) {
  197. cma->name = name;
  198. } else {
  199. cma->name = kasprintf(GFP_KERNEL, "cma%d\n", cma_area_count);
  200. if (!cma->name)
  201. return -ENOMEM;
  202. }
  203. cma->base_pfn = PFN_DOWN(base);
  204. cma->count = size >> PAGE_SHIFT;
  205. cma->order_per_bit = order_per_bit;
  206. *res_cma = cma;
  207. cma_area_count++;
  208. totalcma_pages += (size / PAGE_SIZE);
  209. return 0;
  210. }
  211. /**
  212. * cma_declare_contiguous() - reserve custom contiguous area
  213. * @base: Base address of the reserved area optional, use 0 for any
  214. * @size: Size of the reserved area (in bytes),
  215. * @limit: End address of the reserved memory (optional, 0 for any).
  216. * @alignment: Alignment for the CMA area, should be power of 2 or zero
  217. * @order_per_bit: Order of pages represented by one bit on bitmap.
  218. * @fixed: hint about where to place the reserved area
  219. * @res_cma: Pointer to store the created cma region.
  220. *
  221. * This function reserves memory from early allocator. It should be
  222. * called by arch specific code once the early allocator (memblock or bootmem)
  223. * has been activated and all other subsystems have already allocated/reserved
  224. * memory. This function allows to create custom reserved areas.
  225. *
  226. * If @fixed is true, reserve contiguous area at exactly @base. If false,
  227. * reserve in range from @base to @limit.
  228. */
  229. int __init cma_declare_contiguous(phys_addr_t base,
  230. phys_addr_t size, phys_addr_t limit,
  231. phys_addr_t alignment, unsigned int order_per_bit,
  232. bool fixed, const char *name, struct cma **res_cma)
  233. {
  234. phys_addr_t memblock_end = memblock_end_of_DRAM();
  235. phys_addr_t highmem_start;
  236. int ret = 0;
  237. #ifdef CONFIG_X86
  238. /*
  239. * high_memory isn't direct mapped memory so retrieving its physical
  240. * address isn't appropriate. But it would be useful to check the
  241. * physical address of the highmem boundary so it's justifiable to get
  242. * the physical address from it. On x86 there is a validation check for
  243. * this case, so the following workaround is needed to avoid it.
  244. */
  245. highmem_start = __pa_nodebug(high_memory);
  246. #else
  247. highmem_start = __pa(high_memory);
  248. #endif
  249. pr_debug("%s(size %pa, base %pa, limit %pa alignment %pa)\n",
  250. __func__, &size, &base, &limit, &alignment);
  251. if (cma_area_count == ARRAY_SIZE(cma_areas)) {
  252. pr_err("Not enough slots for CMA reserved regions!\n");
  253. return -ENOSPC;
  254. }
  255. if (!size)
  256. return -EINVAL;
  257. if (alignment && !is_power_of_2(alignment))
  258. return -EINVAL;
  259. /*
  260. * Sanitise input arguments.
  261. * Pages both ends in CMA area could be merged into adjacent unmovable
  262. * migratetype page by page allocator's buddy algorithm. In the case,
  263. * you couldn't get a contiguous memory, which is not what we want.
  264. */
  265. alignment = max(alignment, (phys_addr_t)PAGE_SIZE <<
  266. max_t(unsigned long, MAX_ORDER - 1, pageblock_order));
  267. if (fixed && base & (alignment - 1)) {
  268. ret = -EINVAL;
  269. pr_err("Region at %pa must be aligned to %pa bytes\n",
  270. &base, &alignment);
  271. goto err;
  272. }
  273. base = ALIGN(base, alignment);
  274. size = ALIGN(size, alignment);
  275. limit &= ~(alignment - 1);
  276. if (!base)
  277. fixed = false;
  278. /* size should be aligned with order_per_bit */
  279. if (!IS_ALIGNED(size >> PAGE_SHIFT, 1 << order_per_bit))
  280. return -EINVAL;
  281. /*
  282. * If allocating at a fixed base the request region must not cross the
  283. * low/high memory boundary.
  284. */
  285. if (fixed && base < highmem_start && base + size > highmem_start) {
  286. ret = -EINVAL;
  287. pr_err("Region at %pa defined on low/high memory boundary (%pa)\n",
  288. &base, &highmem_start);
  289. goto err;
  290. }
  291. /*
  292. * If the limit is unspecified or above the memblock end, its effective
  293. * value will be the memblock end. Set it explicitly to simplify further
  294. * checks.
  295. */
  296. if (limit == 0 || limit > memblock_end)
  297. limit = memblock_end;
  298. if (base + size > limit) {
  299. ret = -EINVAL;
  300. pr_err("Size (%pa) of region at %pa exceeds limit (%pa)\n",
  301. &size, &base, &limit);
  302. goto err;
  303. }
  304. /* Reserve memory */
  305. if (fixed) {
  306. if (memblock_is_region_reserved(base, size) ||
  307. memblock_reserve(base, size) < 0) {
  308. ret = -EBUSY;
  309. goto err;
  310. }
  311. } else {
  312. phys_addr_t addr = 0;
  313. /*
  314. * All pages in the reserved area must come from the same zone.
  315. * If the requested region crosses the low/high memory boundary,
  316. * try allocating from high memory first and fall back to low
  317. * memory in case of failure.
  318. */
  319. if (base < highmem_start && limit > highmem_start) {
  320. addr = memblock_alloc_range(size, alignment,
  321. highmem_start, limit,
  322. MEMBLOCK_NONE);
  323. limit = highmem_start;
  324. }
  325. if (!addr) {
  326. addr = memblock_alloc_range(size, alignment, base,
  327. limit,
  328. MEMBLOCK_NONE);
  329. if (!addr) {
  330. ret = -ENOMEM;
  331. goto err;
  332. }
  333. }
  334. /*
  335. * kmemleak scans/reads tracked objects for pointers to other
  336. * objects but this address isn't mapped and accessible
  337. */
  338. kmemleak_ignore_phys(addr);
  339. base = addr;
  340. }
  341. ret = cma_init_reserved_mem(base, size, order_per_bit, name, res_cma);
  342. if (ret)
  343. goto free_mem;
  344. pr_info("Reserved %ld MiB at %pa\n", (unsigned long)size / SZ_1M,
  345. &base);
  346. return 0;
  347. free_mem:
  348. memblock_free(base, size);
  349. err:
  350. pr_err("Failed to reserve %ld MiB\n", (unsigned long)size / SZ_1M);
  351. return ret;
  352. }
  353. #ifdef CONFIG_CMA_DEBUG
  354. static void cma_debug_show_areas(struct cma *cma)
  355. {
  356. unsigned long next_zero_bit, next_set_bit;
  357. unsigned long start = 0;
  358. unsigned int nr_zero, nr_total = 0;
  359. mutex_lock(&cma->lock);
  360. pr_info("number of available pages: ");
  361. for (;;) {
  362. next_zero_bit = find_next_zero_bit(cma->bitmap, cma->count, start);
  363. if (next_zero_bit >= cma->count)
  364. break;
  365. next_set_bit = find_next_bit(cma->bitmap, cma->count, next_zero_bit);
  366. nr_zero = next_set_bit - next_zero_bit;
  367. pr_cont("%s%u@%lu", nr_total ? "+" : "", nr_zero, next_zero_bit);
  368. nr_total += nr_zero;
  369. start = next_zero_bit + nr_zero;
  370. }
  371. pr_cont("=> %u free of %lu total pages\n", nr_total, cma->count);
  372. mutex_unlock(&cma->lock);
  373. }
  374. #else
  375. static inline void cma_debug_show_areas(struct cma *cma) { }
  376. #endif
  377. /**
  378. * cma_alloc() - allocate pages from contiguous area
  379. * @cma: Contiguous memory region for which the allocation is performed.
  380. * @count: Requested number of pages.
  381. * @align: Requested alignment of pages (in PAGE_SIZE order).
  382. *
  383. * This function allocates part of contiguous memory on specific
  384. * contiguous memory area.
  385. */
  386. struct page *cma_alloc(struct cma *cma, size_t count, unsigned int align)
  387. {
  388. unsigned long mask, offset;
  389. unsigned long pfn = -1;
  390. unsigned long start = 0;
  391. unsigned long bitmap_maxno, bitmap_no, bitmap_count;
  392. struct page *page = NULL;
  393. int retry_after_sleep = 0;
  394. int ret = -ENOMEM;
  395. int max_retries = 2;
  396. int available_regions = 0;
  397. if (!cma || !cma->count)
  398. return NULL;
  399. pr_debug("%s(cma %p, count %zu, align %d)\n", __func__, (void *)cma,
  400. count, align);
  401. if (!count)
  402. return NULL;
  403. trace_cma_alloc_start(count, align);
  404. mask = cma_bitmap_aligned_mask(cma, align);
  405. offset = cma_bitmap_aligned_offset(cma, align);
  406. bitmap_maxno = cma_bitmap_maxno(cma);
  407. bitmap_count = cma_bitmap_pages_to_bits(cma, count);
  408. if (bitmap_count > bitmap_maxno)
  409. return NULL;
  410. for (;;) {
  411. mutex_lock(&cma->lock);
  412. bitmap_no = bitmap_find_next_zero_area_off(cma->bitmap,
  413. bitmap_maxno, start, bitmap_count, mask,
  414. offset);
  415. if (bitmap_no >= bitmap_maxno) {
  416. if (retry_after_sleep < max_retries) {
  417. start = 0;
  418. /*
  419. * update max retries if available free regions
  420. * are less.
  421. */
  422. if (available_regions < 3)
  423. max_retries = 5;
  424. available_regions = 0;
  425. /*
  426. * Page may be momentarily pinned by some other
  427. * process which has been scheduled out, eg.
  428. * in exit path, during unmap call, or process
  429. * fork and so cannot be freed there. Sleep
  430. * for 100ms and retry twice to see if it has
  431. * been freed later.
  432. */
  433. mutex_unlock(&cma->lock);
  434. msleep(100);
  435. retry_after_sleep++;
  436. continue;
  437. } else {
  438. mutex_unlock(&cma->lock);
  439. break;
  440. }
  441. }
  442. available_regions++;
  443. bitmap_set(cma->bitmap, bitmap_no, bitmap_count);
  444. /*
  445. * It's safe to drop the lock here. We've marked this region for
  446. * our exclusive use. If the migration fails we will take the
  447. * lock again and unmark it.
  448. */
  449. mutex_unlock(&cma->lock);
  450. pfn = cma->base_pfn + (bitmap_no << cma->order_per_bit);
  451. mutex_lock(&cma_mutex);
  452. ret = alloc_contig_range(pfn, pfn + count, MIGRATE_CMA);
  453. mutex_unlock(&cma_mutex);
  454. if (ret == 0) {
  455. page = pfn_to_page(pfn);
  456. break;
  457. }
  458. cma_clear_bitmap(cma, pfn, count);
  459. if (ret != -EBUSY)
  460. break;
  461. pr_debug("%s(): memory range at %p is busy, retrying\n",
  462. __func__, pfn_to_page(pfn));
  463. trace_cma_alloc_busy_retry(pfn, pfn_to_page(pfn), count, align);
  464. /* try again with a bit different memory target */
  465. start = bitmap_no + mask + 1;
  466. }
  467. trace_cma_alloc(pfn, page, count, align);
  468. if (ret) {
  469. pr_info("%s: alloc failed, req-size: %zu pages, ret: %d\n",
  470. __func__, count, ret);
  471. cma_debug_show_areas(cma);
  472. }
  473. pr_debug("%s(): returned %p\n", __func__, page);
  474. return page;
  475. }
  476. /**
  477. * cma_release() - release allocated pages
  478. * @cma: Contiguous memory region for which the allocation is performed.
  479. * @pages: Allocated pages.
  480. * @count: Number of allocated pages.
  481. *
  482. * This function releases memory allocated by alloc_cma().
  483. * It returns false when provided pages do not belong to contiguous area and
  484. * true otherwise.
  485. */
  486. bool cma_release(struct cma *cma, const struct page *pages, unsigned int count)
  487. {
  488. unsigned long pfn;
  489. if (!cma || !pages)
  490. return false;
  491. pr_debug("%s(page %p)\n", __func__, (void *)pages);
  492. pfn = page_to_pfn(pages);
  493. if (pfn < cma->base_pfn || pfn >= cma->base_pfn + cma->count)
  494. return false;
  495. VM_BUG_ON(pfn + count > cma->base_pfn + cma->count);
  496. free_contig_range(pfn, count);
  497. cma_clear_bitmap(cma, pfn, count);
  498. trace_cma_release(pfn, pages, count);
  499. return true;
  500. }