memory_hotplug.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/mm/memory_hotplug.c
  4. *
  5. * Copyright (C)
  6. */
  7. #include <linux/stddef.h>
  8. #include <linux/mm.h>
  9. #include <linux/sched/signal.h>
  10. #include <linux/swap.h>
  11. #include <linux/interrupt.h>
  12. #include <linux/pagemap.h>
  13. #include <linux/compiler.h>
  14. #include <linux/export.h>
  15. #include <linux/writeback.h>
  16. #include <linux/slab.h>
  17. #include <linux/sysctl.h>
  18. #include <linux/cpu.h>
  19. #include <linux/memory.h>
  20. #include <linux/memremap.h>
  21. #include <linux/memory_hotplug.h>
  22. #include <linux/vmalloc.h>
  23. #include <linux/ioport.h>
  24. #include <linux/delay.h>
  25. #include <linux/migrate.h>
  26. #include <linux/page-isolation.h>
  27. #include <linux/pfn.h>
  28. #include <linux/suspend.h>
  29. #include <linux/mm_inline.h>
  30. #include <linux/firmware-map.h>
  31. #include <linux/stop_machine.h>
  32. #include <linux/hugetlb.h>
  33. #include <linux/memblock.h>
  34. #include <linux/compaction.h>
  35. #include <linux/rmap.h>
  36. #include <linux/module.h>
  37. #include <linux/node.h>
  38. #include <asm/tlbflush.h>
  39. #include "internal.h"
  40. #include "shuffle.h"
  41. enum {
  42. MEMMAP_ON_MEMORY_DISABLE = 0,
  43. MEMMAP_ON_MEMORY_ENABLE,
  44. MEMMAP_ON_MEMORY_FORCE,
  45. };
  46. static int memmap_mode __read_mostly = MEMMAP_ON_MEMORY_DISABLE;
  47. static inline unsigned long memory_block_memmap_size(void)
  48. {
  49. return PHYS_PFN(memory_block_size_bytes()) * sizeof(struct page);
  50. }
  51. static inline unsigned long memory_block_memmap_on_memory_pages(void)
  52. {
  53. unsigned long nr_pages = PFN_UP(memory_block_memmap_size());
  54. /*
  55. * In "forced" memmap_on_memory mode, we add extra pages to align the
  56. * vmemmap size to cover full pageblocks. That way, we can add memory
  57. * even if the vmemmap size is not properly aligned, however, we might waste
  58. * memory.
  59. */
  60. if (memmap_mode == MEMMAP_ON_MEMORY_FORCE)
  61. return pageblock_align(nr_pages);
  62. return nr_pages;
  63. }
  64. #ifdef CONFIG_MHP_MEMMAP_ON_MEMORY
  65. /*
  66. * memory_hotplug.memmap_on_memory parameter
  67. */
  68. static int set_memmap_mode(const char *val, const struct kernel_param *kp)
  69. {
  70. int ret, mode;
  71. bool enabled;
  72. if (sysfs_streq(val, "force") || sysfs_streq(val, "FORCE")) {
  73. mode = MEMMAP_ON_MEMORY_FORCE;
  74. } else {
  75. ret = kstrtobool(val, &enabled);
  76. if (ret < 0)
  77. return ret;
  78. if (enabled)
  79. mode = MEMMAP_ON_MEMORY_ENABLE;
  80. else
  81. mode = MEMMAP_ON_MEMORY_DISABLE;
  82. }
  83. *((int *)kp->arg) = mode;
  84. if (mode == MEMMAP_ON_MEMORY_FORCE) {
  85. unsigned long memmap_pages = memory_block_memmap_on_memory_pages();
  86. pr_info_once("Memory hotplug will waste %ld pages in each memory block\n",
  87. memmap_pages - PFN_UP(memory_block_memmap_size()));
  88. }
  89. return 0;
  90. }
  91. static int get_memmap_mode(char *buffer, const struct kernel_param *kp)
  92. {
  93. int mode = *((int *)kp->arg);
  94. if (mode == MEMMAP_ON_MEMORY_FORCE)
  95. return sprintf(buffer, "force\n");
  96. return sprintf(buffer, "%c\n", mode ? 'Y' : 'N');
  97. }
  98. static const struct kernel_param_ops memmap_mode_ops = {
  99. .set = set_memmap_mode,
  100. .get = get_memmap_mode,
  101. };
  102. module_param_cb(memmap_on_memory, &memmap_mode_ops, &memmap_mode, 0444);
  103. MODULE_PARM_DESC(memmap_on_memory, "Enable memmap on memory for memory hotplug\n"
  104. "With value \"force\" it could result in memory wastage due "
  105. "to memmap size limitations (Y/N/force)");
  106. static inline bool mhp_memmap_on_memory(void)
  107. {
  108. return memmap_mode != MEMMAP_ON_MEMORY_DISABLE;
  109. }
  110. #else
  111. static inline bool mhp_memmap_on_memory(void)
  112. {
  113. return false;
  114. }
  115. #endif
  116. enum {
  117. ONLINE_POLICY_CONTIG_ZONES = 0,
  118. ONLINE_POLICY_AUTO_MOVABLE,
  119. };
  120. static const char * const online_policy_to_str[] = {
  121. [ONLINE_POLICY_CONTIG_ZONES] = "contig-zones",
  122. [ONLINE_POLICY_AUTO_MOVABLE] = "auto-movable",
  123. };
  124. static int set_online_policy(const char *val, const struct kernel_param *kp)
  125. {
  126. int ret = sysfs_match_string(online_policy_to_str, val);
  127. if (ret < 0)
  128. return ret;
  129. *((int *)kp->arg) = ret;
  130. return 0;
  131. }
  132. static int get_online_policy(char *buffer, const struct kernel_param *kp)
  133. {
  134. return sprintf(buffer, "%s\n", online_policy_to_str[*((int *)kp->arg)]);
  135. }
  136. /*
  137. * memory_hotplug.online_policy: configure online behavior when onlining without
  138. * specifying a zone (MMOP_ONLINE)
  139. *
  140. * "contig-zones": keep zone contiguous
  141. * "auto-movable": online memory to ZONE_MOVABLE if the configuration
  142. * (auto_movable_ratio, auto_movable_numa_aware) allows for it
  143. */
  144. static int online_policy __read_mostly = ONLINE_POLICY_CONTIG_ZONES;
  145. static const struct kernel_param_ops online_policy_ops = {
  146. .set = set_online_policy,
  147. .get = get_online_policy,
  148. };
  149. module_param_cb(online_policy, &online_policy_ops, &online_policy, 0644);
  150. MODULE_PARM_DESC(online_policy,
  151. "Set the online policy (\"contig-zones\", \"auto-movable\") "
  152. "Default: \"contig-zones\"");
  153. /*
  154. * memory_hotplug.auto_movable_ratio: specify maximum MOVABLE:KERNEL ratio
  155. *
  156. * The ratio represent an upper limit and the kernel might decide to not
  157. * online some memory to ZONE_MOVABLE -- e.g., because hotplugged KERNEL memory
  158. * doesn't allow for more MOVABLE memory.
  159. */
  160. static unsigned int auto_movable_ratio __read_mostly = 301;
  161. module_param(auto_movable_ratio, uint, 0644);
  162. MODULE_PARM_DESC(auto_movable_ratio,
  163. "Set the maximum ratio of MOVABLE:KERNEL memory in the system "
  164. "in percent for \"auto-movable\" online policy. Default: 301");
  165. /*
  166. * memory_hotplug.auto_movable_numa_aware: consider numa node stats
  167. */
  168. #ifdef CONFIG_NUMA
  169. static bool auto_movable_numa_aware __read_mostly = true;
  170. module_param(auto_movable_numa_aware, bool, 0644);
  171. MODULE_PARM_DESC(auto_movable_numa_aware,
  172. "Consider numa node stats in addition to global stats in "
  173. "\"auto-movable\" online policy. Default: true");
  174. #endif /* CONFIG_NUMA */
  175. /*
  176. * online_page_callback contains pointer to current page onlining function.
  177. * Initially it is generic_online_page(). If it is required it could be
  178. * changed by calling set_online_page_callback() for callback registration
  179. * and restore_online_page_callback() for generic callback restore.
  180. */
  181. static online_page_callback_t online_page_callback = generic_online_page;
  182. static DEFINE_MUTEX(online_page_callback_lock);
  183. DEFINE_STATIC_PERCPU_RWSEM(mem_hotplug_lock);
  184. void get_online_mems(void)
  185. {
  186. percpu_down_read(&mem_hotplug_lock);
  187. }
  188. void put_online_mems(void)
  189. {
  190. percpu_up_read(&mem_hotplug_lock);
  191. }
  192. bool movable_node_enabled = false;
  193. static int mhp_default_online_type = -1;
  194. int mhp_get_default_online_type(void)
  195. {
  196. if (mhp_default_online_type >= 0)
  197. return mhp_default_online_type;
  198. if (IS_ENABLED(CONFIG_MHP_DEFAULT_ONLINE_TYPE_OFFLINE))
  199. mhp_default_online_type = MMOP_OFFLINE;
  200. else if (IS_ENABLED(CONFIG_MHP_DEFAULT_ONLINE_TYPE_ONLINE_AUTO))
  201. mhp_default_online_type = MMOP_ONLINE;
  202. else if (IS_ENABLED(CONFIG_MHP_DEFAULT_ONLINE_TYPE_ONLINE_KERNEL))
  203. mhp_default_online_type = MMOP_ONLINE_KERNEL;
  204. else if (IS_ENABLED(CONFIG_MHP_DEFAULT_ONLINE_TYPE_ONLINE_MOVABLE))
  205. mhp_default_online_type = MMOP_ONLINE_MOVABLE;
  206. else
  207. mhp_default_online_type = MMOP_OFFLINE;
  208. return mhp_default_online_type;
  209. }
  210. void mhp_set_default_online_type(int online_type)
  211. {
  212. mhp_default_online_type = online_type;
  213. }
  214. static int __init setup_memhp_default_state(char *str)
  215. {
  216. const int online_type = mhp_online_type_from_str(str);
  217. if (online_type >= 0)
  218. mhp_default_online_type = online_type;
  219. return 1;
  220. }
  221. __setup("memhp_default_state=", setup_memhp_default_state);
  222. void mem_hotplug_begin(void)
  223. {
  224. cpus_read_lock();
  225. percpu_down_write(&mem_hotplug_lock);
  226. }
  227. void mem_hotplug_done(void)
  228. {
  229. percpu_up_write(&mem_hotplug_lock);
  230. cpus_read_unlock();
  231. }
  232. u64 max_mem_size = U64_MAX;
  233. /* add this memory to iomem resource */
  234. static struct resource *register_memory_resource(u64 start, u64 size,
  235. const char *resource_name)
  236. {
  237. struct resource *res;
  238. unsigned long flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
  239. if (strcmp(resource_name, "System RAM"))
  240. flags |= IORESOURCE_SYSRAM_DRIVER_MANAGED;
  241. if (!mhp_range_allowed(start, size, true))
  242. return ERR_PTR(-E2BIG);
  243. /*
  244. * Make sure value parsed from 'mem=' only restricts memory adding
  245. * while booting, so that memory hotplug won't be impacted. Please
  246. * refer to document of 'mem=' in kernel-parameters.txt for more
  247. * details.
  248. */
  249. if (start + size > max_mem_size && system_state < SYSTEM_RUNNING)
  250. return ERR_PTR(-E2BIG);
  251. /*
  252. * Request ownership of the new memory range. This might be
  253. * a child of an existing resource that was present but
  254. * not marked as busy.
  255. */
  256. res = __request_region(&iomem_resource, start, size,
  257. resource_name, flags);
  258. if (!res) {
  259. pr_debug("Unable to reserve System RAM region: %016llx->%016llx\n",
  260. start, start + size);
  261. return ERR_PTR(-EEXIST);
  262. }
  263. return res;
  264. }
  265. static void release_memory_resource(struct resource *res)
  266. {
  267. if (!res)
  268. return;
  269. release_resource(res);
  270. kfree(res);
  271. }
  272. static int check_pfn_span(unsigned long pfn, unsigned long nr_pages)
  273. {
  274. /*
  275. * Disallow all operations smaller than a sub-section and only
  276. * allow operations smaller than a section for
  277. * SPARSEMEM_VMEMMAP. Note that check_hotplug_memory_range()
  278. * enforces a larger memory_block_size_bytes() granularity for
  279. * memory that will be marked online, so this check should only
  280. * fire for direct arch_{add,remove}_memory() users outside of
  281. * add_memory_resource().
  282. */
  283. unsigned long min_align;
  284. if (IS_ENABLED(CONFIG_SPARSEMEM_VMEMMAP))
  285. min_align = PAGES_PER_SUBSECTION;
  286. else
  287. min_align = PAGES_PER_SECTION;
  288. if (!IS_ALIGNED(pfn | nr_pages, min_align))
  289. return -EINVAL;
  290. return 0;
  291. }
  292. /*
  293. * Return page for the valid pfn only if the page is online. All pfn
  294. * walkers which rely on the fully initialized page->flags and others
  295. * should use this rather than pfn_valid && pfn_to_page
  296. */
  297. struct page *pfn_to_online_page(unsigned long pfn)
  298. {
  299. unsigned long nr = pfn_to_section_nr(pfn);
  300. struct dev_pagemap *pgmap;
  301. struct mem_section *ms;
  302. if (nr >= NR_MEM_SECTIONS)
  303. return NULL;
  304. ms = __nr_to_section(nr);
  305. if (!online_section(ms))
  306. return NULL;
  307. /*
  308. * Save some code text when online_section() +
  309. * pfn_section_valid() are sufficient.
  310. */
  311. if (IS_ENABLED(CONFIG_HAVE_ARCH_PFN_VALID) && !pfn_valid(pfn))
  312. return NULL;
  313. if (!pfn_section_valid(ms, pfn))
  314. return NULL;
  315. if (!online_device_section(ms))
  316. return pfn_to_page(pfn);
  317. /*
  318. * Slowpath: when ZONE_DEVICE collides with
  319. * ZONE_{NORMAL,MOVABLE} within the same section some pfns in
  320. * the section may be 'offline' but 'valid'. Only
  321. * get_dev_pagemap() can determine sub-section online status.
  322. */
  323. pgmap = get_dev_pagemap(pfn);
  324. put_dev_pagemap(pgmap);
  325. /* The presence of a pgmap indicates ZONE_DEVICE offline pfn */
  326. if (pgmap)
  327. return NULL;
  328. return pfn_to_page(pfn);
  329. }
  330. EXPORT_SYMBOL_GPL(pfn_to_online_page);
  331. int __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
  332. struct mhp_params *params)
  333. {
  334. const unsigned long end_pfn = pfn + nr_pages;
  335. unsigned long cur_nr_pages;
  336. int err;
  337. struct vmem_altmap *altmap = params->altmap;
  338. if (WARN_ON_ONCE(!pgprot_val(params->pgprot)))
  339. return -EINVAL;
  340. VM_BUG_ON(!mhp_range_allowed(PFN_PHYS(pfn), nr_pages * PAGE_SIZE, false));
  341. if (altmap) {
  342. /*
  343. * Validate altmap is within bounds of the total request
  344. */
  345. if (altmap->base_pfn != pfn
  346. || vmem_altmap_offset(altmap) > nr_pages) {
  347. pr_warn_once("memory add fail, invalid altmap\n");
  348. return -EINVAL;
  349. }
  350. altmap->alloc = 0;
  351. }
  352. if (check_pfn_span(pfn, nr_pages)) {
  353. WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
  354. return -EINVAL;
  355. }
  356. for (; pfn < end_pfn; pfn += cur_nr_pages) {
  357. /* Select all remaining pages up to the next section boundary */
  358. cur_nr_pages = min(end_pfn - pfn,
  359. SECTION_ALIGN_UP(pfn + 1) - pfn);
  360. err = sparse_add_section(nid, pfn, cur_nr_pages, altmap,
  361. params->pgmap);
  362. if (err)
  363. break;
  364. cond_resched();
  365. }
  366. vmemmap_populate_print_last();
  367. return err;
  368. }
  369. /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
  370. static unsigned long find_smallest_section_pfn(int nid, struct zone *zone,
  371. unsigned long start_pfn,
  372. unsigned long end_pfn)
  373. {
  374. for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SUBSECTION) {
  375. if (unlikely(!pfn_to_online_page(start_pfn)))
  376. continue;
  377. if (unlikely(pfn_to_nid(start_pfn) != nid))
  378. continue;
  379. if (zone != page_zone(pfn_to_page(start_pfn)))
  380. continue;
  381. return start_pfn;
  382. }
  383. return 0;
  384. }
  385. /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
  386. static unsigned long find_biggest_section_pfn(int nid, struct zone *zone,
  387. unsigned long start_pfn,
  388. unsigned long end_pfn)
  389. {
  390. unsigned long pfn;
  391. /* pfn is the end pfn of a memory section. */
  392. pfn = end_pfn - 1;
  393. for (; pfn >= start_pfn; pfn -= PAGES_PER_SUBSECTION) {
  394. if (unlikely(!pfn_to_online_page(pfn)))
  395. continue;
  396. if (unlikely(pfn_to_nid(pfn) != nid))
  397. continue;
  398. if (zone != page_zone(pfn_to_page(pfn)))
  399. continue;
  400. return pfn;
  401. }
  402. return 0;
  403. }
  404. static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
  405. unsigned long end_pfn)
  406. {
  407. unsigned long pfn;
  408. int nid = zone_to_nid(zone);
  409. if (zone->zone_start_pfn == start_pfn) {
  410. /*
  411. * If the section is smallest section in the zone, it need
  412. * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
  413. * In this case, we find second smallest valid mem_section
  414. * for shrinking zone.
  415. */
  416. pfn = find_smallest_section_pfn(nid, zone, end_pfn,
  417. zone_end_pfn(zone));
  418. if (pfn) {
  419. zone->spanned_pages = zone_end_pfn(zone) - pfn;
  420. zone->zone_start_pfn = pfn;
  421. } else {
  422. zone->zone_start_pfn = 0;
  423. zone->spanned_pages = 0;
  424. }
  425. } else if (zone_end_pfn(zone) == end_pfn) {
  426. /*
  427. * If the section is biggest section in the zone, it need
  428. * shrink zone->spanned_pages.
  429. * In this case, we find second biggest valid mem_section for
  430. * shrinking zone.
  431. */
  432. pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn,
  433. start_pfn);
  434. if (pfn)
  435. zone->spanned_pages = pfn - zone->zone_start_pfn + 1;
  436. else {
  437. zone->zone_start_pfn = 0;
  438. zone->spanned_pages = 0;
  439. }
  440. }
  441. }
  442. static void update_pgdat_span(struct pglist_data *pgdat)
  443. {
  444. unsigned long node_start_pfn = 0, node_end_pfn = 0;
  445. struct zone *zone;
  446. for (zone = pgdat->node_zones;
  447. zone < pgdat->node_zones + MAX_NR_ZONES; zone++) {
  448. unsigned long end_pfn = zone_end_pfn(zone);
  449. /* No need to lock the zones, they can't change. */
  450. if (!zone->spanned_pages)
  451. continue;
  452. if (!node_end_pfn) {
  453. node_start_pfn = zone->zone_start_pfn;
  454. node_end_pfn = end_pfn;
  455. continue;
  456. }
  457. if (end_pfn > node_end_pfn)
  458. node_end_pfn = end_pfn;
  459. if (zone->zone_start_pfn < node_start_pfn)
  460. node_start_pfn = zone->zone_start_pfn;
  461. }
  462. pgdat->node_start_pfn = node_start_pfn;
  463. pgdat->node_spanned_pages = node_end_pfn - node_start_pfn;
  464. }
  465. void remove_pfn_range_from_zone(struct zone *zone,
  466. unsigned long start_pfn,
  467. unsigned long nr_pages)
  468. {
  469. const unsigned long end_pfn = start_pfn + nr_pages;
  470. struct pglist_data *pgdat = zone->zone_pgdat;
  471. unsigned long pfn, cur_nr_pages;
  472. /* Poison struct pages because they are now uninitialized again. */
  473. for (pfn = start_pfn; pfn < end_pfn; pfn += cur_nr_pages) {
  474. cond_resched();
  475. /* Select all remaining pages up to the next section boundary */
  476. cur_nr_pages =
  477. min(end_pfn - pfn, SECTION_ALIGN_UP(pfn + 1) - pfn);
  478. page_init_poison(pfn_to_page(pfn),
  479. sizeof(struct page) * cur_nr_pages);
  480. }
  481. /*
  482. * Zone shrinking code cannot properly deal with ZONE_DEVICE. So
  483. * we will not try to shrink the zones - which is okay as
  484. * set_zone_contiguous() cannot deal with ZONE_DEVICE either way.
  485. */
  486. if (zone_is_zone_device(zone))
  487. return;
  488. clear_zone_contiguous(zone);
  489. shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
  490. update_pgdat_span(pgdat);
  491. set_zone_contiguous(zone);
  492. }
  493. /**
  494. * __remove_pages() - remove sections of pages
  495. * @pfn: starting pageframe (must be aligned to start of a section)
  496. * @nr_pages: number of pages to remove (must be multiple of section size)
  497. * @altmap: alternative device page map or %NULL if default memmap is used
  498. *
  499. * Generic helper function to remove section mappings and sysfs entries
  500. * for the section of the memory we are removing. Caller needs to make
  501. * sure that pages are marked reserved and zones are adjust properly by
  502. * calling offline_pages().
  503. */
  504. void __remove_pages(unsigned long pfn, unsigned long nr_pages,
  505. struct vmem_altmap *altmap)
  506. {
  507. const unsigned long end_pfn = pfn + nr_pages;
  508. unsigned long cur_nr_pages;
  509. if (check_pfn_span(pfn, nr_pages)) {
  510. WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
  511. return;
  512. }
  513. for (; pfn < end_pfn; pfn += cur_nr_pages) {
  514. cond_resched();
  515. /* Select all remaining pages up to the next section boundary */
  516. cur_nr_pages = min(end_pfn - pfn,
  517. SECTION_ALIGN_UP(pfn + 1) - pfn);
  518. sparse_remove_section(pfn, cur_nr_pages, altmap);
  519. }
  520. }
  521. int set_online_page_callback(online_page_callback_t callback)
  522. {
  523. int rc = -EINVAL;
  524. get_online_mems();
  525. mutex_lock(&online_page_callback_lock);
  526. if (online_page_callback == generic_online_page) {
  527. online_page_callback = callback;
  528. rc = 0;
  529. }
  530. mutex_unlock(&online_page_callback_lock);
  531. put_online_mems();
  532. return rc;
  533. }
  534. EXPORT_SYMBOL_GPL(set_online_page_callback);
  535. int restore_online_page_callback(online_page_callback_t callback)
  536. {
  537. int rc = -EINVAL;
  538. get_online_mems();
  539. mutex_lock(&online_page_callback_lock);
  540. if (online_page_callback == callback) {
  541. online_page_callback = generic_online_page;
  542. rc = 0;
  543. }
  544. mutex_unlock(&online_page_callback_lock);
  545. put_online_mems();
  546. return rc;
  547. }
  548. EXPORT_SYMBOL_GPL(restore_online_page_callback);
  549. /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
  550. void generic_online_page(struct page *page, unsigned int order)
  551. {
  552. __free_pages_core(page, order, MEMINIT_HOTPLUG);
  553. }
  554. EXPORT_SYMBOL_GPL(generic_online_page);
  555. static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
  556. {
  557. const unsigned long end_pfn = start_pfn + nr_pages;
  558. unsigned long pfn;
  559. /*
  560. * Online the pages in MAX_PAGE_ORDER aligned chunks. The callback might
  561. * decide to not expose all pages to the buddy (e.g., expose them
  562. * later). We account all pages as being online and belonging to this
  563. * zone ("present").
  564. * When using memmap_on_memory, the range might not be aligned to
  565. * MAX_ORDER_NR_PAGES - 1, but pageblock aligned. __ffs() will detect
  566. * this and the first chunk to online will be pageblock_nr_pages.
  567. */
  568. for (pfn = start_pfn; pfn < end_pfn;) {
  569. struct page *page = pfn_to_page(pfn);
  570. int order;
  571. /*
  572. * Free to online pages in the largest chunks alignment allows.
  573. *
  574. * __ffs() behaviour is undefined for 0. start == 0 is
  575. * MAX_PAGE_ORDER-aligned, Set order to MAX_PAGE_ORDER for
  576. * the case.
  577. */
  578. if (pfn)
  579. order = min_t(int, MAX_PAGE_ORDER, __ffs(pfn));
  580. else
  581. order = MAX_PAGE_ORDER;
  582. /*
  583. * Exposing the page to the buddy by freeing can cause
  584. * issues with debug_pagealloc enabled: some archs don't
  585. * like double-unmappings. So treat them like any pages that
  586. * were allocated from the buddy.
  587. */
  588. debug_pagealloc_map_pages(page, 1 << order);
  589. (*online_page_callback)(page, order);
  590. pfn += (1UL << order);
  591. }
  592. /* mark all involved sections as online */
  593. online_mem_sections(start_pfn, end_pfn);
  594. }
  595. static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
  596. unsigned long nr_pages)
  597. {
  598. unsigned long old_end_pfn = zone_end_pfn(zone);
  599. if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
  600. zone->zone_start_pfn = start_pfn;
  601. zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
  602. }
  603. static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
  604. unsigned long nr_pages)
  605. {
  606. unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
  607. if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
  608. pgdat->node_start_pfn = start_pfn;
  609. pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
  610. }
  611. #ifdef CONFIG_ZONE_DEVICE
  612. static void section_taint_zone_device(unsigned long pfn)
  613. {
  614. struct mem_section *ms = __pfn_to_section(pfn);
  615. ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
  616. }
  617. #else
  618. static inline void section_taint_zone_device(unsigned long pfn)
  619. {
  620. }
  621. #endif
  622. /*
  623. * Associate the pfn range with the given zone, initializing the memmaps
  624. * and resizing the pgdat/zone data to span the added pages. After this
  625. * call, all affected pages are PageOffline().
  626. *
  627. * All aligned pageblocks are initialized to the specified migratetype
  628. * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
  629. * zone stats (e.g., nr_isolate_pageblock) are touched.
  630. */
  631. void move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
  632. unsigned long nr_pages,
  633. struct vmem_altmap *altmap, int migratetype,
  634. bool isolate_pageblock)
  635. {
  636. struct pglist_data *pgdat = zone->zone_pgdat;
  637. int nid = pgdat->node_id;
  638. clear_zone_contiguous(zone);
  639. if (zone_is_empty(zone))
  640. init_currently_empty_zone(zone, start_pfn, nr_pages);
  641. resize_zone_range(zone, start_pfn, nr_pages);
  642. resize_pgdat_range(pgdat, start_pfn, nr_pages);
  643. /*
  644. * Subsection population requires care in pfn_to_online_page().
  645. * Set the taint to enable the slow path detection of
  646. * ZONE_DEVICE pages in an otherwise ZONE_{NORMAL,MOVABLE}
  647. * section.
  648. */
  649. if (zone_is_zone_device(zone)) {
  650. if (!IS_ALIGNED(start_pfn, PAGES_PER_SECTION))
  651. section_taint_zone_device(start_pfn);
  652. if (!IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION))
  653. section_taint_zone_device(start_pfn + nr_pages);
  654. }
  655. /*
  656. * TODO now we have a visible range of pages which are not associated
  657. * with their zone properly. Not nice but set_pfnblock_migratetype()
  658. * expects the zone spans the pfn range. All the pages in the range
  659. * are reserved so nobody should be touching them so we should be safe
  660. */
  661. memmap_init_range(nr_pages, nid, zone_idx(zone), start_pfn, 0,
  662. MEMINIT_HOTPLUG, altmap, migratetype,
  663. isolate_pageblock);
  664. set_zone_contiguous(zone);
  665. }
  666. struct auto_movable_stats {
  667. unsigned long kernel_early_pages;
  668. unsigned long movable_pages;
  669. };
  670. static void auto_movable_stats_account_zone(struct auto_movable_stats *stats,
  671. struct zone *zone)
  672. {
  673. if (zone_idx(zone) == ZONE_MOVABLE) {
  674. stats->movable_pages += zone->present_pages;
  675. } else {
  676. stats->kernel_early_pages += zone->present_early_pages;
  677. #ifdef CONFIG_CMA
  678. /*
  679. * CMA pages (never on hotplugged memory) behave like
  680. * ZONE_MOVABLE.
  681. */
  682. stats->movable_pages += zone->cma_pages;
  683. stats->kernel_early_pages -= zone->cma_pages;
  684. #endif /* CONFIG_CMA */
  685. }
  686. }
  687. struct auto_movable_group_stats {
  688. unsigned long movable_pages;
  689. unsigned long req_kernel_early_pages;
  690. };
  691. static int auto_movable_stats_account_group(struct memory_group *group,
  692. void *arg)
  693. {
  694. const int ratio = READ_ONCE(auto_movable_ratio);
  695. struct auto_movable_group_stats *stats = arg;
  696. long pages;
  697. /*
  698. * We don't support modifying the config while the auto-movable online
  699. * policy is already enabled. Just avoid the division by zero below.
  700. */
  701. if (!ratio)
  702. return 0;
  703. /*
  704. * Calculate how many early kernel pages this group requires to
  705. * satisfy the configured zone ratio.
  706. */
  707. pages = group->present_movable_pages * 100 / ratio;
  708. pages -= group->present_kernel_pages;
  709. if (pages > 0)
  710. stats->req_kernel_early_pages += pages;
  711. stats->movable_pages += group->present_movable_pages;
  712. return 0;
  713. }
  714. static bool auto_movable_can_online_movable(int nid, struct memory_group *group,
  715. unsigned long nr_pages)
  716. {
  717. unsigned long kernel_early_pages, movable_pages;
  718. struct auto_movable_group_stats group_stats = {};
  719. struct auto_movable_stats stats = {};
  720. struct zone *zone;
  721. int i;
  722. /* Walk all relevant zones and collect MOVABLE vs. KERNEL stats. */
  723. if (nid == NUMA_NO_NODE) {
  724. /* TODO: cache values */
  725. for_each_populated_zone(zone)
  726. auto_movable_stats_account_zone(&stats, zone);
  727. } else {
  728. for (i = 0; i < MAX_NR_ZONES; i++) {
  729. pg_data_t *pgdat = NODE_DATA(nid);
  730. zone = pgdat->node_zones + i;
  731. if (populated_zone(zone))
  732. auto_movable_stats_account_zone(&stats, zone);
  733. }
  734. }
  735. kernel_early_pages = stats.kernel_early_pages;
  736. movable_pages = stats.movable_pages;
  737. /*
  738. * Kernel memory inside dynamic memory group allows for more MOVABLE
  739. * memory within the same group. Remove the effect of all but the
  740. * current group from the stats.
  741. */
  742. walk_dynamic_memory_groups(nid, auto_movable_stats_account_group,
  743. group, &group_stats);
  744. if (kernel_early_pages <= group_stats.req_kernel_early_pages)
  745. return false;
  746. kernel_early_pages -= group_stats.req_kernel_early_pages;
  747. movable_pages -= group_stats.movable_pages;
  748. if (group && group->is_dynamic)
  749. kernel_early_pages += group->present_kernel_pages;
  750. /*
  751. * Test if we could online the given number of pages to ZONE_MOVABLE
  752. * and still stay in the configured ratio.
  753. */
  754. movable_pages += nr_pages;
  755. return movable_pages <= (auto_movable_ratio * kernel_early_pages) / 100;
  756. }
  757. /*
  758. * Returns a default kernel memory zone for the given pfn range.
  759. * If no kernel zone covers this pfn range it will automatically go
  760. * to the ZONE_NORMAL.
  761. */
  762. static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
  763. unsigned long nr_pages)
  764. {
  765. struct pglist_data *pgdat = NODE_DATA(nid);
  766. int zid;
  767. for (zid = 0; zid < ZONE_NORMAL; zid++) {
  768. struct zone *zone = &pgdat->node_zones[zid];
  769. if (zone_intersects(zone, start_pfn, nr_pages))
  770. return zone;
  771. }
  772. return &pgdat->node_zones[ZONE_NORMAL];
  773. }
  774. /*
  775. * Determine to which zone to online memory dynamically based on user
  776. * configuration and system stats. We care about the following ratio:
  777. *
  778. * MOVABLE : KERNEL
  779. *
  780. * Whereby MOVABLE is memory in ZONE_MOVABLE and KERNEL is memory in
  781. * one of the kernel zones. CMA pages inside one of the kernel zones really
  782. * behaves like ZONE_MOVABLE, so we treat them accordingly.
  783. *
  784. * We don't allow for hotplugged memory in a KERNEL zone to increase the
  785. * amount of MOVABLE memory we can have, so we end up with:
  786. *
  787. * MOVABLE : KERNEL_EARLY
  788. *
  789. * Whereby KERNEL_EARLY is memory in one of the kernel zones, available since
  790. * boot. We base our calculation on KERNEL_EARLY internally, because:
  791. *
  792. * a) Hotplugged memory in one of the kernel zones can sometimes still get
  793. * hotunplugged, especially when hot(un)plugging individual memory blocks.
  794. * There is no coordination across memory devices, therefore "automatic"
  795. * hotunplugging, as implemented in hypervisors, could result in zone
  796. * imbalances.
  797. * b) Early/boot memory in one of the kernel zones can usually not get
  798. * hotunplugged again (e.g., no firmware interface to unplug, fragmented
  799. * with unmovable allocations). While there are corner cases where it might
  800. * still work, it is barely relevant in practice.
  801. *
  802. * Exceptions are dynamic memory groups, which allow for more MOVABLE
  803. * memory within the same memory group -- because in that case, there is
  804. * coordination within the single memory device managed by a single driver.
  805. *
  806. * We rely on "present pages" instead of "managed pages", as the latter is
  807. * highly unreliable and dynamic in virtualized environments, and does not
  808. * consider boot time allocations. For example, memory ballooning adjusts the
  809. * managed pages when inflating/deflating the balloon, and balloon page
  810. * migration can even migrate inflated pages between zones.
  811. *
  812. * Using "present pages" is better but some things to keep in mind are:
  813. *
  814. * a) Some memblock allocations, such as for the crashkernel area, are
  815. * effectively unused by the kernel, yet they account to "present pages".
  816. * Fortunately, these allocations are comparatively small in relevant setups
  817. * (e.g., fraction of system memory).
  818. * b) Some hotplugged memory blocks in virtualized environments, especially
  819. * hotplugged by virtio-mem, look like they are completely present, however,
  820. * only parts of the memory block are actually currently usable.
  821. * "present pages" is an upper limit that can get reached at runtime. As
  822. * we base our calculations on KERNEL_EARLY, this is not an issue.
  823. */
  824. static struct zone *auto_movable_zone_for_pfn(int nid,
  825. struct memory_group *group,
  826. unsigned long pfn,
  827. unsigned long nr_pages)
  828. {
  829. unsigned long online_pages = 0, max_pages, end_pfn;
  830. struct page *page;
  831. if (!auto_movable_ratio)
  832. goto kernel_zone;
  833. if (group && !group->is_dynamic) {
  834. max_pages = group->s.max_pages;
  835. online_pages = group->present_movable_pages;
  836. /* If anything is !MOVABLE online the rest !MOVABLE. */
  837. if (group->present_kernel_pages)
  838. goto kernel_zone;
  839. } else if (!group || group->d.unit_pages == nr_pages) {
  840. max_pages = nr_pages;
  841. } else {
  842. max_pages = group->d.unit_pages;
  843. /*
  844. * Take a look at all online sections in the current unit.
  845. * We can safely assume that all pages within a section belong
  846. * to the same zone, because dynamic memory groups only deal
  847. * with hotplugged memory.
  848. */
  849. pfn = ALIGN_DOWN(pfn, group->d.unit_pages);
  850. end_pfn = pfn + group->d.unit_pages;
  851. for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
  852. page = pfn_to_online_page(pfn);
  853. if (!page)
  854. continue;
  855. /* If anything is !MOVABLE online the rest !MOVABLE. */
  856. if (!is_zone_movable_page(page))
  857. goto kernel_zone;
  858. online_pages += PAGES_PER_SECTION;
  859. }
  860. }
  861. /*
  862. * Online MOVABLE if we could *currently* online all remaining parts
  863. * MOVABLE. We expect to (add+) online them immediately next, so if
  864. * nobody interferes, all will be MOVABLE if possible.
  865. */
  866. nr_pages = max_pages - online_pages;
  867. if (!auto_movable_can_online_movable(NUMA_NO_NODE, group, nr_pages))
  868. goto kernel_zone;
  869. #ifdef CONFIG_NUMA
  870. if (auto_movable_numa_aware &&
  871. !auto_movable_can_online_movable(nid, group, nr_pages))
  872. goto kernel_zone;
  873. #endif /* CONFIG_NUMA */
  874. return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
  875. kernel_zone:
  876. return default_kernel_zone_for_pfn(nid, pfn, nr_pages);
  877. }
  878. static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
  879. unsigned long nr_pages)
  880. {
  881. struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
  882. nr_pages);
  883. struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
  884. bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
  885. bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
  886. /*
  887. * We inherit the existing zone in a simple case where zones do not
  888. * overlap in the given range
  889. */
  890. if (in_kernel ^ in_movable)
  891. return (in_kernel) ? kernel_zone : movable_zone;
  892. /*
  893. * If the range doesn't belong to any zone or two zones overlap in the
  894. * given range then we use movable zone only if movable_node is
  895. * enabled because we always online to a kernel zone by default.
  896. */
  897. return movable_node_enabled ? movable_zone : kernel_zone;
  898. }
  899. struct zone *zone_for_pfn_range(int online_type, int nid,
  900. struct memory_group *group, unsigned long start_pfn,
  901. unsigned long nr_pages)
  902. {
  903. if (online_type == MMOP_ONLINE_KERNEL)
  904. return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
  905. if (online_type == MMOP_ONLINE_MOVABLE)
  906. return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
  907. if (online_policy == ONLINE_POLICY_AUTO_MOVABLE)
  908. return auto_movable_zone_for_pfn(nid, group, start_pfn, nr_pages);
  909. return default_zone_for_pfn(nid, start_pfn, nr_pages);
  910. }
  911. /*
  912. * This function should only be called by memory_block_{online,offline},
  913. * and {online,offline}_pages.
  914. */
  915. void adjust_present_page_count(struct page *page, struct memory_group *group,
  916. long nr_pages)
  917. {
  918. struct zone *zone = page_zone(page);
  919. const bool movable = zone_idx(zone) == ZONE_MOVABLE;
  920. /*
  921. * We only support onlining/offlining/adding/removing of complete
  922. * memory blocks; therefore, either all is either early or hotplugged.
  923. */
  924. if (early_section(__pfn_to_section(page_to_pfn(page))))
  925. zone->present_early_pages += nr_pages;
  926. zone->present_pages += nr_pages;
  927. zone->zone_pgdat->node_present_pages += nr_pages;
  928. if (group && movable)
  929. group->present_movable_pages += nr_pages;
  930. else if (group && !movable)
  931. group->present_kernel_pages += nr_pages;
  932. }
  933. int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,
  934. struct zone *zone)
  935. {
  936. unsigned long end_pfn = pfn + nr_pages;
  937. int ret, i;
  938. ret = kasan_add_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
  939. if (ret)
  940. return ret;
  941. move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_UNMOVABLE,
  942. false);
  943. for (i = 0; i < nr_pages; i++) {
  944. struct page *page = pfn_to_page(pfn + i);
  945. __ClearPageOffline(page);
  946. SetPageVmemmapSelfHosted(page);
  947. }
  948. /*
  949. * It might be that the vmemmap_pages fully span sections. If that is
  950. * the case, mark those sections online here as otherwise they will be
  951. * left offline.
  952. */
  953. if (nr_pages >= PAGES_PER_SECTION)
  954. online_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
  955. return ret;
  956. }
  957. void mhp_deinit_memmap_on_memory(unsigned long pfn, unsigned long nr_pages)
  958. {
  959. unsigned long end_pfn = pfn + nr_pages;
  960. /*
  961. * It might be that the vmemmap_pages fully span sections. If that is
  962. * the case, mark those sections offline here as otherwise they will be
  963. * left online.
  964. */
  965. if (nr_pages >= PAGES_PER_SECTION)
  966. offline_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
  967. /*
  968. * The pages associated with this vmemmap have been offlined, so
  969. * we can reset its state here.
  970. */
  971. remove_pfn_range_from_zone(page_zone(pfn_to_page(pfn)), pfn, nr_pages);
  972. kasan_remove_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
  973. }
  974. /*
  975. * Must be called with mem_hotplug_lock in write mode.
  976. */
  977. int online_pages(unsigned long pfn, unsigned long nr_pages,
  978. struct zone *zone, struct memory_group *group)
  979. {
  980. struct memory_notify mem_arg = {
  981. .start_pfn = pfn,
  982. .nr_pages = nr_pages,
  983. };
  984. struct node_notify node_arg = {
  985. .nid = NUMA_NO_NODE,
  986. };
  987. const int nid = zone_to_nid(zone);
  988. int need_zonelists_rebuild = 0;
  989. unsigned long flags;
  990. int ret;
  991. /*
  992. * {on,off}lining is constrained to full memory sections (or more
  993. * precisely to memory blocks from the user space POV).
  994. * memmap_on_memory is an exception because it reserves initial part
  995. * of the physical memory space for vmemmaps. That space is pageblock
  996. * aligned.
  997. */
  998. if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(pfn) ||
  999. !IS_ALIGNED(pfn + nr_pages, PAGES_PER_SECTION)))
  1000. return -EINVAL;
  1001. /* associate pfn range with the zone */
  1002. move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_MOVABLE,
  1003. true);
  1004. if (!node_state(nid, N_MEMORY)) {
  1005. /* Adding memory to the node for the first time */
  1006. node_arg.nid = nid;
  1007. ret = node_notify(NODE_ADDING_FIRST_MEMORY, &node_arg);
  1008. ret = notifier_to_errno(ret);
  1009. if (ret)
  1010. goto failed_addition;
  1011. }
  1012. ret = memory_notify(MEM_GOING_ONLINE, &mem_arg);
  1013. ret = notifier_to_errno(ret);
  1014. if (ret)
  1015. goto failed_addition;
  1016. /*
  1017. * Fixup the number of isolated pageblocks before marking the sections
  1018. * onlining, such that undo_isolate_page_range() works correctly.
  1019. */
  1020. spin_lock_irqsave(&zone->lock, flags);
  1021. zone->nr_isolate_pageblock += nr_pages / pageblock_nr_pages;
  1022. spin_unlock_irqrestore(&zone->lock, flags);
  1023. /*
  1024. * If this zone is not populated, then it is not in zonelist.
  1025. * This means the page allocator ignores this zone.
  1026. * So, zonelist must be updated after online.
  1027. */
  1028. if (!populated_zone(zone)) {
  1029. need_zonelists_rebuild = 1;
  1030. setup_zone_pageset(zone);
  1031. }
  1032. online_pages_range(pfn, nr_pages);
  1033. adjust_present_page_count(pfn_to_page(pfn), group, nr_pages);
  1034. if (node_arg.nid >= 0)
  1035. node_set_state(nid, N_MEMORY);
  1036. /*
  1037. * Check whether we are adding normal memory to the node for the first
  1038. * time.
  1039. */
  1040. if (!node_state(nid, N_NORMAL_MEMORY) && zone_idx(zone) <= ZONE_NORMAL)
  1041. node_set_state(nid, N_NORMAL_MEMORY);
  1042. if (need_zonelists_rebuild)
  1043. build_all_zonelists(NULL);
  1044. /* Basic onlining is complete, allow allocation of onlined pages. */
  1045. undo_isolate_page_range(pfn, pfn + nr_pages);
  1046. /*
  1047. * Freshly onlined pages aren't shuffled (e.g., all pages are placed to
  1048. * the tail of the freelist when undoing isolation). Shuffle the whole
  1049. * zone to make sure the just onlined pages are properly distributed
  1050. * across the whole freelist - to create an initial shuffle.
  1051. */
  1052. shuffle_zone(zone);
  1053. /* reinitialise watermarks and update pcp limits */
  1054. init_per_zone_wmark_min();
  1055. kswapd_run(nid);
  1056. kcompactd_run(nid);
  1057. if (node_arg.nid >= 0)
  1058. /* First memory added successfully. Notify consumers. */
  1059. node_notify(NODE_ADDED_FIRST_MEMORY, &node_arg);
  1060. writeback_set_ratelimit();
  1061. memory_notify(MEM_ONLINE, &mem_arg);
  1062. return 0;
  1063. failed_addition:
  1064. pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
  1065. (unsigned long long) pfn << PAGE_SHIFT,
  1066. (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
  1067. memory_notify(MEM_CANCEL_ONLINE, &mem_arg);
  1068. if (node_arg.nid != NUMA_NO_NODE)
  1069. node_notify(NODE_CANCEL_ADDING_FIRST_MEMORY, &node_arg);
  1070. remove_pfn_range_from_zone(zone, pfn, nr_pages);
  1071. return ret;
  1072. }
  1073. /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
  1074. static pg_data_t *hotadd_init_pgdat(int nid)
  1075. {
  1076. struct pglist_data *pgdat;
  1077. /*
  1078. * NODE_DATA is preallocated (free_area_init) but its internal
  1079. * state is not allocated completely. Add missing pieces.
  1080. * Completely offline nodes stay around and they just need
  1081. * reinitialization.
  1082. */
  1083. pgdat = NODE_DATA(nid);
  1084. /* init node's zones as empty zones, we don't have any present pages.*/
  1085. free_area_init_core_hotplug(pgdat);
  1086. /*
  1087. * The node we allocated has no zone fallback lists. For avoiding
  1088. * to access not-initialized zonelist, build here.
  1089. */
  1090. build_all_zonelists(pgdat);
  1091. return pgdat;
  1092. }
  1093. /*
  1094. * __try_online_node - online a node if offlined
  1095. * @nid: the node ID
  1096. * @set_node_online: Whether we want to online the node
  1097. * called by cpu_up() to online a node without onlined memory.
  1098. *
  1099. * Returns:
  1100. * 1 -> a new node has been allocated
  1101. * 0 -> the node is already online
  1102. * -ENOMEM -> the node could not be allocated
  1103. */
  1104. static int __try_online_node(int nid, bool set_node_online)
  1105. {
  1106. pg_data_t *pgdat;
  1107. int ret = 1;
  1108. if (node_online(nid))
  1109. return 0;
  1110. pgdat = hotadd_init_pgdat(nid);
  1111. if (!pgdat) {
  1112. pr_err("Cannot online node %d due to NULL pgdat\n", nid);
  1113. ret = -ENOMEM;
  1114. goto out;
  1115. }
  1116. if (set_node_online) {
  1117. node_set_online(nid);
  1118. ret = register_node(nid);
  1119. BUG_ON(ret);
  1120. }
  1121. out:
  1122. return ret;
  1123. }
  1124. /*
  1125. * Users of this function always want to online/register the node
  1126. */
  1127. int try_online_node(int nid)
  1128. {
  1129. int ret;
  1130. mem_hotplug_begin();
  1131. ret = __try_online_node(nid, true);
  1132. mem_hotplug_done();
  1133. return ret;
  1134. }
  1135. static int check_hotplug_memory_range(u64 start, u64 size)
  1136. {
  1137. /* memory range must be block size aligned */
  1138. if (!size || !IS_ALIGNED(start, memory_block_size_bytes()) ||
  1139. !IS_ALIGNED(size, memory_block_size_bytes())) {
  1140. pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
  1141. memory_block_size_bytes(), start, size);
  1142. return -EINVAL;
  1143. }
  1144. return 0;
  1145. }
  1146. static int online_memory_block(struct memory_block *mem, void *arg)
  1147. {
  1148. mem->online_type = mhp_get_default_online_type();
  1149. return device_online(&mem->dev);
  1150. }
  1151. #ifndef arch_supports_memmap_on_memory
  1152. static inline bool arch_supports_memmap_on_memory(unsigned long vmemmap_size)
  1153. {
  1154. /*
  1155. * As default, we want the vmemmap to span a complete PMD such that we
  1156. * can map the vmemmap using a single PMD if supported by the
  1157. * architecture.
  1158. */
  1159. return IS_ALIGNED(vmemmap_size, PMD_SIZE);
  1160. }
  1161. #endif
  1162. bool mhp_supports_memmap_on_memory(void)
  1163. {
  1164. unsigned long vmemmap_size = memory_block_memmap_size();
  1165. unsigned long memmap_pages = memory_block_memmap_on_memory_pages();
  1166. /*
  1167. * Besides having arch support and the feature enabled at runtime, we
  1168. * need a few more assumptions to hold true:
  1169. *
  1170. * a) The vmemmap pages span complete PMDs: We don't want vmemmap code
  1171. * to populate memory from the altmap for unrelated parts (i.e.,
  1172. * other memory blocks)
  1173. *
  1174. * b) The vmemmap pages (and thereby the pages that will be exposed to
  1175. * the buddy) have to cover full pageblocks: memory onlining/offlining
  1176. * code requires applicable ranges to be page-aligned, for example, to
  1177. * set the migratetypes properly.
  1178. *
  1179. * TODO: Although we have a check here to make sure that vmemmap pages
  1180. * fully populate a PMD, it is not the right place to check for
  1181. * this. A much better solution involves improving vmemmap code
  1182. * to fallback to base pages when trying to populate vmemmap using
  1183. * altmap as an alternative source of memory, and we do not exactly
  1184. * populate a single PMD.
  1185. */
  1186. if (!mhp_memmap_on_memory())
  1187. return false;
  1188. /*
  1189. * Make sure the vmemmap allocation is fully contained
  1190. * so that we always allocate vmemmap memory from altmap area.
  1191. */
  1192. if (!IS_ALIGNED(vmemmap_size, PAGE_SIZE))
  1193. return false;
  1194. /*
  1195. * start pfn should be pageblock_nr_pages aligned for correctly
  1196. * setting migrate types
  1197. */
  1198. if (!pageblock_aligned(memmap_pages))
  1199. return false;
  1200. if (memmap_pages == PHYS_PFN(memory_block_size_bytes()))
  1201. /* No effective hotplugged memory doesn't make sense. */
  1202. return false;
  1203. return arch_supports_memmap_on_memory(vmemmap_size);
  1204. }
  1205. EXPORT_SYMBOL_GPL(mhp_supports_memmap_on_memory);
  1206. static void remove_memory_blocks_and_altmaps(u64 start, u64 size)
  1207. {
  1208. unsigned long memblock_size = memory_block_size_bytes();
  1209. u64 cur_start;
  1210. /*
  1211. * For memmap_on_memory, the altmaps were added on a per-memblock
  1212. * basis; we have to process each individual memory block.
  1213. */
  1214. for (cur_start = start; cur_start < start + size;
  1215. cur_start += memblock_size) {
  1216. struct vmem_altmap *altmap = NULL;
  1217. struct memory_block *mem;
  1218. mem = find_memory_block(pfn_to_section_nr(PFN_DOWN(cur_start)));
  1219. if (WARN_ON_ONCE(!mem))
  1220. continue;
  1221. altmap = mem->altmap;
  1222. mem->altmap = NULL;
  1223. remove_memory_block_devices(cur_start, memblock_size);
  1224. arch_remove_memory(cur_start, memblock_size, altmap);
  1225. /* Verify that all vmemmap pages have actually been freed. */
  1226. WARN(altmap->alloc, "Altmap not fully unmapped");
  1227. kfree(altmap);
  1228. }
  1229. }
  1230. static int create_altmaps_and_memory_blocks(int nid, struct memory_group *group,
  1231. u64 start, u64 size)
  1232. {
  1233. unsigned long memblock_size = memory_block_size_bytes();
  1234. u64 cur_start;
  1235. int ret;
  1236. for (cur_start = start; cur_start < start + size;
  1237. cur_start += memblock_size) {
  1238. struct mhp_params params = { .pgprot =
  1239. pgprot_mhp(PAGE_KERNEL) };
  1240. struct vmem_altmap mhp_altmap = {
  1241. .base_pfn = PHYS_PFN(cur_start),
  1242. .end_pfn = PHYS_PFN(cur_start + memblock_size - 1),
  1243. };
  1244. mhp_altmap.free = memory_block_memmap_on_memory_pages();
  1245. params.altmap = kmemdup(&mhp_altmap, sizeof(struct vmem_altmap),
  1246. GFP_KERNEL);
  1247. if (!params.altmap) {
  1248. ret = -ENOMEM;
  1249. goto out;
  1250. }
  1251. /* call arch's memory hotadd */
  1252. ret = arch_add_memory(nid, cur_start, memblock_size, &params);
  1253. if (ret < 0) {
  1254. kfree(params.altmap);
  1255. goto out;
  1256. }
  1257. /* create memory block devices after memory was added */
  1258. ret = create_memory_block_devices(cur_start, memblock_size, nid,
  1259. params.altmap, group);
  1260. if (ret) {
  1261. arch_remove_memory(cur_start, memblock_size, NULL);
  1262. kfree(params.altmap);
  1263. goto out;
  1264. }
  1265. }
  1266. return 0;
  1267. out:
  1268. if (ret && cur_start != start)
  1269. remove_memory_blocks_and_altmaps(start, cur_start - start);
  1270. return ret;
  1271. }
  1272. /*
  1273. * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
  1274. * and online/offline operations (triggered e.g. by sysfs).
  1275. *
  1276. * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
  1277. */
  1278. int add_memory_resource(int nid, struct resource *res, mhp_t mhp_flags)
  1279. {
  1280. struct mhp_params params = { .pgprot = pgprot_mhp(PAGE_KERNEL) };
  1281. enum memblock_flags memblock_flags = MEMBLOCK_NONE;
  1282. struct memory_group *group = NULL;
  1283. u64 start, size;
  1284. bool new_node = false;
  1285. int ret;
  1286. start = res->start;
  1287. size = resource_size(res);
  1288. ret = check_hotplug_memory_range(start, size);
  1289. if (ret)
  1290. return ret;
  1291. if (mhp_flags & MHP_NID_IS_MGID) {
  1292. group = memory_group_find_by_id(nid);
  1293. if (!group)
  1294. return -EINVAL;
  1295. nid = group->nid;
  1296. }
  1297. if (!node_possible(nid)) {
  1298. WARN(1, "node %d was absent from the node_possible_map\n", nid);
  1299. return -EINVAL;
  1300. }
  1301. mem_hotplug_begin();
  1302. if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
  1303. if (res->flags & IORESOURCE_SYSRAM_DRIVER_MANAGED)
  1304. memblock_flags = MEMBLOCK_DRIVER_MANAGED;
  1305. ret = memblock_add_node(start, size, nid, memblock_flags);
  1306. if (ret)
  1307. goto error_mem_hotplug_end;
  1308. }
  1309. ret = __try_online_node(nid, false);
  1310. if (ret < 0)
  1311. goto error_memblock_remove;
  1312. if (ret) {
  1313. node_set_online(nid);
  1314. ret = register_node(nid);
  1315. if (WARN_ON(ret)) {
  1316. node_set_offline(nid);
  1317. goto error_memblock_remove;
  1318. }
  1319. new_node = true;
  1320. }
  1321. /*
  1322. * Self hosted memmap array
  1323. */
  1324. if ((mhp_flags & MHP_MEMMAP_ON_MEMORY) &&
  1325. mhp_supports_memmap_on_memory()) {
  1326. ret = create_altmaps_and_memory_blocks(nid, group, start, size);
  1327. if (ret)
  1328. goto error;
  1329. } else {
  1330. ret = arch_add_memory(nid, start, size, &params);
  1331. if (ret < 0)
  1332. goto error;
  1333. /* create memory block devices after memory was added */
  1334. ret = create_memory_block_devices(start, size, nid, NULL, group);
  1335. if (ret) {
  1336. arch_remove_memory(start, size, params.altmap);
  1337. goto error;
  1338. }
  1339. }
  1340. register_memory_blocks_under_node_hotplug(nid, PFN_DOWN(start),
  1341. PFN_UP(start + size - 1));
  1342. /* create new memmap entry */
  1343. if (!strcmp(res->name, "System RAM"))
  1344. firmware_map_add_hotplug(start, start + size, "System RAM");
  1345. /* device_online() will take the lock when calling online_pages() */
  1346. mem_hotplug_done();
  1347. /*
  1348. * In case we're allowed to merge the resource, flag it and trigger
  1349. * merging now that adding succeeded.
  1350. */
  1351. if (mhp_flags & MHP_MERGE_RESOURCE)
  1352. merge_system_ram_resource(res);
  1353. /* online pages if requested */
  1354. if (mhp_get_default_online_type() != MMOP_OFFLINE)
  1355. walk_memory_blocks(start, size, NULL, online_memory_block);
  1356. return ret;
  1357. error:
  1358. if (new_node) {
  1359. node_set_offline(nid);
  1360. unregister_node(nid);
  1361. }
  1362. error_memblock_remove:
  1363. if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
  1364. memblock_remove(start, size);
  1365. error_mem_hotplug_end:
  1366. mem_hotplug_done();
  1367. return ret;
  1368. }
  1369. /* requires device_hotplug_lock, see add_memory_resource() */
  1370. int __add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
  1371. {
  1372. struct resource *res;
  1373. int ret;
  1374. res = register_memory_resource(start, size, "System RAM");
  1375. if (IS_ERR(res))
  1376. return PTR_ERR(res);
  1377. ret = add_memory_resource(nid, res, mhp_flags);
  1378. if (ret < 0)
  1379. release_memory_resource(res);
  1380. return ret;
  1381. }
  1382. int add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
  1383. {
  1384. int rc;
  1385. lock_device_hotplug();
  1386. rc = __add_memory(nid, start, size, mhp_flags);
  1387. unlock_device_hotplug();
  1388. return rc;
  1389. }
  1390. EXPORT_SYMBOL_GPL(add_memory);
  1391. /*
  1392. * Add special, driver-managed memory to the system as system RAM. Such
  1393. * memory is not exposed via the raw firmware-provided memmap as system
  1394. * RAM, instead, it is detected and added by a driver - during cold boot,
  1395. * after a reboot, and after kexec.
  1396. *
  1397. * Reasons why this memory should not be used for the initial memmap of a
  1398. * kexec kernel or for placing kexec images:
  1399. * - The booting kernel is in charge of determining how this memory will be
  1400. * used (e.g., use persistent memory as system RAM)
  1401. * - Coordination with a hypervisor is required before this memory
  1402. * can be used (e.g., inaccessible parts).
  1403. *
  1404. * For this memory, no entries in /sys/firmware/memmap ("raw firmware-provided
  1405. * memory map") are created. Also, the created memory resource is flagged
  1406. * with IORESOURCE_SYSRAM_DRIVER_MANAGED, so in-kernel users can special-case
  1407. * this memory as well (esp., not place kexec images onto it).
  1408. *
  1409. * The resource_name (visible via /proc/iomem) has to have the format
  1410. * "System RAM ($DRIVER)".
  1411. */
  1412. int add_memory_driver_managed(int nid, u64 start, u64 size,
  1413. const char *resource_name, mhp_t mhp_flags)
  1414. {
  1415. struct resource *res;
  1416. int rc;
  1417. if (!resource_name ||
  1418. strstr(resource_name, "System RAM (") != resource_name ||
  1419. resource_name[strlen(resource_name) - 1] != ')')
  1420. return -EINVAL;
  1421. lock_device_hotplug();
  1422. res = register_memory_resource(start, size, resource_name);
  1423. if (IS_ERR(res)) {
  1424. rc = PTR_ERR(res);
  1425. goto out_unlock;
  1426. }
  1427. rc = add_memory_resource(nid, res, mhp_flags);
  1428. if (rc < 0)
  1429. release_memory_resource(res);
  1430. out_unlock:
  1431. unlock_device_hotplug();
  1432. return rc;
  1433. }
  1434. EXPORT_SYMBOL_GPL(add_memory_driver_managed);
  1435. /*
  1436. * Platforms should define arch_get_mappable_range() that provides
  1437. * maximum possible addressable physical memory range for which the
  1438. * linear mapping could be created. The platform returned address
  1439. * range must adhere to these following semantics.
  1440. *
  1441. * - range.start <= range.end
  1442. * - Range includes both end points [range.start..range.end]
  1443. *
  1444. * There is also a fallback definition provided here, allowing the
  1445. * entire possible physical address range in case any platform does
  1446. * not define arch_get_mappable_range().
  1447. */
  1448. struct range __weak arch_get_mappable_range(void)
  1449. {
  1450. struct range mhp_range = {
  1451. .start = 0UL,
  1452. .end = -1ULL,
  1453. };
  1454. return mhp_range;
  1455. }
  1456. struct range mhp_get_pluggable_range(bool need_mapping)
  1457. {
  1458. const u64 max_phys = DIRECT_MAP_PHYSMEM_END;
  1459. struct range mhp_range;
  1460. if (need_mapping) {
  1461. mhp_range = arch_get_mappable_range();
  1462. if (mhp_range.start > max_phys) {
  1463. mhp_range.start = 0;
  1464. mhp_range.end = 0;
  1465. }
  1466. mhp_range.end = min_t(u64, mhp_range.end, max_phys);
  1467. } else {
  1468. mhp_range.start = 0;
  1469. mhp_range.end = max_phys;
  1470. }
  1471. return mhp_range;
  1472. }
  1473. EXPORT_SYMBOL_GPL(mhp_get_pluggable_range);
  1474. bool mhp_range_allowed(u64 start, u64 size, bool need_mapping)
  1475. {
  1476. struct range mhp_range = mhp_get_pluggable_range(need_mapping);
  1477. u64 end = start + size;
  1478. if (start < end && start >= mhp_range.start && (end - 1) <= mhp_range.end)
  1479. return true;
  1480. pr_warn("Hotplug memory [%#llx-%#llx] exceeds maximum addressable range [%#llx-%#llx]\n",
  1481. start, end, mhp_range.start, mhp_range.end);
  1482. return false;
  1483. }
  1484. #ifdef CONFIG_MEMORY_HOTREMOVE
  1485. /*
  1486. * Scan pfn range [start,end) to find movable/migratable pages (LRU and
  1487. * hugetlb folio, movable_ops pages). Will skip over most unmovable
  1488. * pages (esp., pages that can be skipped when offlining), but bail out on
  1489. * definitely unmovable pages.
  1490. *
  1491. * Returns:
  1492. * 0 in case a movable page is found and movable_pfn was updated.
  1493. * -ENOENT in case no movable page was found.
  1494. * -EBUSY in case a definitely unmovable page was found.
  1495. */
  1496. static int scan_movable_pages(unsigned long start, unsigned long end,
  1497. unsigned long *movable_pfn)
  1498. {
  1499. unsigned long pfn;
  1500. for_each_valid_pfn(pfn, start, end) {
  1501. struct page *page;
  1502. struct folio *folio;
  1503. page = pfn_to_page(pfn);
  1504. if (PageLRU(page) || page_has_movable_ops(page))
  1505. goto found;
  1506. /*
  1507. * PageOffline() pages that do not have movable_ops and
  1508. * have a reference count > 0 (after MEM_GOING_OFFLINE) are
  1509. * definitely unmovable. If their reference count would be 0,
  1510. * they could at least be skipped when offlining memory.
  1511. */
  1512. if (PageOffline(page) && page_count(page))
  1513. return -EBUSY;
  1514. if (!PageHuge(page))
  1515. continue;
  1516. folio = page_folio(page);
  1517. /*
  1518. * This test is racy as we hold no reference or lock. The
  1519. * hugetlb page could have been free'ed and head is no longer
  1520. * a hugetlb page before the following check. In such unlikely
  1521. * cases false positives and negatives are possible. Calling
  1522. * code must deal with these scenarios.
  1523. */
  1524. if (folio_test_hugetlb_migratable(folio))
  1525. goto found;
  1526. pfn |= folio_nr_pages(folio) - 1;
  1527. }
  1528. return -ENOENT;
  1529. found:
  1530. *movable_pfn = pfn;
  1531. return 0;
  1532. }
  1533. static void do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
  1534. {
  1535. struct folio *folio;
  1536. unsigned long pfn;
  1537. LIST_HEAD(source);
  1538. static DEFINE_RATELIMIT_STATE(migrate_rs, DEFAULT_RATELIMIT_INTERVAL,
  1539. DEFAULT_RATELIMIT_BURST);
  1540. for_each_valid_pfn(pfn, start_pfn, end_pfn) {
  1541. struct page *page;
  1542. page = pfn_to_page(pfn);
  1543. folio = page_folio(page);
  1544. if (!folio_try_get(folio))
  1545. continue;
  1546. if (unlikely(page_folio(page) != folio))
  1547. goto put_folio;
  1548. if (folio_test_large(folio))
  1549. pfn = folio_pfn(folio) + folio_nr_pages(folio) - 1;
  1550. if (folio_contain_hwpoisoned_page(folio)) {
  1551. /*
  1552. * unmap_poisoned_folio() cannot handle large folios
  1553. * in all cases yet.
  1554. */
  1555. if (folio_test_large(folio) && !folio_test_hugetlb(folio))
  1556. goto put_folio;
  1557. if (folio_test_lru(folio) && !folio_isolate_lru(folio))
  1558. goto put_folio;
  1559. if (folio_mapped(folio)) {
  1560. folio_lock(folio);
  1561. unmap_poisoned_folio(folio, pfn, false);
  1562. folio_unlock(folio);
  1563. }
  1564. goto put_folio;
  1565. }
  1566. if (!isolate_folio_to_list(folio, &source)) {
  1567. if (__ratelimit(&migrate_rs)) {
  1568. pr_warn("failed to isolate pfn %lx\n",
  1569. page_to_pfn(page));
  1570. dump_page(page, "isolation failed");
  1571. }
  1572. }
  1573. put_folio:
  1574. folio_put(folio);
  1575. }
  1576. if (!list_empty(&source)) {
  1577. nodemask_t nmask = node_states[N_MEMORY];
  1578. struct migration_target_control mtc = {
  1579. .nmask = &nmask,
  1580. .gfp_mask = GFP_KERNEL | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
  1581. .reason = MR_MEMORY_HOTPLUG,
  1582. };
  1583. int ret;
  1584. /*
  1585. * We have checked that migration range is on a single zone so
  1586. * we can use the nid of the first page to all the others.
  1587. */
  1588. mtc.nid = folio_nid(list_first_entry(&source, struct folio, lru));
  1589. /*
  1590. * try to allocate from a different node but reuse this node
  1591. * if there are no other online nodes to be used (e.g. we are
  1592. * offlining a part of the only existing node)
  1593. */
  1594. node_clear(mtc.nid, nmask);
  1595. if (nodes_empty(nmask))
  1596. node_set(mtc.nid, nmask);
  1597. ret = migrate_pages(&source, alloc_migration_target, NULL,
  1598. (unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_HOTPLUG, NULL);
  1599. if (ret) {
  1600. list_for_each_entry(folio, &source, lru) {
  1601. if (__ratelimit(&migrate_rs)) {
  1602. pr_warn("migrating pfn %lx failed ret:%d\n",
  1603. folio_pfn(folio), ret);
  1604. dump_page(&folio->page,
  1605. "migration failure");
  1606. }
  1607. }
  1608. putback_movable_pages(&source);
  1609. }
  1610. }
  1611. }
  1612. static int __init cmdline_parse_movable_node(char *p)
  1613. {
  1614. movable_node_enabled = true;
  1615. return 0;
  1616. }
  1617. early_param("movable_node", cmdline_parse_movable_node);
  1618. static int count_system_ram_pages_cb(unsigned long start_pfn,
  1619. unsigned long nr_pages, void *data)
  1620. {
  1621. unsigned long *nr_system_ram_pages = data;
  1622. *nr_system_ram_pages += nr_pages;
  1623. return 0;
  1624. }
  1625. /*
  1626. * Must be called with mem_hotplug_lock in write mode.
  1627. */
  1628. int offline_pages(unsigned long start_pfn, unsigned long nr_pages,
  1629. struct zone *zone, struct memory_group *group)
  1630. {
  1631. unsigned long pfn, managed_pages, system_ram_pages = 0;
  1632. const unsigned long end_pfn = start_pfn + nr_pages;
  1633. struct pglist_data *pgdat = zone->zone_pgdat;
  1634. const int node = zone_to_nid(zone);
  1635. struct memory_notify mem_arg = {
  1636. .start_pfn = start_pfn,
  1637. .nr_pages = nr_pages,
  1638. };
  1639. struct node_notify node_arg = {
  1640. .nid = NUMA_NO_NODE,
  1641. };
  1642. unsigned long flags;
  1643. char *reason;
  1644. int ret;
  1645. unsigned long normal_pages = 0;
  1646. enum zone_type zt;
  1647. /*
  1648. * {on,off}lining is constrained to full memory sections (or more
  1649. * precisely to memory blocks from the user space POV).
  1650. * memmap_on_memory is an exception because it reserves initial part
  1651. * of the physical memory space for vmemmaps. That space is pageblock
  1652. * aligned.
  1653. */
  1654. if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(start_pfn) ||
  1655. !IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION)))
  1656. return -EINVAL;
  1657. /*
  1658. * Don't allow to offline memory blocks that contain holes.
  1659. * Consequently, memory blocks with holes can never get onlined
  1660. * via the hotplug path - online_pages() - as hotplugged memory has
  1661. * no holes. This way, we don't have to worry about memory holes,
  1662. * don't need pfn_valid() checks, and can avoid using
  1663. * walk_system_ram_range() later.
  1664. */
  1665. walk_system_ram_range(start_pfn, nr_pages, &system_ram_pages,
  1666. count_system_ram_pages_cb);
  1667. if (system_ram_pages != nr_pages) {
  1668. ret = -EINVAL;
  1669. reason = "memory holes";
  1670. goto failed_removal;
  1671. }
  1672. /*
  1673. * We only support offlining of memory blocks managed by a single zone,
  1674. * checked by calling code. This is just a sanity check that we might
  1675. * want to remove in the future.
  1676. */
  1677. if (WARN_ON_ONCE(page_zone(pfn_to_page(start_pfn)) != zone ||
  1678. page_zone(pfn_to_page(end_pfn - 1)) != zone)) {
  1679. ret = -EINVAL;
  1680. reason = "multizone range";
  1681. goto failed_removal;
  1682. }
  1683. /*
  1684. * Disable pcplists so that page isolation cannot race with freeing
  1685. * in a way that pages from isolated pageblock are left on pcplists.
  1686. */
  1687. zone_pcp_disable(zone);
  1688. lru_cache_disable();
  1689. /* set above range as isolated */
  1690. ret = start_isolate_page_range(start_pfn, end_pfn,
  1691. PB_ISOLATE_MODE_MEM_OFFLINE);
  1692. if (ret) {
  1693. reason = "failure to isolate range";
  1694. goto failed_removal_pcplists_disabled;
  1695. }
  1696. /*
  1697. * Check whether the node will have no present pages after we offline
  1698. * 'nr_pages' more. If so, we know that the node will become empty, and
  1699. * so we will clear N_MEMORY for it.
  1700. */
  1701. if (nr_pages >= pgdat->node_present_pages) {
  1702. node_arg.nid = node;
  1703. ret = node_notify(NODE_REMOVING_LAST_MEMORY, &node_arg);
  1704. ret = notifier_to_errno(ret);
  1705. if (ret) {
  1706. reason = "node notifier failure";
  1707. goto failed_removal_isolated;
  1708. }
  1709. }
  1710. ret = memory_notify(MEM_GOING_OFFLINE, &mem_arg);
  1711. ret = notifier_to_errno(ret);
  1712. if (ret) {
  1713. reason = "notifier failure";
  1714. goto failed_removal_isolated;
  1715. }
  1716. do {
  1717. pfn = start_pfn;
  1718. do {
  1719. /*
  1720. * Historically we always checked for any signal and
  1721. * can't limit it to fatal signals without eventually
  1722. * breaking user space.
  1723. */
  1724. if (signal_pending(current)) {
  1725. ret = -EINTR;
  1726. reason = "signal backoff";
  1727. goto failed_removal_isolated;
  1728. }
  1729. cond_resched();
  1730. ret = scan_movable_pages(pfn, end_pfn, &pfn);
  1731. if (!ret) {
  1732. /*
  1733. * TODO: fatal migration failures should bail
  1734. * out
  1735. */
  1736. do_migrate_range(pfn, end_pfn);
  1737. }
  1738. } while (!ret);
  1739. if (ret != -ENOENT) {
  1740. reason = "unmovable page";
  1741. goto failed_removal_isolated;
  1742. }
  1743. /*
  1744. * Dissolve free hugetlb folios in the memory block before doing
  1745. * offlining actually in order to make hugetlbfs's object
  1746. * counting consistent.
  1747. */
  1748. ret = dissolve_free_hugetlb_folios(start_pfn, end_pfn);
  1749. if (ret) {
  1750. reason = "failure to dissolve huge pages";
  1751. goto failed_removal_isolated;
  1752. }
  1753. ret = test_pages_isolated(start_pfn, end_pfn,
  1754. PB_ISOLATE_MODE_MEM_OFFLINE);
  1755. } while (ret);
  1756. /* Mark all sections offline and remove free pages from the buddy. */
  1757. managed_pages = __offline_isolated_pages(start_pfn, end_pfn);
  1758. pr_debug("Offlined Pages %ld\n", nr_pages);
  1759. /*
  1760. * The memory sections are marked offline, and the pageblock flags
  1761. * effectively stale; nobody should be touching them. Fixup the number
  1762. * of isolated pageblocks, memory onlining will properly revert this.
  1763. */
  1764. spin_lock_irqsave(&zone->lock, flags);
  1765. zone->nr_isolate_pageblock -= nr_pages / pageblock_nr_pages;
  1766. spin_unlock_irqrestore(&zone->lock, flags);
  1767. lru_cache_enable();
  1768. zone_pcp_enable(zone);
  1769. /* removal success */
  1770. adjust_managed_page_count(pfn_to_page(start_pfn), -managed_pages);
  1771. adjust_present_page_count(pfn_to_page(start_pfn), group, -nr_pages);
  1772. /* reinitialise watermarks and update pcp limits */
  1773. init_per_zone_wmark_min();
  1774. /*
  1775. * Check whether this operation removes the last normal memory from
  1776. * the node. We do this before clearing N_MEMORY to avoid the possible
  1777. * transient "!N_MEMORY && N_NORMAL_MEMORY" state.
  1778. */
  1779. if (zone_idx(zone) <= ZONE_NORMAL) {
  1780. for (zt = 0; zt <= ZONE_NORMAL; zt++)
  1781. normal_pages += pgdat->node_zones[zt].present_pages;
  1782. if (!normal_pages)
  1783. node_clear_state(node, N_NORMAL_MEMORY);
  1784. }
  1785. /*
  1786. * Make sure to mark the node as memory-less before rebuilding the zone
  1787. * list. Otherwise this node would still appear in the fallback lists.
  1788. */
  1789. if (node_arg.nid >= 0)
  1790. node_clear_state(node, N_MEMORY);
  1791. if (!populated_zone(zone)) {
  1792. zone_pcp_reset(zone);
  1793. build_all_zonelists(NULL);
  1794. }
  1795. if (node_arg.nid >= 0) {
  1796. kcompactd_stop(node);
  1797. kswapd_stop(node);
  1798. /* Node went memoryless. Notify consumers */
  1799. node_notify(NODE_REMOVED_LAST_MEMORY, &node_arg);
  1800. }
  1801. writeback_set_ratelimit();
  1802. memory_notify(MEM_OFFLINE, &mem_arg);
  1803. remove_pfn_range_from_zone(zone, start_pfn, nr_pages);
  1804. return 0;
  1805. failed_removal_isolated:
  1806. /* pushback to free area */
  1807. undo_isolate_page_range(start_pfn, end_pfn);
  1808. memory_notify(MEM_CANCEL_OFFLINE, &mem_arg);
  1809. if (node_arg.nid != NUMA_NO_NODE)
  1810. node_notify(NODE_CANCEL_REMOVING_LAST_MEMORY, &node_arg);
  1811. failed_removal_pcplists_disabled:
  1812. lru_cache_enable();
  1813. zone_pcp_enable(zone);
  1814. failed_removal:
  1815. pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
  1816. (unsigned long long) start_pfn << PAGE_SHIFT,
  1817. ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
  1818. reason);
  1819. return ret;
  1820. }
  1821. static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
  1822. {
  1823. int *nid = arg;
  1824. *nid = mem->nid;
  1825. if (unlikely(mem->state != MEM_OFFLINE)) {
  1826. phys_addr_t beginpa, endpa;
  1827. beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
  1828. endpa = beginpa + memory_block_size_bytes() - 1;
  1829. pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
  1830. &beginpa, &endpa);
  1831. return -EBUSY;
  1832. }
  1833. return 0;
  1834. }
  1835. static int count_memory_range_altmaps_cb(struct memory_block *mem, void *arg)
  1836. {
  1837. u64 *num_altmaps = (u64 *)arg;
  1838. if (mem->altmap)
  1839. *num_altmaps += 1;
  1840. return 0;
  1841. }
  1842. static int check_cpu_on_node(int nid)
  1843. {
  1844. int cpu;
  1845. for_each_present_cpu(cpu) {
  1846. if (cpu_to_node(cpu) == nid)
  1847. /*
  1848. * the cpu on this node isn't removed, and we can't
  1849. * offline this node.
  1850. */
  1851. return -EBUSY;
  1852. }
  1853. return 0;
  1854. }
  1855. static int check_no_memblock_for_node_cb(struct memory_block *mem, void *arg)
  1856. {
  1857. int nid = *(int *)arg;
  1858. /*
  1859. * If a memory block belongs to multiple nodes, the stored nid is not
  1860. * reliable. However, such blocks are always online (e.g., cannot get
  1861. * offlined) and, therefore, are still spanned by the node.
  1862. */
  1863. return mem->nid == nid ? -EEXIST : 0;
  1864. }
  1865. /**
  1866. * try_offline_node
  1867. * @nid: the node ID
  1868. *
  1869. * Offline a node if all memory sections and cpus of the node are removed.
  1870. *
  1871. * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
  1872. * and online/offline operations before this call.
  1873. */
  1874. void try_offline_node(int nid)
  1875. {
  1876. int rc;
  1877. /*
  1878. * If the node still spans pages (especially ZONE_DEVICE), don't
  1879. * offline it. A node spans memory after move_pfn_range_to_zone(),
  1880. * e.g., after the memory block was onlined.
  1881. */
  1882. if (node_spanned_pages(nid))
  1883. return;
  1884. /*
  1885. * Especially offline memory blocks might not be spanned by the
  1886. * node. They will get spanned by the node once they get onlined.
  1887. * However, they link to the node in sysfs and can get onlined later.
  1888. */
  1889. rc = for_each_memory_block(&nid, check_no_memblock_for_node_cb);
  1890. if (rc)
  1891. return;
  1892. if (check_cpu_on_node(nid))
  1893. return;
  1894. /*
  1895. * all memory/cpu of this node are removed, we can offline this
  1896. * node now.
  1897. */
  1898. node_set_offline(nid);
  1899. unregister_node(nid);
  1900. }
  1901. EXPORT_SYMBOL(try_offline_node);
  1902. static int memory_blocks_have_altmaps(u64 start, u64 size)
  1903. {
  1904. u64 num_memblocks = size / memory_block_size_bytes();
  1905. u64 num_altmaps = 0;
  1906. if (!mhp_memmap_on_memory())
  1907. return 0;
  1908. walk_memory_blocks(start, size, &num_altmaps,
  1909. count_memory_range_altmaps_cb);
  1910. if (num_altmaps == 0)
  1911. return 0;
  1912. if (WARN_ON_ONCE(num_memblocks != num_altmaps))
  1913. return -EINVAL;
  1914. return 1;
  1915. }
  1916. static int try_remove_memory(u64 start, u64 size)
  1917. {
  1918. int rc, nid = NUMA_NO_NODE;
  1919. BUG_ON(check_hotplug_memory_range(start, size));
  1920. /*
  1921. * All memory blocks must be offlined before removing memory. Check
  1922. * whether all memory blocks in question are offline and return error
  1923. * if this is not the case.
  1924. *
  1925. * While at it, determine the nid. Note that if we'd have mixed nodes,
  1926. * we'd only try to offline the last determined one -- which is good
  1927. * enough for the cases we care about.
  1928. */
  1929. rc = walk_memory_blocks(start, size, &nid, check_memblock_offlined_cb);
  1930. if (rc)
  1931. return rc;
  1932. /* remove memmap entry */
  1933. firmware_map_remove(start, start + size, "System RAM");
  1934. mem_hotplug_begin();
  1935. rc = memory_blocks_have_altmaps(start, size);
  1936. if (rc < 0) {
  1937. mem_hotplug_done();
  1938. return rc;
  1939. } else if (!rc) {
  1940. /*
  1941. * Memory block device removal under the device_hotplug_lock is
  1942. * a barrier against racing online attempts.
  1943. * No altmaps present, do the removal directly
  1944. */
  1945. remove_memory_block_devices(start, size);
  1946. arch_remove_memory(start, size, NULL);
  1947. } else {
  1948. /* all memblocks in the range have altmaps */
  1949. remove_memory_blocks_and_altmaps(start, size);
  1950. }
  1951. if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
  1952. memblock_remove(start, size);
  1953. release_mem_region_adjustable(start, size);
  1954. if (nid != NUMA_NO_NODE)
  1955. try_offline_node(nid);
  1956. mem_hotplug_done();
  1957. return 0;
  1958. }
  1959. /**
  1960. * __remove_memory - Remove memory if every memory block is offline
  1961. * @start: physical address of the region to remove
  1962. * @size: size of the region to remove
  1963. *
  1964. * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
  1965. * and online/offline operations before this call, as required by
  1966. * try_offline_node().
  1967. */
  1968. void __remove_memory(u64 start, u64 size)
  1969. {
  1970. /*
  1971. * trigger BUG() if some memory is not offlined prior to calling this
  1972. * function
  1973. */
  1974. if (try_remove_memory(start, size))
  1975. BUG();
  1976. }
  1977. /*
  1978. * Remove memory if every memory block is offline, otherwise return -EBUSY is
  1979. * some memory is not offline
  1980. */
  1981. int remove_memory(u64 start, u64 size)
  1982. {
  1983. int rc;
  1984. lock_device_hotplug();
  1985. rc = try_remove_memory(start, size);
  1986. unlock_device_hotplug();
  1987. return rc;
  1988. }
  1989. EXPORT_SYMBOL_GPL(remove_memory);
  1990. static int try_offline_memory_block(struct memory_block *mem, void *arg)
  1991. {
  1992. uint8_t online_type = MMOP_ONLINE_KERNEL;
  1993. uint8_t **online_types = arg;
  1994. struct page *page;
  1995. int rc;
  1996. /*
  1997. * Sense the online_type via the zone of the memory block. Offlining
  1998. * with multiple zones within one memory block will be rejected
  1999. * by offlining code ... so we don't care about that.
  2000. */
  2001. page = pfn_to_online_page(section_nr_to_pfn(mem->start_section_nr));
  2002. if (page && page_zonenum(page) == ZONE_MOVABLE)
  2003. online_type = MMOP_ONLINE_MOVABLE;
  2004. rc = device_offline(&mem->dev);
  2005. /*
  2006. * Default is MMOP_OFFLINE - change it only if offlining succeeded,
  2007. * so try_reonline_memory_block() can do the right thing.
  2008. */
  2009. if (!rc)
  2010. **online_types = online_type;
  2011. (*online_types)++;
  2012. /* Ignore if already offline. */
  2013. return rc < 0 ? rc : 0;
  2014. }
  2015. static int try_reonline_memory_block(struct memory_block *mem, void *arg)
  2016. {
  2017. uint8_t **online_types = arg;
  2018. int rc;
  2019. if (**online_types != MMOP_OFFLINE) {
  2020. mem->online_type = **online_types;
  2021. rc = device_online(&mem->dev);
  2022. if (rc < 0)
  2023. pr_warn("%s: Failed to re-online memory: %d",
  2024. __func__, rc);
  2025. }
  2026. /* Continue processing all remaining memory blocks. */
  2027. (*online_types)++;
  2028. return 0;
  2029. }
  2030. /*
  2031. * Try to offline and remove memory. Might take a long time to finish in case
  2032. * memory is still in use. Primarily useful for memory devices that logically
  2033. * unplugged all memory (so it's no longer in use) and want to offline + remove
  2034. * that memory.
  2035. */
  2036. int offline_and_remove_memory(u64 start, u64 size)
  2037. {
  2038. const unsigned long mb_count = size / memory_block_size_bytes();
  2039. uint8_t *online_types, *tmp;
  2040. int rc;
  2041. if (!IS_ALIGNED(start, memory_block_size_bytes()) ||
  2042. !IS_ALIGNED(size, memory_block_size_bytes()) || !size)
  2043. return -EINVAL;
  2044. /*
  2045. * We'll remember the old online type of each memory block, so we can
  2046. * try to revert whatever we did when offlining one memory block fails
  2047. * after offlining some others succeeded.
  2048. */
  2049. online_types = kmalloc_array(mb_count, sizeof(*online_types),
  2050. GFP_KERNEL);
  2051. if (!online_types)
  2052. return -ENOMEM;
  2053. /*
  2054. * Initialize all states to MMOP_OFFLINE, so when we abort processing in
  2055. * try_offline_memory_block(), we'll skip all unprocessed blocks in
  2056. * try_reonline_memory_block().
  2057. */
  2058. memset(online_types, MMOP_OFFLINE, mb_count);
  2059. lock_device_hotplug();
  2060. tmp = online_types;
  2061. rc = walk_memory_blocks(start, size, &tmp, try_offline_memory_block);
  2062. /*
  2063. * In case we succeeded to offline all memory, remove it.
  2064. * This cannot fail as it cannot get onlined in the meantime.
  2065. */
  2066. if (!rc) {
  2067. rc = try_remove_memory(start, size);
  2068. if (rc)
  2069. pr_err("%s: Failed to remove memory: %d", __func__, rc);
  2070. }
  2071. /*
  2072. * Rollback what we did. While memory onlining might theoretically fail
  2073. * (nacked by a notifier), it barely ever happens.
  2074. */
  2075. if (rc) {
  2076. tmp = online_types;
  2077. walk_memory_blocks(start, size, &tmp,
  2078. try_reonline_memory_block);
  2079. }
  2080. unlock_device_hotplug();
  2081. kfree(online_types);
  2082. return rc;
  2083. }
  2084. EXPORT_SYMBOL_GPL(offline_and_remove_memory);
  2085. #endif /* CONFIG_MEMORY_HOTREMOVE */