memory_hotplug.c 66 KB

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