memory_hotplug.c 67 KB

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