mm_init.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * mm_init.c - Memory initialisation verification and debugging
  4. *
  5. * Copyright 2008 IBM Corporation, 2008
  6. * Author Mel Gorman <mel@csn.ul.ie>
  7. *
  8. */
  9. #include <linux/kernel.h>
  10. #include <linux/init.h>
  11. #include <linux/kobject.h>
  12. #include <linux/export.h>
  13. #include <linux/memory.h>
  14. #include <linux/notifier.h>
  15. #include <linux/sched.h>
  16. #include <linux/mman.h>
  17. #include <linux/memblock.h>
  18. #include <linux/page-isolation.h>
  19. #include <linux/padata.h>
  20. #include <linux/nmi.h>
  21. #include <linux/buffer_head.h>
  22. #include <linux/kmemleak.h>
  23. #include <linux/kfence.h>
  24. #include <linux/page_ext.h>
  25. #include <linux/pti.h>
  26. #include <linux/pgtable.h>
  27. #include <linux/stackdepot.h>
  28. #include <linux/swap.h>
  29. #include <linux/cma.h>
  30. #include <linux/crash_dump.h>
  31. #include <linux/execmem.h>
  32. #include <linux/vmstat.h>
  33. #include "internal.h"
  34. #include "slab.h"
  35. #include "shuffle.h"
  36. #include <asm/setup.h>
  37. #ifdef CONFIG_DEBUG_MEMORY_INIT
  38. int __meminitdata mminit_loglevel;
  39. /* The zonelists are simply reported, validation is manual. */
  40. void __init mminit_verify_zonelist(void)
  41. {
  42. int nid;
  43. if (mminit_loglevel < MMINIT_VERIFY)
  44. return;
  45. for_each_online_node(nid) {
  46. pg_data_t *pgdat = NODE_DATA(nid);
  47. struct zone *zone;
  48. struct zoneref *z;
  49. struct zonelist *zonelist;
  50. int i, listid, zoneid;
  51. for (i = 0; i < MAX_ZONELISTS * MAX_NR_ZONES; i++) {
  52. /* Identify the zone and nodelist */
  53. zoneid = i % MAX_NR_ZONES;
  54. listid = i / MAX_NR_ZONES;
  55. zonelist = &pgdat->node_zonelists[listid];
  56. zone = &pgdat->node_zones[zoneid];
  57. if (!populated_zone(zone))
  58. continue;
  59. /* Print information about the zonelist */
  60. printk(KERN_DEBUG "mminit::zonelist %s %d:%s = ",
  61. listid > 0 ? "thisnode" : "general", nid,
  62. zone->name);
  63. /* Iterate the zonelist */
  64. for_each_zone_zonelist(zone, z, zonelist, zoneid)
  65. pr_cont("%d:%s ", zone_to_nid(zone), zone->name);
  66. pr_cont("\n");
  67. }
  68. }
  69. }
  70. void __init mminit_verify_pageflags_layout(void)
  71. {
  72. int shift, width;
  73. unsigned long or_mask, add_mask;
  74. shift = BITS_PER_LONG;
  75. width = shift - SECTIONS_WIDTH - NODES_WIDTH - ZONES_WIDTH
  76. - LAST_CPUPID_SHIFT - KASAN_TAG_WIDTH - LRU_GEN_WIDTH - LRU_REFS_WIDTH;
  77. mminit_dprintk(MMINIT_TRACE, "pageflags_layout_widths",
  78. "Section %d Node %d Zone %d Lastcpupid %d Kasantag %d Gen %d Tier %d Flags %d\n",
  79. SECTIONS_WIDTH,
  80. NODES_WIDTH,
  81. ZONES_WIDTH,
  82. LAST_CPUPID_WIDTH,
  83. KASAN_TAG_WIDTH,
  84. LRU_GEN_WIDTH,
  85. LRU_REFS_WIDTH,
  86. NR_PAGEFLAGS);
  87. mminit_dprintk(MMINIT_TRACE, "pageflags_layout_shifts",
  88. "Section %d Node %d Zone %d Lastcpupid %d Kasantag %d\n",
  89. SECTIONS_SHIFT,
  90. NODES_SHIFT,
  91. ZONES_SHIFT,
  92. LAST_CPUPID_SHIFT,
  93. KASAN_TAG_WIDTH);
  94. mminit_dprintk(MMINIT_TRACE, "pageflags_layout_pgshifts",
  95. "Section %lu Node %lu Zone %lu Lastcpupid %lu Kasantag %lu\n",
  96. (unsigned long)SECTIONS_PGSHIFT,
  97. (unsigned long)NODES_PGSHIFT,
  98. (unsigned long)ZONES_PGSHIFT,
  99. (unsigned long)LAST_CPUPID_PGSHIFT,
  100. (unsigned long)KASAN_TAG_PGSHIFT);
  101. mminit_dprintk(MMINIT_TRACE, "pageflags_layout_nodezoneid",
  102. "Node/Zone ID: %lu -> %lu\n",
  103. (unsigned long)(ZONEID_PGOFF + ZONEID_SHIFT),
  104. (unsigned long)ZONEID_PGOFF);
  105. mminit_dprintk(MMINIT_TRACE, "pageflags_layout_usage",
  106. "location: %d -> %d layout %d -> %d unused %d -> %d page-flags\n",
  107. shift, width, width, NR_PAGEFLAGS, NR_PAGEFLAGS, 0);
  108. #ifdef NODE_NOT_IN_PAGE_FLAGS
  109. mminit_dprintk(MMINIT_TRACE, "pageflags_layout_nodeflags",
  110. "Node not in page flags");
  111. #endif
  112. #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS
  113. mminit_dprintk(MMINIT_TRACE, "pageflags_layout_nodeflags",
  114. "Last cpupid not in page flags");
  115. #endif
  116. if (SECTIONS_WIDTH) {
  117. shift -= SECTIONS_WIDTH;
  118. BUG_ON(shift != SECTIONS_PGSHIFT);
  119. }
  120. if (NODES_WIDTH) {
  121. shift -= NODES_WIDTH;
  122. BUG_ON(shift != NODES_PGSHIFT);
  123. }
  124. if (ZONES_WIDTH) {
  125. shift -= ZONES_WIDTH;
  126. BUG_ON(shift != ZONES_PGSHIFT);
  127. }
  128. /* Check for bitmask overlaps */
  129. or_mask = (ZONES_MASK << ZONES_PGSHIFT) |
  130. (NODES_MASK << NODES_PGSHIFT) |
  131. (SECTIONS_MASK << SECTIONS_PGSHIFT);
  132. add_mask = (ZONES_MASK << ZONES_PGSHIFT) +
  133. (NODES_MASK << NODES_PGSHIFT) +
  134. (SECTIONS_MASK << SECTIONS_PGSHIFT);
  135. BUG_ON(or_mask != add_mask);
  136. }
  137. static __init int set_mminit_loglevel(char *str)
  138. {
  139. get_option(&str, &mminit_loglevel);
  140. return 0;
  141. }
  142. early_param("mminit_loglevel", set_mminit_loglevel);
  143. #endif /* CONFIG_DEBUG_MEMORY_INIT */
  144. struct kobject *mm_kobj;
  145. #ifdef CONFIG_SMP
  146. s32 vm_committed_as_batch = 32;
  147. void mm_compute_batch(int overcommit_policy)
  148. {
  149. u64 memsized_batch;
  150. s32 nr = num_present_cpus();
  151. s32 batch = max_t(s32, nr*2, 32);
  152. unsigned long ram_pages = totalram_pages();
  153. /*
  154. * For policy OVERCOMMIT_NEVER, set batch size to 0.4% of
  155. * (total memory/#cpus), and lift it to 25% for other policies
  156. * to easy the possible lock contention for percpu_counter
  157. * vm_committed_as, while the max limit is INT_MAX
  158. */
  159. if (overcommit_policy == OVERCOMMIT_NEVER)
  160. memsized_batch = min_t(u64, ram_pages/nr/256, INT_MAX);
  161. else
  162. memsized_batch = min_t(u64, ram_pages/nr/4, INT_MAX);
  163. vm_committed_as_batch = max_t(s32, memsized_batch, batch);
  164. }
  165. static int __meminit mm_compute_batch_notifier(struct notifier_block *self,
  166. unsigned long action, void *arg)
  167. {
  168. switch (action) {
  169. case MEM_ONLINE:
  170. case MEM_OFFLINE:
  171. mm_compute_batch(sysctl_overcommit_memory);
  172. break;
  173. default:
  174. break;
  175. }
  176. return NOTIFY_OK;
  177. }
  178. static int __init mm_compute_batch_init(void)
  179. {
  180. mm_compute_batch(sysctl_overcommit_memory);
  181. hotplug_memory_notifier(mm_compute_batch_notifier, MM_COMPUTE_BATCH_PRI);
  182. return 0;
  183. }
  184. __initcall(mm_compute_batch_init);
  185. #endif
  186. static int __init mm_sysfs_init(void)
  187. {
  188. mm_kobj = kobject_create_and_add("mm", kernel_kobj);
  189. if (!mm_kobj)
  190. return -ENOMEM;
  191. return 0;
  192. }
  193. postcore_initcall(mm_sysfs_init);
  194. static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
  195. static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
  196. static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
  197. static unsigned long required_kernelcore __initdata;
  198. static unsigned long required_kernelcore_percent __initdata;
  199. static unsigned long required_movablecore __initdata;
  200. static unsigned long required_movablecore_percent __initdata;
  201. static unsigned long nr_kernel_pages __initdata;
  202. static unsigned long nr_all_pages __initdata;
  203. static bool deferred_struct_pages __meminitdata;
  204. static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
  205. static int __init cmdline_parse_core(char *p, unsigned long *core,
  206. unsigned long *percent)
  207. {
  208. unsigned long long coremem;
  209. char *endptr;
  210. if (!p)
  211. return -EINVAL;
  212. /* Value may be a percentage of total memory, otherwise bytes */
  213. coremem = simple_strtoull(p, &endptr, 0);
  214. if (*endptr == '%') {
  215. /* Paranoid check for percent values greater than 100 */
  216. WARN_ON(coremem > 100);
  217. *percent = coremem;
  218. } else {
  219. coremem = memparse(p, &p);
  220. /* Paranoid check that UL is enough for the coremem value */
  221. WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
  222. *core = coremem >> PAGE_SHIFT;
  223. *percent = 0UL;
  224. }
  225. return 0;
  226. }
  227. bool mirrored_kernelcore __initdata_memblock;
  228. /*
  229. * kernelcore=size sets the amount of memory for use for allocations that
  230. * cannot be reclaimed or migrated.
  231. */
  232. static int __init cmdline_parse_kernelcore(char *p)
  233. {
  234. /* parse kernelcore=mirror */
  235. if (parse_option_str(p, "mirror")) {
  236. mirrored_kernelcore = true;
  237. return 0;
  238. }
  239. return cmdline_parse_core(p, &required_kernelcore,
  240. &required_kernelcore_percent);
  241. }
  242. early_param("kernelcore", cmdline_parse_kernelcore);
  243. /*
  244. * movablecore=size sets the amount of memory for use for allocations that
  245. * can be reclaimed or migrated.
  246. */
  247. static int __init cmdline_parse_movablecore(char *p)
  248. {
  249. return cmdline_parse_core(p, &required_movablecore,
  250. &required_movablecore_percent);
  251. }
  252. early_param("movablecore", cmdline_parse_movablecore);
  253. /*
  254. * early_calculate_totalpages()
  255. * Sum pages in active regions for movable zone.
  256. * Populate N_MEMORY for calculating usable_nodes.
  257. */
  258. static unsigned long __init early_calculate_totalpages(void)
  259. {
  260. unsigned long totalpages = 0;
  261. unsigned long start_pfn, end_pfn;
  262. int i, nid;
  263. for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
  264. unsigned long pages = end_pfn - start_pfn;
  265. totalpages += pages;
  266. if (pages)
  267. node_set_state(nid, N_MEMORY);
  268. }
  269. return totalpages;
  270. }
  271. /*
  272. * This finds a zone that can be used for ZONE_MOVABLE pages. The
  273. * assumption is made that zones within a node are ordered in monotonic
  274. * increasing memory addresses so that the "highest" populated zone is used
  275. */
  276. static void __init find_usable_zone_for_movable(void)
  277. {
  278. int zone_index;
  279. for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
  280. if (zone_index == ZONE_MOVABLE)
  281. continue;
  282. if (arch_zone_highest_possible_pfn[zone_index] >
  283. arch_zone_lowest_possible_pfn[zone_index])
  284. break;
  285. }
  286. VM_BUG_ON(zone_index == -1);
  287. movable_zone = zone_index;
  288. }
  289. /*
  290. * Find the PFN the Movable zone begins in each node. Kernel memory
  291. * is spread evenly between nodes as long as the nodes have enough
  292. * memory. When they don't, some nodes will have more kernelcore than
  293. * others
  294. */
  295. static void __init find_zone_movable_pfns_for_nodes(void)
  296. {
  297. int i, nid;
  298. unsigned long usable_startpfn;
  299. unsigned long kernelcore_node, kernelcore_remaining;
  300. /* save the state before borrow the nodemask */
  301. nodemask_t saved_node_state = node_states[N_MEMORY];
  302. unsigned long totalpages = early_calculate_totalpages();
  303. int usable_nodes = nodes_weight(node_states[N_MEMORY]);
  304. struct memblock_region *r;
  305. /* Need to find movable_zone earlier when movable_node is specified. */
  306. find_usable_zone_for_movable();
  307. /*
  308. * If movable_node is specified, ignore kernelcore and movablecore
  309. * options.
  310. */
  311. if (movable_node_is_enabled()) {
  312. for_each_mem_region(r) {
  313. if (!memblock_is_hotpluggable(r))
  314. continue;
  315. nid = memblock_get_region_node(r);
  316. usable_startpfn = memblock_region_memory_base_pfn(r);
  317. zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
  318. min(usable_startpfn, zone_movable_pfn[nid]) :
  319. usable_startpfn;
  320. }
  321. goto out2;
  322. }
  323. /*
  324. * If kernelcore=mirror is specified, ignore movablecore option
  325. */
  326. if (mirrored_kernelcore) {
  327. bool mem_below_4gb_not_mirrored = false;
  328. if (!memblock_has_mirror()) {
  329. pr_warn("The system has no mirror memory, ignore kernelcore=mirror.\n");
  330. goto out;
  331. }
  332. if (is_kdump_kernel()) {
  333. pr_warn("The system is under kdump, ignore kernelcore=mirror.\n");
  334. goto out;
  335. }
  336. for_each_mem_region(r) {
  337. if (memblock_is_mirror(r))
  338. continue;
  339. nid = memblock_get_region_node(r);
  340. usable_startpfn = memblock_region_memory_base_pfn(r);
  341. if (usable_startpfn < PHYS_PFN(SZ_4G)) {
  342. mem_below_4gb_not_mirrored = true;
  343. continue;
  344. }
  345. zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
  346. min(usable_startpfn, zone_movable_pfn[nid]) :
  347. usable_startpfn;
  348. }
  349. if (mem_below_4gb_not_mirrored)
  350. pr_warn("This configuration results in unmirrored kernel memory.\n");
  351. goto out2;
  352. }
  353. /*
  354. * If kernelcore=nn% or movablecore=nn% was specified, calculate the
  355. * amount of necessary memory.
  356. */
  357. if (required_kernelcore_percent)
  358. required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
  359. 10000UL;
  360. if (required_movablecore_percent)
  361. required_movablecore = (totalpages * 100 * required_movablecore_percent) /
  362. 10000UL;
  363. /*
  364. * If movablecore= was specified, calculate what size of
  365. * kernelcore that corresponds so that memory usable for
  366. * any allocation type is evenly spread. If both kernelcore
  367. * and movablecore are specified, then the value of kernelcore
  368. * will be used for required_kernelcore if it's greater than
  369. * what movablecore would have allowed.
  370. */
  371. if (required_movablecore) {
  372. unsigned long corepages;
  373. /*
  374. * Round-up so that ZONE_MOVABLE is at least as large as what
  375. * was requested by the user
  376. */
  377. required_movablecore =
  378. roundup(required_movablecore, MAX_ORDER_NR_PAGES);
  379. required_movablecore = min(totalpages, required_movablecore);
  380. corepages = totalpages - required_movablecore;
  381. required_kernelcore = max(required_kernelcore, corepages);
  382. }
  383. /*
  384. * If kernelcore was not specified or kernelcore size is larger
  385. * than totalpages, there is no ZONE_MOVABLE.
  386. */
  387. if (!required_kernelcore || required_kernelcore >= totalpages)
  388. goto out;
  389. /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
  390. usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
  391. restart:
  392. /* Spread kernelcore memory as evenly as possible throughout nodes */
  393. kernelcore_node = required_kernelcore / usable_nodes;
  394. for_each_node_state(nid, N_MEMORY) {
  395. unsigned long start_pfn, end_pfn;
  396. /*
  397. * Recalculate kernelcore_node if the division per node
  398. * now exceeds what is necessary to satisfy the requested
  399. * amount of memory for the kernel
  400. */
  401. if (required_kernelcore < kernelcore_node)
  402. kernelcore_node = required_kernelcore / usable_nodes;
  403. /*
  404. * As the map is walked, we track how much memory is usable
  405. * by the kernel using kernelcore_remaining. When it is
  406. * 0, the rest of the node is usable by ZONE_MOVABLE
  407. */
  408. kernelcore_remaining = kernelcore_node;
  409. /* Go through each range of PFNs within this node */
  410. for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
  411. unsigned long size_pages;
  412. start_pfn = max(start_pfn, zone_movable_pfn[nid]);
  413. if (start_pfn >= end_pfn)
  414. continue;
  415. /* Account for what is only usable for kernelcore */
  416. if (start_pfn < usable_startpfn) {
  417. unsigned long kernel_pages;
  418. kernel_pages = min(end_pfn, usable_startpfn)
  419. - start_pfn;
  420. kernelcore_remaining -= min(kernel_pages,
  421. kernelcore_remaining);
  422. required_kernelcore -= min(kernel_pages,
  423. required_kernelcore);
  424. /* Continue if range is now fully accounted */
  425. if (end_pfn <= usable_startpfn) {
  426. /*
  427. * Push zone_movable_pfn to the end so
  428. * that if we have to rebalance
  429. * kernelcore across nodes, we will
  430. * not double account here
  431. */
  432. zone_movable_pfn[nid] = end_pfn;
  433. continue;
  434. }
  435. start_pfn = usable_startpfn;
  436. }
  437. /*
  438. * The usable PFN range for ZONE_MOVABLE is from
  439. * start_pfn->end_pfn. Calculate size_pages as the
  440. * number of pages used as kernelcore
  441. */
  442. size_pages = end_pfn - start_pfn;
  443. if (size_pages > kernelcore_remaining)
  444. size_pages = kernelcore_remaining;
  445. zone_movable_pfn[nid] = start_pfn + size_pages;
  446. /*
  447. * Some kernelcore has been met, update counts and
  448. * break if the kernelcore for this node has been
  449. * satisfied
  450. */
  451. required_kernelcore -= min(required_kernelcore,
  452. size_pages);
  453. kernelcore_remaining -= size_pages;
  454. if (!kernelcore_remaining)
  455. break;
  456. }
  457. }
  458. /*
  459. * If there is still required_kernelcore, we do another pass with one
  460. * less node in the count. This will push zone_movable_pfn[nid] further
  461. * along on the nodes that still have memory until kernelcore is
  462. * satisfied
  463. */
  464. usable_nodes--;
  465. if (usable_nodes && required_kernelcore > usable_nodes)
  466. goto restart;
  467. out2:
  468. /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
  469. for (nid = 0; nid < MAX_NUMNODES; nid++) {
  470. unsigned long start_pfn, end_pfn;
  471. zone_movable_pfn[nid] =
  472. roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
  473. get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
  474. if (zone_movable_pfn[nid] >= end_pfn)
  475. zone_movable_pfn[nid] = 0;
  476. }
  477. out:
  478. /* restore the node_state */
  479. node_states[N_MEMORY] = saved_node_state;
  480. }
  481. void __meminit __init_single_page(struct page *page, unsigned long pfn,
  482. unsigned long zone, int nid)
  483. {
  484. mm_zero_struct_page(page);
  485. set_page_links(page, zone, nid, pfn);
  486. init_page_count(page);
  487. atomic_set(&page->_mapcount, -1);
  488. page_cpupid_reset_last(page);
  489. page_kasan_tag_reset(page);
  490. INIT_LIST_HEAD(&page->lru);
  491. #ifdef WANT_PAGE_VIRTUAL
  492. /* The shift won't overflow because ZONE_NORMAL is below 4G. */
  493. if (!is_highmem_idx(zone))
  494. set_page_address(page, __va(pfn << PAGE_SHIFT));
  495. #endif
  496. }
  497. #ifdef CONFIG_NUMA
  498. /*
  499. * During memory init memblocks map pfns to nids. The search is expensive and
  500. * this caches recent lookups. The implementation of __early_pfn_to_nid
  501. * treats start/end as pfns.
  502. */
  503. struct mminit_pfnnid_cache {
  504. unsigned long last_start;
  505. unsigned long last_end;
  506. int last_nid;
  507. };
  508. static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
  509. /*
  510. * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
  511. */
  512. static int __meminit __early_pfn_to_nid(unsigned long pfn,
  513. struct mminit_pfnnid_cache *state)
  514. {
  515. unsigned long start_pfn, end_pfn;
  516. int nid;
  517. if (state->last_start <= pfn && pfn < state->last_end)
  518. return state->last_nid;
  519. nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
  520. if (nid != NUMA_NO_NODE) {
  521. state->last_start = start_pfn;
  522. state->last_end = end_pfn;
  523. state->last_nid = nid;
  524. }
  525. return nid;
  526. }
  527. int __meminit early_pfn_to_nid(unsigned long pfn)
  528. {
  529. static DEFINE_SPINLOCK(early_pfn_lock);
  530. int nid;
  531. spin_lock(&early_pfn_lock);
  532. nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
  533. if (nid < 0)
  534. nid = first_online_node;
  535. spin_unlock(&early_pfn_lock);
  536. return nid;
  537. }
  538. int hashdist = HASHDIST_DEFAULT;
  539. static int __init set_hashdist(char *str)
  540. {
  541. if (!str)
  542. return 0;
  543. hashdist = simple_strtoul(str, &str, 0);
  544. return 1;
  545. }
  546. __setup("hashdist=", set_hashdist);
  547. static inline void fixup_hashdist(void)
  548. {
  549. if (num_node_state(N_MEMORY) == 1)
  550. hashdist = 0;
  551. }
  552. #else
  553. static inline void fixup_hashdist(void) {}
  554. #endif /* CONFIG_NUMA */
  555. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  556. static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
  557. {
  558. pgdat->first_deferred_pfn = ULONG_MAX;
  559. }
  560. /* Returns true if the struct page for the pfn is initialised */
  561. static inline bool __meminit early_page_initialised(unsigned long pfn, int nid)
  562. {
  563. if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
  564. return false;
  565. return true;
  566. }
  567. /*
  568. * Returns true when the remaining initialisation should be deferred until
  569. * later in the boot cycle when it can be parallelised.
  570. */
  571. static bool __meminit
  572. defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
  573. {
  574. static unsigned long prev_end_pfn, nr_initialised;
  575. if (early_page_ext_enabled())
  576. return false;
  577. /* Always populate low zones for address-constrained allocations */
  578. if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
  579. return false;
  580. if (NODE_DATA(nid)->first_deferred_pfn != ULONG_MAX)
  581. return true;
  582. /*
  583. * prev_end_pfn static that contains the end of previous zone
  584. * No need to protect because called very early in boot before smp_init.
  585. */
  586. if (prev_end_pfn != end_pfn) {
  587. prev_end_pfn = end_pfn;
  588. nr_initialised = 0;
  589. }
  590. /*
  591. * We start only with one section of pages, more pages are added as
  592. * needed until the rest of deferred pages are initialized.
  593. */
  594. nr_initialised++;
  595. if ((nr_initialised > PAGES_PER_SECTION) &&
  596. (pfn & (PAGES_PER_SECTION - 1)) == 0) {
  597. NODE_DATA(nid)->first_deferred_pfn = pfn;
  598. return true;
  599. }
  600. return false;
  601. }
  602. static void __meminit init_reserved_page(unsigned long pfn, int nid)
  603. {
  604. pg_data_t *pgdat;
  605. int zid;
  606. if (early_page_initialised(pfn, nid))
  607. return;
  608. pgdat = NODE_DATA(nid);
  609. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  610. struct zone *zone = &pgdat->node_zones[zid];
  611. if (zone_spans_pfn(zone, pfn))
  612. break;
  613. }
  614. __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
  615. }
  616. #else
  617. static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
  618. static inline bool early_page_initialised(unsigned long pfn, int nid)
  619. {
  620. return true;
  621. }
  622. static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
  623. {
  624. return false;
  625. }
  626. static inline void init_reserved_page(unsigned long pfn, int nid)
  627. {
  628. }
  629. #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
  630. /*
  631. * Initialised pages do not have PageReserved set. This function is
  632. * called for each range allocated by the bootmem allocator and
  633. * marks the pages PageReserved. The remaining valid pages are later
  634. * sent to the buddy page allocator.
  635. */
  636. void __meminit reserve_bootmem_region(phys_addr_t start,
  637. phys_addr_t end, int nid)
  638. {
  639. unsigned long start_pfn = PFN_DOWN(start);
  640. unsigned long end_pfn = PFN_UP(end);
  641. for (; start_pfn < end_pfn; start_pfn++) {
  642. if (pfn_valid(start_pfn)) {
  643. struct page *page = pfn_to_page(start_pfn);
  644. init_reserved_page(start_pfn, nid);
  645. /*
  646. * no need for atomic set_bit because the struct
  647. * page is not visible yet so nobody should
  648. * access it yet.
  649. */
  650. __SetPageReserved(page);
  651. }
  652. }
  653. }
  654. /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
  655. static bool __meminit
  656. overlap_memmap_init(unsigned long zone, unsigned long *pfn)
  657. {
  658. static struct memblock_region *r;
  659. if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
  660. if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
  661. for_each_mem_region(r) {
  662. if (*pfn < memblock_region_memory_end_pfn(r))
  663. break;
  664. }
  665. }
  666. if (*pfn >= memblock_region_memory_base_pfn(r) &&
  667. memblock_is_mirror(r)) {
  668. *pfn = memblock_region_memory_end_pfn(r);
  669. return true;
  670. }
  671. }
  672. return false;
  673. }
  674. /*
  675. * Only struct pages that correspond to ranges defined by memblock.memory
  676. * are zeroed and initialized by going through __init_single_page() during
  677. * memmap_init_zone_range().
  678. *
  679. * But, there could be struct pages that correspond to holes in
  680. * memblock.memory. This can happen because of the following reasons:
  681. * - physical memory bank size is not necessarily the exact multiple of the
  682. * arbitrary section size
  683. * - early reserved memory may not be listed in memblock.memory
  684. * - non-memory regions covered by the contigious flatmem mapping
  685. * - memory layouts defined with memmap= kernel parameter may not align
  686. * nicely with memmap sections
  687. *
  688. * Explicitly initialize those struct pages so that:
  689. * - PG_Reserved is set
  690. * - zone and node links point to zone and node that span the page if the
  691. * hole is in the middle of a zone
  692. * - zone and node links point to adjacent zone/node if the hole falls on
  693. * the zone boundary; the pages in such holes will be prepended to the
  694. * zone/node above the hole except for the trailing pages in the last
  695. * section that will be appended to the zone/node below.
  696. */
  697. static void __init init_unavailable_range(unsigned long spfn,
  698. unsigned long epfn,
  699. int zone, int node)
  700. {
  701. unsigned long pfn;
  702. u64 pgcnt = 0;
  703. for (pfn = spfn; pfn < epfn; pfn++) {
  704. if (!pfn_valid(pageblock_start_pfn(pfn))) {
  705. pfn = pageblock_end_pfn(pfn) - 1;
  706. continue;
  707. }
  708. __init_single_page(pfn_to_page(pfn), pfn, zone, node);
  709. __SetPageReserved(pfn_to_page(pfn));
  710. pgcnt++;
  711. }
  712. if (pgcnt)
  713. pr_info("On node %d, zone %s: %lld pages in unavailable ranges\n",
  714. node, zone_names[zone], pgcnt);
  715. }
  716. /*
  717. * Initially all pages are reserved - free ones are freed
  718. * up by memblock_free_all() once the early boot process is
  719. * done. Non-atomic initialization, single-pass.
  720. *
  721. * All aligned pageblocks are initialized to the specified migratetype
  722. * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
  723. * zone stats (e.g., nr_isolate_pageblock) are touched.
  724. */
  725. void __meminit memmap_init_range(unsigned long size, int nid, unsigned long zone,
  726. unsigned long start_pfn, unsigned long zone_end_pfn,
  727. enum meminit_context context,
  728. struct vmem_altmap *altmap, int migratetype)
  729. {
  730. unsigned long pfn, end_pfn = start_pfn + size;
  731. struct page *page;
  732. if (highest_memmap_pfn < end_pfn - 1)
  733. highest_memmap_pfn = end_pfn - 1;
  734. #ifdef CONFIG_ZONE_DEVICE
  735. /*
  736. * Honor reservation requested by the driver for this ZONE_DEVICE
  737. * memory. We limit the total number of pages to initialize to just
  738. * those that might contain the memory mapping. We will defer the
  739. * ZONE_DEVICE page initialization until after we have released
  740. * the hotplug lock.
  741. */
  742. if (zone == ZONE_DEVICE) {
  743. if (!altmap)
  744. return;
  745. if (start_pfn == altmap->base_pfn)
  746. start_pfn += altmap->reserve;
  747. end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
  748. }
  749. #endif
  750. for (pfn = start_pfn; pfn < end_pfn; ) {
  751. /*
  752. * There can be holes in boot-time mem_map[]s handed to this
  753. * function. They do not exist on hotplugged memory.
  754. */
  755. if (context == MEMINIT_EARLY) {
  756. if (overlap_memmap_init(zone, &pfn))
  757. continue;
  758. if (defer_init(nid, pfn, zone_end_pfn)) {
  759. deferred_struct_pages = true;
  760. break;
  761. }
  762. }
  763. page = pfn_to_page(pfn);
  764. __init_single_page(page, pfn, zone, nid);
  765. if (context == MEMINIT_HOTPLUG) {
  766. #ifdef CONFIG_ZONE_DEVICE
  767. if (zone == ZONE_DEVICE)
  768. __SetPageReserved(page);
  769. else
  770. #endif
  771. __SetPageOffline(page);
  772. }
  773. /*
  774. * Usually, we want to mark the pageblock MIGRATE_MOVABLE,
  775. * such that unmovable allocations won't be scattered all
  776. * over the place during system boot.
  777. */
  778. if (pageblock_aligned(pfn)) {
  779. set_pageblock_migratetype(page, migratetype);
  780. cond_resched();
  781. }
  782. pfn++;
  783. }
  784. }
  785. static void __init memmap_init_zone_range(struct zone *zone,
  786. unsigned long start_pfn,
  787. unsigned long end_pfn,
  788. unsigned long *hole_pfn)
  789. {
  790. unsigned long zone_start_pfn = zone->zone_start_pfn;
  791. unsigned long zone_end_pfn = zone_start_pfn + zone->spanned_pages;
  792. int nid = zone_to_nid(zone), zone_id = zone_idx(zone);
  793. start_pfn = clamp(start_pfn, zone_start_pfn, zone_end_pfn);
  794. end_pfn = clamp(end_pfn, zone_start_pfn, zone_end_pfn);
  795. if (start_pfn >= end_pfn)
  796. return;
  797. memmap_init_range(end_pfn - start_pfn, nid, zone_id, start_pfn,
  798. zone_end_pfn, MEMINIT_EARLY, NULL, MIGRATE_MOVABLE);
  799. if (*hole_pfn < start_pfn)
  800. init_unavailable_range(*hole_pfn, start_pfn, zone_id, nid);
  801. *hole_pfn = end_pfn;
  802. }
  803. static void __init memmap_init(void)
  804. {
  805. unsigned long start_pfn, end_pfn;
  806. unsigned long hole_pfn = 0;
  807. int i, j, zone_id = 0, nid;
  808. for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
  809. struct pglist_data *node = NODE_DATA(nid);
  810. for (j = 0; j < MAX_NR_ZONES; j++) {
  811. struct zone *zone = node->node_zones + j;
  812. if (!populated_zone(zone))
  813. continue;
  814. memmap_init_zone_range(zone, start_pfn, end_pfn,
  815. &hole_pfn);
  816. zone_id = j;
  817. }
  818. }
  819. #ifdef CONFIG_SPARSEMEM
  820. /*
  821. * Initialize the memory map for hole in the range [memory_end,
  822. * section_end].
  823. * Append the pages in this hole to the highest zone in the last
  824. * node.
  825. * The call to init_unavailable_range() is outside the ifdef to
  826. * silence the compiler warining about zone_id set but not used;
  827. * for FLATMEM it is a nop anyway
  828. */
  829. end_pfn = round_up(end_pfn, PAGES_PER_SECTION);
  830. if (hole_pfn < end_pfn)
  831. #endif
  832. init_unavailable_range(hole_pfn, end_pfn, zone_id, nid);
  833. }
  834. #ifdef CONFIG_ZONE_DEVICE
  835. static void __ref __init_zone_device_page(struct page *page, unsigned long pfn,
  836. unsigned long zone_idx, int nid,
  837. struct dev_pagemap *pgmap)
  838. {
  839. __init_single_page(page, pfn, zone_idx, nid);
  840. /*
  841. * Mark page reserved as it will need to wait for onlining
  842. * phase for it to be fully associated with a zone.
  843. *
  844. * We can use the non-atomic __set_bit operation for setting
  845. * the flag as we are still initializing the pages.
  846. */
  847. __SetPageReserved(page);
  848. /*
  849. * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
  850. * and zone_device_data. It is a bug if a ZONE_DEVICE page is
  851. * ever freed or placed on a driver-private list.
  852. */
  853. page->pgmap = pgmap;
  854. page->zone_device_data = NULL;
  855. /*
  856. * Mark the block movable so that blocks are reserved for
  857. * movable at startup. This will force kernel allocations
  858. * to reserve their blocks rather than leaking throughout
  859. * the address space during boot when many long-lived
  860. * kernel allocations are made.
  861. *
  862. * Please note that MEMINIT_HOTPLUG path doesn't clear memmap
  863. * because this is done early in section_activate()
  864. */
  865. if (pageblock_aligned(pfn)) {
  866. set_pageblock_migratetype(page, MIGRATE_MOVABLE);
  867. cond_resched();
  868. }
  869. /*
  870. * ZONE_DEVICE pages are released directly to the driver page allocator
  871. * which will set the page count to 1 when allocating the page.
  872. */
  873. if (pgmap->type == MEMORY_DEVICE_PRIVATE ||
  874. pgmap->type == MEMORY_DEVICE_COHERENT)
  875. set_page_count(page, 0);
  876. }
  877. /*
  878. * With compound page geometry and when struct pages are stored in ram most
  879. * tail pages are reused. Consequently, the amount of unique struct pages to
  880. * initialize is a lot smaller that the total amount of struct pages being
  881. * mapped. This is a paired / mild layering violation with explicit knowledge
  882. * of how the sparse_vmemmap internals handle compound pages in the lack
  883. * of an altmap. See vmemmap_populate_compound_pages().
  884. */
  885. static inline unsigned long compound_nr_pages(struct vmem_altmap *altmap,
  886. struct dev_pagemap *pgmap)
  887. {
  888. if (!vmemmap_can_optimize(altmap, pgmap))
  889. return pgmap_vmemmap_nr(pgmap);
  890. return VMEMMAP_RESERVE_NR * (PAGE_SIZE / sizeof(struct page));
  891. }
  892. static void __ref memmap_init_compound(struct page *head,
  893. unsigned long head_pfn,
  894. unsigned long zone_idx, int nid,
  895. struct dev_pagemap *pgmap,
  896. unsigned long nr_pages)
  897. {
  898. unsigned long pfn, end_pfn = head_pfn + nr_pages;
  899. unsigned int order = pgmap->vmemmap_shift;
  900. __SetPageHead(head);
  901. for (pfn = head_pfn + 1; pfn < end_pfn; pfn++) {
  902. struct page *page = pfn_to_page(pfn);
  903. __init_zone_device_page(page, pfn, zone_idx, nid, pgmap);
  904. prep_compound_tail(head, pfn - head_pfn);
  905. set_page_count(page, 0);
  906. /*
  907. * The first tail page stores important compound page info.
  908. * Call prep_compound_head() after the first tail page has
  909. * been initialized, to not have the data overwritten.
  910. */
  911. if (pfn == head_pfn + 1)
  912. prep_compound_head(head, order);
  913. }
  914. }
  915. void __ref memmap_init_zone_device(struct zone *zone,
  916. unsigned long start_pfn,
  917. unsigned long nr_pages,
  918. struct dev_pagemap *pgmap)
  919. {
  920. unsigned long pfn, end_pfn = start_pfn + nr_pages;
  921. struct pglist_data *pgdat = zone->zone_pgdat;
  922. struct vmem_altmap *altmap = pgmap_altmap(pgmap);
  923. unsigned int pfns_per_compound = pgmap_vmemmap_nr(pgmap);
  924. unsigned long zone_idx = zone_idx(zone);
  925. unsigned long start = jiffies;
  926. int nid = pgdat->node_id;
  927. if (WARN_ON_ONCE(!pgmap || zone_idx != ZONE_DEVICE))
  928. return;
  929. /*
  930. * The call to memmap_init should have already taken care
  931. * of the pages reserved for the memmap, so we can just jump to
  932. * the end of that region and start processing the device pages.
  933. */
  934. if (altmap) {
  935. start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
  936. nr_pages = end_pfn - start_pfn;
  937. }
  938. for (pfn = start_pfn; pfn < end_pfn; pfn += pfns_per_compound) {
  939. struct page *page = pfn_to_page(pfn);
  940. __init_zone_device_page(page, pfn, zone_idx, nid, pgmap);
  941. if (pfns_per_compound == 1)
  942. continue;
  943. memmap_init_compound(page, pfn, zone_idx, nid, pgmap,
  944. compound_nr_pages(altmap, pgmap));
  945. }
  946. pr_debug("%s initialised %lu pages in %ums\n", __func__,
  947. nr_pages, jiffies_to_msecs(jiffies - start));
  948. }
  949. #endif
  950. /*
  951. * The zone ranges provided by the architecture do not include ZONE_MOVABLE
  952. * because it is sized independent of architecture. Unlike the other zones,
  953. * the starting point for ZONE_MOVABLE is not fixed. It may be different
  954. * in each node depending on the size of each node and how evenly kernelcore
  955. * is distributed. This helper function adjusts the zone ranges
  956. * provided by the architecture for a given node by using the end of the
  957. * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
  958. * zones within a node are in order of monotonic increases memory addresses
  959. */
  960. static void __init adjust_zone_range_for_zone_movable(int nid,
  961. unsigned long zone_type,
  962. unsigned long node_end_pfn,
  963. unsigned long *zone_start_pfn,
  964. unsigned long *zone_end_pfn)
  965. {
  966. /* Only adjust if ZONE_MOVABLE is on this node */
  967. if (zone_movable_pfn[nid]) {
  968. /* Size ZONE_MOVABLE */
  969. if (zone_type == ZONE_MOVABLE) {
  970. *zone_start_pfn = zone_movable_pfn[nid];
  971. *zone_end_pfn = min(node_end_pfn,
  972. arch_zone_highest_possible_pfn[movable_zone]);
  973. /* Adjust for ZONE_MOVABLE starting within this range */
  974. } else if (!mirrored_kernelcore &&
  975. *zone_start_pfn < zone_movable_pfn[nid] &&
  976. *zone_end_pfn > zone_movable_pfn[nid]) {
  977. *zone_end_pfn = zone_movable_pfn[nid];
  978. /* Check if this whole range is within ZONE_MOVABLE */
  979. } else if (*zone_start_pfn >= zone_movable_pfn[nid])
  980. *zone_start_pfn = *zone_end_pfn;
  981. }
  982. }
  983. /*
  984. * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
  985. * then all holes in the requested range will be accounted for.
  986. */
  987. static unsigned long __init __absent_pages_in_range(int nid,
  988. unsigned long range_start_pfn,
  989. unsigned long range_end_pfn)
  990. {
  991. unsigned long nr_absent = range_end_pfn - range_start_pfn;
  992. unsigned long start_pfn, end_pfn;
  993. int i;
  994. for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
  995. start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
  996. end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
  997. nr_absent -= end_pfn - start_pfn;
  998. }
  999. return nr_absent;
  1000. }
  1001. /**
  1002. * absent_pages_in_range - Return number of page frames in holes within a range
  1003. * @start_pfn: The start PFN to start searching for holes
  1004. * @end_pfn: The end PFN to stop searching for holes
  1005. *
  1006. * Return: the number of pages frames in memory holes within a range.
  1007. */
  1008. unsigned long __init absent_pages_in_range(unsigned long start_pfn,
  1009. unsigned long end_pfn)
  1010. {
  1011. return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
  1012. }
  1013. /* Return the number of page frames in holes in a zone on a node */
  1014. static unsigned long __init zone_absent_pages_in_node(int nid,
  1015. unsigned long zone_type,
  1016. unsigned long zone_start_pfn,
  1017. unsigned long zone_end_pfn)
  1018. {
  1019. unsigned long nr_absent;
  1020. /* zone is empty, we don't have any absent pages */
  1021. if (zone_start_pfn == zone_end_pfn)
  1022. return 0;
  1023. nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
  1024. /*
  1025. * ZONE_MOVABLE handling.
  1026. * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
  1027. * and vice versa.
  1028. */
  1029. if (mirrored_kernelcore && zone_movable_pfn[nid]) {
  1030. unsigned long start_pfn, end_pfn;
  1031. struct memblock_region *r;
  1032. for_each_mem_region(r) {
  1033. start_pfn = clamp(memblock_region_memory_base_pfn(r),
  1034. zone_start_pfn, zone_end_pfn);
  1035. end_pfn = clamp(memblock_region_memory_end_pfn(r),
  1036. zone_start_pfn, zone_end_pfn);
  1037. if (zone_type == ZONE_MOVABLE &&
  1038. memblock_is_mirror(r))
  1039. nr_absent += end_pfn - start_pfn;
  1040. if (zone_type == ZONE_NORMAL &&
  1041. !memblock_is_mirror(r))
  1042. nr_absent += end_pfn - start_pfn;
  1043. }
  1044. }
  1045. return nr_absent;
  1046. }
  1047. /*
  1048. * Return the number of pages a zone spans in a node, including holes
  1049. * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
  1050. */
  1051. static unsigned long __init zone_spanned_pages_in_node(int nid,
  1052. unsigned long zone_type,
  1053. unsigned long node_start_pfn,
  1054. unsigned long node_end_pfn,
  1055. unsigned long *zone_start_pfn,
  1056. unsigned long *zone_end_pfn)
  1057. {
  1058. unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
  1059. unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
  1060. /* Get the start and end of the zone */
  1061. *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
  1062. *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
  1063. adjust_zone_range_for_zone_movable(nid, zone_type, node_end_pfn,
  1064. zone_start_pfn, zone_end_pfn);
  1065. /* Check that this node has pages within the zone's required range */
  1066. if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
  1067. return 0;
  1068. /* Move the zone boundaries inside the node if necessary */
  1069. *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
  1070. *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
  1071. /* Return the spanned pages */
  1072. return *zone_end_pfn - *zone_start_pfn;
  1073. }
  1074. static void __init reset_memoryless_node_totalpages(struct pglist_data *pgdat)
  1075. {
  1076. struct zone *z;
  1077. for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++) {
  1078. z->zone_start_pfn = 0;
  1079. z->spanned_pages = 0;
  1080. z->present_pages = 0;
  1081. #if defined(CONFIG_MEMORY_HOTPLUG)
  1082. z->present_early_pages = 0;
  1083. #endif
  1084. }
  1085. pgdat->node_spanned_pages = 0;
  1086. pgdat->node_present_pages = 0;
  1087. pr_debug("On node %d totalpages: 0\n", pgdat->node_id);
  1088. }
  1089. static void __init calc_nr_kernel_pages(void)
  1090. {
  1091. unsigned long start_pfn, end_pfn;
  1092. phys_addr_t start_addr, end_addr;
  1093. u64 u;
  1094. #ifdef CONFIG_HIGHMEM
  1095. unsigned long high_zone_low = arch_zone_lowest_possible_pfn[ZONE_HIGHMEM];
  1096. #endif
  1097. for_each_free_mem_range(u, NUMA_NO_NODE, MEMBLOCK_NONE, &start_addr, &end_addr, NULL) {
  1098. start_pfn = PFN_UP(start_addr);
  1099. end_pfn = PFN_DOWN(end_addr);
  1100. if (start_pfn < end_pfn) {
  1101. nr_all_pages += end_pfn - start_pfn;
  1102. #ifdef CONFIG_HIGHMEM
  1103. start_pfn = clamp(start_pfn, 0, high_zone_low);
  1104. end_pfn = clamp(end_pfn, 0, high_zone_low);
  1105. #endif
  1106. nr_kernel_pages += end_pfn - start_pfn;
  1107. }
  1108. }
  1109. }
  1110. static void __init calculate_node_totalpages(struct pglist_data *pgdat,
  1111. unsigned long node_start_pfn,
  1112. unsigned long node_end_pfn)
  1113. {
  1114. unsigned long realtotalpages = 0, totalpages = 0;
  1115. enum zone_type i;
  1116. for (i = 0; i < MAX_NR_ZONES; i++) {
  1117. struct zone *zone = pgdat->node_zones + i;
  1118. unsigned long zone_start_pfn, zone_end_pfn;
  1119. unsigned long spanned, absent;
  1120. unsigned long real_size;
  1121. spanned = zone_spanned_pages_in_node(pgdat->node_id, i,
  1122. node_start_pfn,
  1123. node_end_pfn,
  1124. &zone_start_pfn,
  1125. &zone_end_pfn);
  1126. absent = zone_absent_pages_in_node(pgdat->node_id, i,
  1127. zone_start_pfn,
  1128. zone_end_pfn);
  1129. real_size = spanned - absent;
  1130. if (spanned)
  1131. zone->zone_start_pfn = zone_start_pfn;
  1132. else
  1133. zone->zone_start_pfn = 0;
  1134. zone->spanned_pages = spanned;
  1135. zone->present_pages = real_size;
  1136. #if defined(CONFIG_MEMORY_HOTPLUG)
  1137. zone->present_early_pages = real_size;
  1138. #endif
  1139. totalpages += spanned;
  1140. realtotalpages += real_size;
  1141. }
  1142. pgdat->node_spanned_pages = totalpages;
  1143. pgdat->node_present_pages = realtotalpages;
  1144. pr_debug("On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
  1145. }
  1146. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1147. static void pgdat_init_split_queue(struct pglist_data *pgdat)
  1148. {
  1149. struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
  1150. spin_lock_init(&ds_queue->split_queue_lock);
  1151. INIT_LIST_HEAD(&ds_queue->split_queue);
  1152. ds_queue->split_queue_len = 0;
  1153. }
  1154. #else
  1155. static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
  1156. #endif
  1157. #ifdef CONFIG_COMPACTION
  1158. static void pgdat_init_kcompactd(struct pglist_data *pgdat)
  1159. {
  1160. init_waitqueue_head(&pgdat->kcompactd_wait);
  1161. }
  1162. #else
  1163. static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
  1164. #endif
  1165. static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
  1166. {
  1167. int i;
  1168. pgdat_resize_init(pgdat);
  1169. pgdat_kswapd_lock_init(pgdat);
  1170. pgdat_init_split_queue(pgdat);
  1171. pgdat_init_kcompactd(pgdat);
  1172. init_waitqueue_head(&pgdat->kswapd_wait);
  1173. init_waitqueue_head(&pgdat->pfmemalloc_wait);
  1174. for (i = 0; i < NR_VMSCAN_THROTTLE; i++)
  1175. init_waitqueue_head(&pgdat->reclaim_wait[i]);
  1176. pgdat_page_ext_init(pgdat);
  1177. lruvec_init(&pgdat->__lruvec);
  1178. }
  1179. static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
  1180. unsigned long remaining_pages)
  1181. {
  1182. atomic_long_set(&zone->managed_pages, remaining_pages);
  1183. zone_set_nid(zone, nid);
  1184. zone->name = zone_names[idx];
  1185. zone->zone_pgdat = NODE_DATA(nid);
  1186. spin_lock_init(&zone->lock);
  1187. zone_seqlock_init(zone);
  1188. zone_pcp_init(zone);
  1189. }
  1190. static void __meminit zone_init_free_lists(struct zone *zone)
  1191. {
  1192. unsigned int order, t;
  1193. for_each_migratetype_order(order, t) {
  1194. INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
  1195. zone->free_area[order].nr_free = 0;
  1196. }
  1197. #ifdef CONFIG_UNACCEPTED_MEMORY
  1198. INIT_LIST_HEAD(&zone->unaccepted_pages);
  1199. #endif
  1200. }
  1201. void __meminit init_currently_empty_zone(struct zone *zone,
  1202. unsigned long zone_start_pfn,
  1203. unsigned long size)
  1204. {
  1205. struct pglist_data *pgdat = zone->zone_pgdat;
  1206. int zone_idx = zone_idx(zone) + 1;
  1207. if (zone_idx > pgdat->nr_zones)
  1208. pgdat->nr_zones = zone_idx;
  1209. zone->zone_start_pfn = zone_start_pfn;
  1210. mminit_dprintk(MMINIT_TRACE, "memmap_init",
  1211. "Initialising map node %d zone %lu pfns %lu -> %lu\n",
  1212. pgdat->node_id,
  1213. (unsigned long)zone_idx(zone),
  1214. zone_start_pfn, (zone_start_pfn + size));
  1215. zone_init_free_lists(zone);
  1216. zone->initialized = 1;
  1217. }
  1218. #ifndef CONFIG_SPARSEMEM
  1219. /*
  1220. * Calculate the size of the zone->blockflags rounded to an unsigned long
  1221. * Start by making sure zonesize is a multiple of pageblock_order by rounding
  1222. * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
  1223. * round what is now in bits to nearest long in bits, then return it in
  1224. * bytes.
  1225. */
  1226. static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
  1227. {
  1228. unsigned long usemapsize;
  1229. zonesize += zone_start_pfn & (pageblock_nr_pages-1);
  1230. usemapsize = roundup(zonesize, pageblock_nr_pages);
  1231. usemapsize = usemapsize >> pageblock_order;
  1232. usemapsize *= NR_PAGEBLOCK_BITS;
  1233. usemapsize = roundup(usemapsize, BITS_PER_LONG);
  1234. return usemapsize / BITS_PER_BYTE;
  1235. }
  1236. static void __ref setup_usemap(struct zone *zone)
  1237. {
  1238. unsigned long usemapsize = usemap_size(zone->zone_start_pfn,
  1239. zone->spanned_pages);
  1240. zone->pageblock_flags = NULL;
  1241. if (usemapsize) {
  1242. zone->pageblock_flags =
  1243. memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
  1244. zone_to_nid(zone));
  1245. if (!zone->pageblock_flags)
  1246. panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
  1247. usemapsize, zone->name, zone_to_nid(zone));
  1248. }
  1249. }
  1250. #else
  1251. static inline void setup_usemap(struct zone *zone) {}
  1252. #endif /* CONFIG_SPARSEMEM */
  1253. #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
  1254. /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
  1255. void __init set_pageblock_order(void)
  1256. {
  1257. unsigned int order = MAX_PAGE_ORDER;
  1258. /* Check that pageblock_nr_pages has not already been setup */
  1259. if (pageblock_order)
  1260. return;
  1261. /* Don't let pageblocks exceed the maximum allocation granularity. */
  1262. if (HPAGE_SHIFT > PAGE_SHIFT && HUGETLB_PAGE_ORDER < order)
  1263. order = HUGETLB_PAGE_ORDER;
  1264. /*
  1265. * Assume the largest contiguous order of interest is a huge page.
  1266. * This value may be variable depending on boot parameters on powerpc.
  1267. */
  1268. pageblock_order = order;
  1269. }
  1270. #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
  1271. /*
  1272. * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
  1273. * is unused as pageblock_order is set at compile-time. See
  1274. * include/linux/pageblock-flags.h for the values of pageblock_order based on
  1275. * the kernel config
  1276. */
  1277. void __init set_pageblock_order(void)
  1278. {
  1279. }
  1280. #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
  1281. /*
  1282. * Set up the zone data structures
  1283. * - init pgdat internals
  1284. * - init all zones belonging to this node
  1285. *
  1286. * NOTE: this function is only called during memory hotplug
  1287. */
  1288. #ifdef CONFIG_MEMORY_HOTPLUG
  1289. void __ref free_area_init_core_hotplug(struct pglist_data *pgdat)
  1290. {
  1291. int nid = pgdat->node_id;
  1292. enum zone_type z;
  1293. int cpu;
  1294. pgdat_init_internals(pgdat);
  1295. if (pgdat->per_cpu_nodestats == &boot_nodestats)
  1296. pgdat->per_cpu_nodestats = alloc_percpu(struct per_cpu_nodestat);
  1297. /*
  1298. * Reset the nr_zones, order and highest_zoneidx before reuse.
  1299. * Note that kswapd will init kswapd_highest_zoneidx properly
  1300. * when it starts in the near future.
  1301. */
  1302. pgdat->nr_zones = 0;
  1303. pgdat->kswapd_order = 0;
  1304. pgdat->kswapd_highest_zoneidx = 0;
  1305. pgdat->node_start_pfn = 0;
  1306. pgdat->node_present_pages = 0;
  1307. for_each_online_cpu(cpu) {
  1308. struct per_cpu_nodestat *p;
  1309. p = per_cpu_ptr(pgdat->per_cpu_nodestats, cpu);
  1310. memset(p, 0, sizeof(*p));
  1311. }
  1312. /*
  1313. * When memory is hot-added, all the memory is in offline state. So
  1314. * clear all zones' present_pages and managed_pages because they will
  1315. * be updated in online_pages() and offline_pages().
  1316. */
  1317. for (z = 0; z < MAX_NR_ZONES; z++) {
  1318. struct zone *zone = pgdat->node_zones + z;
  1319. zone->present_pages = 0;
  1320. zone_init_internals(zone, z, nid, 0);
  1321. }
  1322. }
  1323. #endif
  1324. static void __init free_area_init_core(struct pglist_data *pgdat)
  1325. {
  1326. enum zone_type j;
  1327. int nid = pgdat->node_id;
  1328. pgdat_init_internals(pgdat);
  1329. pgdat->per_cpu_nodestats = &boot_nodestats;
  1330. for (j = 0; j < MAX_NR_ZONES; j++) {
  1331. struct zone *zone = pgdat->node_zones + j;
  1332. unsigned long size = zone->spanned_pages;
  1333. /*
  1334. * Initialize zone->managed_pages as 0 , it will be reset
  1335. * when memblock allocator frees pages into buddy system.
  1336. */
  1337. zone_init_internals(zone, j, nid, zone->present_pages);
  1338. if (!size)
  1339. continue;
  1340. setup_usemap(zone);
  1341. init_currently_empty_zone(zone, zone->zone_start_pfn, size);
  1342. }
  1343. }
  1344. void __init *memmap_alloc(phys_addr_t size, phys_addr_t align,
  1345. phys_addr_t min_addr, int nid, bool exact_nid)
  1346. {
  1347. void *ptr;
  1348. if (exact_nid)
  1349. ptr = memblock_alloc_exact_nid_raw(size, align, min_addr,
  1350. MEMBLOCK_ALLOC_ACCESSIBLE,
  1351. nid);
  1352. else
  1353. ptr = memblock_alloc_try_nid_raw(size, align, min_addr,
  1354. MEMBLOCK_ALLOC_ACCESSIBLE,
  1355. nid);
  1356. if (ptr && size > 0)
  1357. page_init_poison(ptr, size);
  1358. return ptr;
  1359. }
  1360. #ifdef CONFIG_FLATMEM
  1361. static void __init alloc_node_mem_map(struct pglist_data *pgdat)
  1362. {
  1363. unsigned long start, offset, size, end;
  1364. struct page *map;
  1365. /* Skip empty nodes */
  1366. if (!pgdat->node_spanned_pages)
  1367. return;
  1368. start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
  1369. offset = pgdat->node_start_pfn - start;
  1370. /*
  1371. * The zone's endpoints aren't required to be MAX_PAGE_ORDER
  1372. * aligned but the node_mem_map endpoints must be in order
  1373. * for the buddy allocator to function correctly.
  1374. */
  1375. end = ALIGN(pgdat_end_pfn(pgdat), MAX_ORDER_NR_PAGES);
  1376. size = (end - start) * sizeof(struct page);
  1377. map = memmap_alloc(size, SMP_CACHE_BYTES, MEMBLOCK_LOW_LIMIT,
  1378. pgdat->node_id, false);
  1379. if (!map)
  1380. panic("Failed to allocate %ld bytes for node %d memory map\n",
  1381. size, pgdat->node_id);
  1382. pgdat->node_mem_map = map + offset;
  1383. memmap_boot_pages_add(DIV_ROUND_UP(size, PAGE_SIZE));
  1384. pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
  1385. __func__, pgdat->node_id, (unsigned long)pgdat,
  1386. (unsigned long)pgdat->node_mem_map);
  1387. #ifndef CONFIG_NUMA
  1388. /* the global mem_map is just set as node 0's */
  1389. if (pgdat == NODE_DATA(0)) {
  1390. mem_map = NODE_DATA(0)->node_mem_map;
  1391. if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
  1392. mem_map -= offset;
  1393. }
  1394. #endif
  1395. }
  1396. #else
  1397. static inline void alloc_node_mem_map(struct pglist_data *pgdat) { }
  1398. #endif /* CONFIG_FLATMEM */
  1399. /**
  1400. * get_pfn_range_for_nid - Return the start and end page frames for a node
  1401. * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
  1402. * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
  1403. * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
  1404. *
  1405. * It returns the start and end page frame of a node based on information
  1406. * provided by memblock_set_node(). If called for a node
  1407. * with no available memory, the start and end PFNs will be 0.
  1408. */
  1409. void __init get_pfn_range_for_nid(unsigned int nid,
  1410. unsigned long *start_pfn, unsigned long *end_pfn)
  1411. {
  1412. unsigned long this_start_pfn, this_end_pfn;
  1413. int i;
  1414. *start_pfn = -1UL;
  1415. *end_pfn = 0;
  1416. for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
  1417. *start_pfn = min(*start_pfn, this_start_pfn);
  1418. *end_pfn = max(*end_pfn, this_end_pfn);
  1419. }
  1420. if (*start_pfn == -1UL)
  1421. *start_pfn = 0;
  1422. }
  1423. static void __init free_area_init_node(int nid)
  1424. {
  1425. pg_data_t *pgdat = NODE_DATA(nid);
  1426. unsigned long start_pfn = 0;
  1427. unsigned long end_pfn = 0;
  1428. /* pg_data_t should be reset to zero when it's allocated */
  1429. WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx);
  1430. get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
  1431. pgdat->node_id = nid;
  1432. pgdat->node_start_pfn = start_pfn;
  1433. pgdat->per_cpu_nodestats = NULL;
  1434. if (start_pfn != end_pfn) {
  1435. pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
  1436. (u64)start_pfn << PAGE_SHIFT,
  1437. end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
  1438. calculate_node_totalpages(pgdat, start_pfn, end_pfn);
  1439. } else {
  1440. pr_info("Initmem setup node %d as memoryless\n", nid);
  1441. reset_memoryless_node_totalpages(pgdat);
  1442. }
  1443. alloc_node_mem_map(pgdat);
  1444. pgdat_set_deferred_range(pgdat);
  1445. free_area_init_core(pgdat);
  1446. lru_gen_init_pgdat(pgdat);
  1447. }
  1448. /* Any regular or high memory on that node ? */
  1449. static void __init check_for_memory(pg_data_t *pgdat)
  1450. {
  1451. enum zone_type zone_type;
  1452. for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
  1453. struct zone *zone = &pgdat->node_zones[zone_type];
  1454. if (populated_zone(zone)) {
  1455. if (IS_ENABLED(CONFIG_HIGHMEM))
  1456. node_set_state(pgdat->node_id, N_HIGH_MEMORY);
  1457. if (zone_type <= ZONE_NORMAL)
  1458. node_set_state(pgdat->node_id, N_NORMAL_MEMORY);
  1459. break;
  1460. }
  1461. }
  1462. }
  1463. #if MAX_NUMNODES > 1
  1464. /*
  1465. * Figure out the number of possible node ids.
  1466. */
  1467. void __init setup_nr_node_ids(void)
  1468. {
  1469. unsigned int highest;
  1470. highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
  1471. nr_node_ids = highest + 1;
  1472. }
  1473. #endif
  1474. /*
  1475. * Some architectures, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For
  1476. * such cases we allow max_zone_pfn sorted in the descending order
  1477. */
  1478. static bool arch_has_descending_max_zone_pfns(void)
  1479. {
  1480. return IS_ENABLED(CONFIG_ARC) && !IS_ENABLED(CONFIG_ARC_HAS_PAE40);
  1481. }
  1482. /**
  1483. * free_area_init - Initialise all pg_data_t and zone data
  1484. * @max_zone_pfn: an array of max PFNs for each zone
  1485. *
  1486. * This will call free_area_init_node() for each active node in the system.
  1487. * Using the page ranges provided by memblock_set_node(), the size of each
  1488. * zone in each node and their holes is calculated. If the maximum PFN
  1489. * between two adjacent zones match, it is assumed that the zone is empty.
  1490. * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
  1491. * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
  1492. * starts where the previous one ended. For example, ZONE_DMA32 starts
  1493. * at arch_max_dma_pfn.
  1494. */
  1495. void __init free_area_init(unsigned long *max_zone_pfn)
  1496. {
  1497. unsigned long start_pfn, end_pfn;
  1498. int i, nid, zone;
  1499. bool descending;
  1500. /* Record where the zone boundaries are */
  1501. memset(arch_zone_lowest_possible_pfn, 0,
  1502. sizeof(arch_zone_lowest_possible_pfn));
  1503. memset(arch_zone_highest_possible_pfn, 0,
  1504. sizeof(arch_zone_highest_possible_pfn));
  1505. start_pfn = PHYS_PFN(memblock_start_of_DRAM());
  1506. descending = arch_has_descending_max_zone_pfns();
  1507. for (i = 0; i < MAX_NR_ZONES; i++) {
  1508. if (descending)
  1509. zone = MAX_NR_ZONES - i - 1;
  1510. else
  1511. zone = i;
  1512. if (zone == ZONE_MOVABLE)
  1513. continue;
  1514. end_pfn = max(max_zone_pfn[zone], start_pfn);
  1515. arch_zone_lowest_possible_pfn[zone] = start_pfn;
  1516. arch_zone_highest_possible_pfn[zone] = end_pfn;
  1517. start_pfn = end_pfn;
  1518. }
  1519. /* Find the PFNs that ZONE_MOVABLE begins at in each node */
  1520. memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
  1521. find_zone_movable_pfns_for_nodes();
  1522. /* Print out the zone ranges */
  1523. pr_info("Zone ranges:\n");
  1524. for (i = 0; i < MAX_NR_ZONES; i++) {
  1525. if (i == ZONE_MOVABLE)
  1526. continue;
  1527. pr_info(" %-8s ", zone_names[i]);
  1528. if (arch_zone_lowest_possible_pfn[i] ==
  1529. arch_zone_highest_possible_pfn[i])
  1530. pr_cont("empty\n");
  1531. else
  1532. pr_cont("[mem %#018Lx-%#018Lx]\n",
  1533. (u64)arch_zone_lowest_possible_pfn[i]
  1534. << PAGE_SHIFT,
  1535. ((u64)arch_zone_highest_possible_pfn[i]
  1536. << PAGE_SHIFT) - 1);
  1537. }
  1538. /* Print out the PFNs ZONE_MOVABLE begins at in each node */
  1539. pr_info("Movable zone start for each node\n");
  1540. for (i = 0; i < MAX_NUMNODES; i++) {
  1541. if (zone_movable_pfn[i])
  1542. pr_info(" Node %d: %#018Lx\n", i,
  1543. (u64)zone_movable_pfn[i] << PAGE_SHIFT);
  1544. }
  1545. /*
  1546. * Print out the early node map, and initialize the
  1547. * subsection-map relative to active online memory ranges to
  1548. * enable future "sub-section" extensions of the memory map.
  1549. */
  1550. pr_info("Early memory node ranges\n");
  1551. for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
  1552. pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
  1553. (u64)start_pfn << PAGE_SHIFT,
  1554. ((u64)end_pfn << PAGE_SHIFT) - 1);
  1555. subsection_map_init(start_pfn, end_pfn - start_pfn);
  1556. }
  1557. /* Initialise every node */
  1558. mminit_verify_pageflags_layout();
  1559. setup_nr_node_ids();
  1560. set_pageblock_order();
  1561. for_each_node(nid) {
  1562. pg_data_t *pgdat;
  1563. if (!node_online(nid))
  1564. alloc_offline_node_data(nid);
  1565. pgdat = NODE_DATA(nid);
  1566. free_area_init_node(nid);
  1567. /*
  1568. * No sysfs hierarcy will be created via register_one_node()
  1569. *for memory-less node because here it's not marked as N_MEMORY
  1570. *and won't be set online later. The benefit is userspace
  1571. *program won't be confused by sysfs files/directories of
  1572. *memory-less node. The pgdat will get fully initialized by
  1573. *hotadd_init_pgdat() when memory is hotplugged into this node.
  1574. */
  1575. if (pgdat->node_present_pages) {
  1576. node_set_state(nid, N_MEMORY);
  1577. check_for_memory(pgdat);
  1578. }
  1579. }
  1580. calc_nr_kernel_pages();
  1581. memmap_init();
  1582. /* disable hash distribution for systems with a single node */
  1583. fixup_hashdist();
  1584. }
  1585. /**
  1586. * node_map_pfn_alignment - determine the maximum internode alignment
  1587. *
  1588. * This function should be called after node map is populated and sorted.
  1589. * It calculates the maximum power of two alignment which can distinguish
  1590. * all the nodes.
  1591. *
  1592. * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
  1593. * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
  1594. * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
  1595. * shifted, 1GiB is enough and this function will indicate so.
  1596. *
  1597. * This is used to test whether pfn -> nid mapping of the chosen memory
  1598. * model has fine enough granularity to avoid incorrect mapping for the
  1599. * populated node map.
  1600. *
  1601. * Return: the determined alignment in pfn's. 0 if there is no alignment
  1602. * requirement (single node).
  1603. */
  1604. unsigned long __init node_map_pfn_alignment(void)
  1605. {
  1606. unsigned long accl_mask = 0, last_end = 0;
  1607. unsigned long start, end, mask;
  1608. int last_nid = NUMA_NO_NODE;
  1609. int i, nid;
  1610. for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
  1611. if (!start || last_nid < 0 || last_nid == nid) {
  1612. last_nid = nid;
  1613. last_end = end;
  1614. continue;
  1615. }
  1616. /*
  1617. * Start with a mask granular enough to pin-point to the
  1618. * start pfn and tick off bits one-by-one until it becomes
  1619. * too coarse to separate the current node from the last.
  1620. */
  1621. mask = ~((1 << __ffs(start)) - 1);
  1622. while (mask && last_end <= (start & (mask << 1)))
  1623. mask <<= 1;
  1624. /* accumulate all internode masks */
  1625. accl_mask |= mask;
  1626. }
  1627. /* convert mask to number of pages */
  1628. return ~accl_mask + 1;
  1629. }
  1630. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  1631. static void __init deferred_free_pages(unsigned long pfn,
  1632. unsigned long nr_pages)
  1633. {
  1634. struct page *page;
  1635. unsigned long i;
  1636. if (!nr_pages)
  1637. return;
  1638. page = pfn_to_page(pfn);
  1639. /* Free a large naturally-aligned chunk if possible */
  1640. if (nr_pages == MAX_ORDER_NR_PAGES && IS_MAX_ORDER_ALIGNED(pfn)) {
  1641. for (i = 0; i < nr_pages; i += pageblock_nr_pages)
  1642. set_pageblock_migratetype(page + i, MIGRATE_MOVABLE);
  1643. __free_pages_core(page, MAX_PAGE_ORDER, MEMINIT_EARLY);
  1644. return;
  1645. }
  1646. /* Accept chunks smaller than MAX_PAGE_ORDER upfront */
  1647. accept_memory(PFN_PHYS(pfn), nr_pages * PAGE_SIZE);
  1648. for (i = 0; i < nr_pages; i++, page++, pfn++) {
  1649. if (pageblock_aligned(pfn))
  1650. set_pageblock_migratetype(page, MIGRATE_MOVABLE);
  1651. __free_pages_core(page, 0, MEMINIT_EARLY);
  1652. }
  1653. }
  1654. /* Completion tracking for deferred_init_memmap() threads */
  1655. static atomic_t pgdat_init_n_undone __initdata;
  1656. static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
  1657. static inline void __init pgdat_init_report_one_done(void)
  1658. {
  1659. if (atomic_dec_and_test(&pgdat_init_n_undone))
  1660. complete(&pgdat_init_all_done_comp);
  1661. }
  1662. /*
  1663. * Initialize struct pages. We minimize pfn page lookups and scheduler checks
  1664. * by performing it only once every MAX_ORDER_NR_PAGES.
  1665. * Return number of pages initialized.
  1666. */
  1667. static unsigned long __init deferred_init_pages(struct zone *zone,
  1668. unsigned long pfn, unsigned long end_pfn)
  1669. {
  1670. int nid = zone_to_nid(zone);
  1671. unsigned long nr_pages = end_pfn - pfn;
  1672. int zid = zone_idx(zone);
  1673. struct page *page = pfn_to_page(pfn);
  1674. for (; pfn < end_pfn; pfn++, page++)
  1675. __init_single_page(page, pfn, zid, nid);
  1676. return nr_pages;
  1677. }
  1678. /*
  1679. * This function is meant to pre-load the iterator for the zone init from
  1680. * a given point.
  1681. * Specifically it walks through the ranges starting with initial index
  1682. * passed to it until we are caught up to the first_init_pfn value and
  1683. * exits there. If we never encounter the value we return false indicating
  1684. * there are no valid ranges left.
  1685. */
  1686. static bool __init
  1687. deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
  1688. unsigned long *spfn, unsigned long *epfn,
  1689. unsigned long first_init_pfn)
  1690. {
  1691. u64 j = *i;
  1692. if (j == 0)
  1693. __next_mem_pfn_range_in_zone(&j, zone, spfn, epfn);
  1694. /*
  1695. * Start out by walking through the ranges in this zone that have
  1696. * already been initialized. We don't need to do anything with them
  1697. * so we just need to flush them out of the system.
  1698. */
  1699. for_each_free_mem_pfn_range_in_zone_from(j, zone, spfn, epfn) {
  1700. if (*epfn <= first_init_pfn)
  1701. continue;
  1702. if (*spfn < first_init_pfn)
  1703. *spfn = first_init_pfn;
  1704. *i = j;
  1705. return true;
  1706. }
  1707. return false;
  1708. }
  1709. /*
  1710. * Initialize and free pages. We do it in two loops: first we initialize
  1711. * struct page, then free to buddy allocator, because while we are
  1712. * freeing pages we can access pages that are ahead (computing buddy
  1713. * page in __free_one_page()).
  1714. *
  1715. * In order to try and keep some memory in the cache we have the loop
  1716. * broken along max page order boundaries. This way we will not cause
  1717. * any issues with the buddy page computation.
  1718. */
  1719. static unsigned long __init
  1720. deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
  1721. unsigned long *end_pfn)
  1722. {
  1723. unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
  1724. unsigned long spfn = *start_pfn, epfn = *end_pfn;
  1725. unsigned long nr_pages = 0;
  1726. u64 j = *i;
  1727. /* First we loop through and initialize the page values */
  1728. for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
  1729. unsigned long t;
  1730. if (mo_pfn <= *start_pfn)
  1731. break;
  1732. t = min(mo_pfn, *end_pfn);
  1733. nr_pages += deferred_init_pages(zone, *start_pfn, t);
  1734. if (mo_pfn < *end_pfn) {
  1735. *start_pfn = mo_pfn;
  1736. break;
  1737. }
  1738. }
  1739. /* Reset values and now loop through freeing pages as needed */
  1740. swap(j, *i);
  1741. for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
  1742. unsigned long t;
  1743. if (mo_pfn <= spfn)
  1744. break;
  1745. t = min(mo_pfn, epfn);
  1746. deferred_free_pages(spfn, t - spfn);
  1747. if (mo_pfn <= epfn)
  1748. break;
  1749. }
  1750. return nr_pages;
  1751. }
  1752. static void __init
  1753. deferred_init_memmap_chunk(unsigned long start_pfn, unsigned long end_pfn,
  1754. void *arg)
  1755. {
  1756. unsigned long spfn, epfn;
  1757. struct zone *zone = arg;
  1758. u64 i = 0;
  1759. deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, start_pfn);
  1760. /*
  1761. * Initialize and free pages in MAX_PAGE_ORDER sized increments so that
  1762. * we can avoid introducing any issues with the buddy allocator.
  1763. */
  1764. while (spfn < end_pfn) {
  1765. deferred_init_maxorder(&i, zone, &spfn, &epfn);
  1766. cond_resched();
  1767. }
  1768. }
  1769. static unsigned int __init
  1770. deferred_page_init_max_threads(const struct cpumask *node_cpumask)
  1771. {
  1772. return max(cpumask_weight(node_cpumask), 1U);
  1773. }
  1774. /* Initialise remaining memory on a node */
  1775. static int __init deferred_init_memmap(void *data)
  1776. {
  1777. pg_data_t *pgdat = data;
  1778. const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
  1779. unsigned long spfn = 0, epfn = 0;
  1780. unsigned long first_init_pfn, flags;
  1781. unsigned long start = jiffies;
  1782. struct zone *zone;
  1783. int max_threads;
  1784. u64 i = 0;
  1785. /* Bind memory initialisation thread to a local node if possible */
  1786. if (!cpumask_empty(cpumask))
  1787. set_cpus_allowed_ptr(current, cpumask);
  1788. pgdat_resize_lock(pgdat, &flags);
  1789. first_init_pfn = pgdat->first_deferred_pfn;
  1790. if (first_init_pfn == ULONG_MAX) {
  1791. pgdat_resize_unlock(pgdat, &flags);
  1792. pgdat_init_report_one_done();
  1793. return 0;
  1794. }
  1795. /* Sanity check boundaries */
  1796. BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
  1797. BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
  1798. pgdat->first_deferred_pfn = ULONG_MAX;
  1799. /*
  1800. * Once we unlock here, the zone cannot be grown anymore, thus if an
  1801. * interrupt thread must allocate this early in boot, zone must be
  1802. * pre-grown prior to start of deferred page initialization.
  1803. */
  1804. pgdat_resize_unlock(pgdat, &flags);
  1805. /* Only the highest zone is deferred */
  1806. zone = pgdat->node_zones + pgdat->nr_zones - 1;
  1807. max_threads = deferred_page_init_max_threads(cpumask);
  1808. while (deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, first_init_pfn)) {
  1809. first_init_pfn = ALIGN(epfn, PAGES_PER_SECTION);
  1810. struct padata_mt_job job = {
  1811. .thread_fn = deferred_init_memmap_chunk,
  1812. .fn_arg = zone,
  1813. .start = spfn,
  1814. .size = first_init_pfn - spfn,
  1815. .align = PAGES_PER_SECTION,
  1816. .min_chunk = PAGES_PER_SECTION,
  1817. .max_threads = max_threads,
  1818. .numa_aware = false,
  1819. };
  1820. padata_do_multithreaded(&job);
  1821. }
  1822. /* Sanity check that the next zone really is unpopulated */
  1823. WARN_ON(pgdat->nr_zones < MAX_NR_ZONES && populated_zone(++zone));
  1824. pr_info("node %d deferred pages initialised in %ums\n",
  1825. pgdat->node_id, jiffies_to_msecs(jiffies - start));
  1826. pgdat_init_report_one_done();
  1827. return 0;
  1828. }
  1829. /*
  1830. * If this zone has deferred pages, try to grow it by initializing enough
  1831. * deferred pages to satisfy the allocation specified by order, rounded up to
  1832. * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
  1833. * of SECTION_SIZE bytes by initializing struct pages in increments of
  1834. * PAGES_PER_SECTION * sizeof(struct page) bytes.
  1835. *
  1836. * Return true when zone was grown, otherwise return false. We return true even
  1837. * when we grow less than requested, to let the caller decide if there are
  1838. * enough pages to satisfy the allocation.
  1839. */
  1840. bool __init deferred_grow_zone(struct zone *zone, unsigned int order)
  1841. {
  1842. unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
  1843. pg_data_t *pgdat = zone->zone_pgdat;
  1844. unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
  1845. unsigned long spfn, epfn, flags;
  1846. unsigned long nr_pages = 0;
  1847. u64 i = 0;
  1848. /* Only the last zone may have deferred pages */
  1849. if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
  1850. return false;
  1851. pgdat_resize_lock(pgdat, &flags);
  1852. /*
  1853. * If someone grew this zone while we were waiting for spinlock, return
  1854. * true, as there might be enough pages already.
  1855. */
  1856. if (first_deferred_pfn != pgdat->first_deferred_pfn) {
  1857. pgdat_resize_unlock(pgdat, &flags);
  1858. return true;
  1859. }
  1860. /* If the zone is empty somebody else may have cleared out the zone */
  1861. if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
  1862. first_deferred_pfn)) {
  1863. pgdat->first_deferred_pfn = ULONG_MAX;
  1864. pgdat_resize_unlock(pgdat, &flags);
  1865. /* Retry only once. */
  1866. return first_deferred_pfn != ULONG_MAX;
  1867. }
  1868. /*
  1869. * Initialize and free pages in MAX_PAGE_ORDER sized increments so
  1870. * that we can avoid introducing any issues with the buddy
  1871. * allocator.
  1872. */
  1873. while (spfn < epfn) {
  1874. /* update our first deferred PFN for this section */
  1875. first_deferred_pfn = spfn;
  1876. nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
  1877. touch_nmi_watchdog();
  1878. /* We should only stop along section boundaries */
  1879. if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
  1880. continue;
  1881. /* If our quota has been met we can stop here */
  1882. if (nr_pages >= nr_pages_needed)
  1883. break;
  1884. }
  1885. pgdat->first_deferred_pfn = spfn;
  1886. pgdat_resize_unlock(pgdat, &flags);
  1887. return nr_pages > 0;
  1888. }
  1889. #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
  1890. #ifdef CONFIG_CMA
  1891. void __init init_cma_reserved_pageblock(struct page *page)
  1892. {
  1893. unsigned i = pageblock_nr_pages;
  1894. struct page *p = page;
  1895. do {
  1896. __ClearPageReserved(p);
  1897. set_page_count(p, 0);
  1898. } while (++p, --i);
  1899. set_pageblock_migratetype(page, MIGRATE_CMA);
  1900. set_page_refcounted(page);
  1901. /* pages were reserved and not allocated */
  1902. clear_page_tag_ref(page);
  1903. __free_pages(page, pageblock_order);
  1904. adjust_managed_page_count(page, pageblock_nr_pages);
  1905. page_zone(page)->cma_pages += pageblock_nr_pages;
  1906. }
  1907. #endif
  1908. void set_zone_contiguous(struct zone *zone)
  1909. {
  1910. unsigned long block_start_pfn = zone->zone_start_pfn;
  1911. unsigned long block_end_pfn;
  1912. block_end_pfn = pageblock_end_pfn(block_start_pfn);
  1913. for (; block_start_pfn < zone_end_pfn(zone);
  1914. block_start_pfn = block_end_pfn,
  1915. block_end_pfn += pageblock_nr_pages) {
  1916. block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
  1917. if (!__pageblock_pfn_to_page(block_start_pfn,
  1918. block_end_pfn, zone))
  1919. return;
  1920. cond_resched();
  1921. }
  1922. /* We confirm that there is no hole */
  1923. zone->contiguous = true;
  1924. }
  1925. static void __init mem_init_print_info(void);
  1926. void __init page_alloc_init_late(void)
  1927. {
  1928. struct zone *zone;
  1929. int nid;
  1930. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  1931. /* There will be num_node_state(N_MEMORY) threads */
  1932. atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
  1933. for_each_node_state(nid, N_MEMORY) {
  1934. kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
  1935. }
  1936. /* Block until all are initialised */
  1937. wait_for_completion(&pgdat_init_all_done_comp);
  1938. /*
  1939. * We initialized the rest of the deferred pages. Permanently disable
  1940. * on-demand struct page initialization.
  1941. */
  1942. static_branch_disable(&deferred_pages);
  1943. /* Reinit limits that are based on free pages after the kernel is up */
  1944. files_maxfiles_init();
  1945. #endif
  1946. /* Accounting of total+free memory is stable at this point. */
  1947. mem_init_print_info();
  1948. buffer_init();
  1949. /* Discard memblock private memory */
  1950. memblock_discard();
  1951. for_each_node_state(nid, N_MEMORY)
  1952. shuffle_free_memory(NODE_DATA(nid));
  1953. for_each_populated_zone(zone)
  1954. set_zone_contiguous(zone);
  1955. /* Initialize page ext after all struct pages are initialized. */
  1956. if (deferred_struct_pages)
  1957. page_ext_init();
  1958. page_alloc_sysctl_init();
  1959. }
  1960. /*
  1961. * Adaptive scale is meant to reduce sizes of hash tables on large memory
  1962. * machines. As memory size is increased the scale is also increased but at
  1963. * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
  1964. * quadruples the scale is increased by one, which means the size of hash table
  1965. * only doubles, instead of quadrupling as well.
  1966. * Because 32-bit systems cannot have large physical memory, where this scaling
  1967. * makes sense, it is disabled on such platforms.
  1968. */
  1969. #if __BITS_PER_LONG > 32
  1970. #define ADAPT_SCALE_BASE (64ul << 30)
  1971. #define ADAPT_SCALE_SHIFT 2
  1972. #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
  1973. #endif
  1974. /*
  1975. * allocate a large system hash table from bootmem
  1976. * - it is assumed that the hash table must contain an exact power-of-2
  1977. * quantity of entries
  1978. * - limit is the number of hash buckets, not the total allocation size
  1979. */
  1980. void *__init alloc_large_system_hash(const char *tablename,
  1981. unsigned long bucketsize,
  1982. unsigned long numentries,
  1983. int scale,
  1984. int flags,
  1985. unsigned int *_hash_shift,
  1986. unsigned int *_hash_mask,
  1987. unsigned long low_limit,
  1988. unsigned long high_limit)
  1989. {
  1990. unsigned long long max = high_limit;
  1991. unsigned long log2qty, size;
  1992. void *table;
  1993. gfp_t gfp_flags;
  1994. bool virt;
  1995. bool huge;
  1996. /* allow the kernel cmdline to have a say */
  1997. if (!numentries) {
  1998. /* round applicable memory size up to nearest megabyte */
  1999. numentries = nr_kernel_pages;
  2000. /* It isn't necessary when PAGE_SIZE >= 1MB */
  2001. if (PAGE_SIZE < SZ_1M)
  2002. numentries = round_up(numentries, SZ_1M / PAGE_SIZE);
  2003. #if __BITS_PER_LONG > 32
  2004. if (!high_limit) {
  2005. unsigned long adapt;
  2006. for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
  2007. adapt <<= ADAPT_SCALE_SHIFT)
  2008. scale++;
  2009. }
  2010. #endif
  2011. /* limit to 1 bucket per 2^scale bytes of low memory */
  2012. if (scale > PAGE_SHIFT)
  2013. numentries >>= (scale - PAGE_SHIFT);
  2014. else
  2015. numentries <<= (PAGE_SHIFT - scale);
  2016. if (unlikely((numentries * bucketsize) < PAGE_SIZE))
  2017. numentries = PAGE_SIZE / bucketsize;
  2018. }
  2019. numentries = roundup_pow_of_two(numentries);
  2020. /* limit allocation size to 1/16 total memory by default */
  2021. if (max == 0) {
  2022. max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
  2023. do_div(max, bucketsize);
  2024. }
  2025. max = min(max, 0x80000000ULL);
  2026. if (numentries < low_limit)
  2027. numentries = low_limit;
  2028. if (numentries > max)
  2029. numentries = max;
  2030. log2qty = ilog2(numentries);
  2031. gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
  2032. do {
  2033. virt = false;
  2034. size = bucketsize << log2qty;
  2035. if (flags & HASH_EARLY) {
  2036. if (flags & HASH_ZERO)
  2037. table = memblock_alloc(size, SMP_CACHE_BYTES);
  2038. else
  2039. table = memblock_alloc_raw(size,
  2040. SMP_CACHE_BYTES);
  2041. } else if (get_order(size) > MAX_PAGE_ORDER || hashdist) {
  2042. table = vmalloc_huge(size, gfp_flags);
  2043. virt = true;
  2044. if (table)
  2045. huge = is_vm_area_hugepages(table);
  2046. } else {
  2047. /*
  2048. * If bucketsize is not a power-of-two, we may free
  2049. * some pages at the end of hash table which
  2050. * alloc_pages_exact() automatically does
  2051. */
  2052. table = alloc_pages_exact(size, gfp_flags);
  2053. kmemleak_alloc(table, size, 1, gfp_flags);
  2054. }
  2055. } while (!table && size > PAGE_SIZE && --log2qty);
  2056. if (!table)
  2057. panic("Failed to allocate %s hash table\n", tablename);
  2058. pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
  2059. tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
  2060. virt ? (huge ? "vmalloc hugepage" : "vmalloc") : "linear");
  2061. if (_hash_shift)
  2062. *_hash_shift = log2qty;
  2063. if (_hash_mask)
  2064. *_hash_mask = (1 << log2qty) - 1;
  2065. return table;
  2066. }
  2067. void __init memblock_free_pages(struct page *page, unsigned long pfn,
  2068. unsigned int order)
  2069. {
  2070. if (IS_ENABLED(CONFIG_DEFERRED_STRUCT_PAGE_INIT)) {
  2071. int nid = early_pfn_to_nid(pfn);
  2072. if (!early_page_initialised(pfn, nid))
  2073. return;
  2074. }
  2075. if (!kmsan_memblock_free_pages(page, order)) {
  2076. /* KMSAN will take care of these pages. */
  2077. return;
  2078. }
  2079. /* pages were reserved and not allocated */
  2080. clear_page_tag_ref(page);
  2081. __free_pages_core(page, order, MEMINIT_EARLY);
  2082. }
  2083. DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_ALLOC_DEFAULT_ON, init_on_alloc);
  2084. EXPORT_SYMBOL(init_on_alloc);
  2085. DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_FREE_DEFAULT_ON, init_on_free);
  2086. EXPORT_SYMBOL(init_on_free);
  2087. static bool _init_on_alloc_enabled_early __read_mostly
  2088. = IS_ENABLED(CONFIG_INIT_ON_ALLOC_DEFAULT_ON);
  2089. static int __init early_init_on_alloc(char *buf)
  2090. {
  2091. return kstrtobool(buf, &_init_on_alloc_enabled_early);
  2092. }
  2093. early_param("init_on_alloc", early_init_on_alloc);
  2094. static bool _init_on_free_enabled_early __read_mostly
  2095. = IS_ENABLED(CONFIG_INIT_ON_FREE_DEFAULT_ON);
  2096. static int __init early_init_on_free(char *buf)
  2097. {
  2098. return kstrtobool(buf, &_init_on_free_enabled_early);
  2099. }
  2100. early_param("init_on_free", early_init_on_free);
  2101. DEFINE_STATIC_KEY_MAYBE(CONFIG_DEBUG_VM, check_pages_enabled);
  2102. /*
  2103. * Enable static keys related to various memory debugging and hardening options.
  2104. * Some override others, and depend on early params that are evaluated in the
  2105. * order of appearance. So we need to first gather the full picture of what was
  2106. * enabled, and then make decisions.
  2107. */
  2108. static void __init mem_debugging_and_hardening_init(void)
  2109. {
  2110. bool page_poisoning_requested = false;
  2111. bool want_check_pages = false;
  2112. #ifdef CONFIG_PAGE_POISONING
  2113. /*
  2114. * Page poisoning is debug page alloc for some arches. If
  2115. * either of those options are enabled, enable poisoning.
  2116. */
  2117. if (page_poisoning_enabled() ||
  2118. (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC) &&
  2119. debug_pagealloc_enabled())) {
  2120. static_branch_enable(&_page_poisoning_enabled);
  2121. page_poisoning_requested = true;
  2122. want_check_pages = true;
  2123. }
  2124. #endif
  2125. if ((_init_on_alloc_enabled_early || _init_on_free_enabled_early) &&
  2126. page_poisoning_requested) {
  2127. pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, "
  2128. "will take precedence over init_on_alloc and init_on_free\n");
  2129. _init_on_alloc_enabled_early = false;
  2130. _init_on_free_enabled_early = false;
  2131. }
  2132. if (_init_on_alloc_enabled_early) {
  2133. want_check_pages = true;
  2134. static_branch_enable(&init_on_alloc);
  2135. } else {
  2136. static_branch_disable(&init_on_alloc);
  2137. }
  2138. if (_init_on_free_enabled_early) {
  2139. want_check_pages = true;
  2140. static_branch_enable(&init_on_free);
  2141. } else {
  2142. static_branch_disable(&init_on_free);
  2143. }
  2144. if (IS_ENABLED(CONFIG_KMSAN) &&
  2145. (_init_on_alloc_enabled_early || _init_on_free_enabled_early))
  2146. pr_info("mem auto-init: please make sure init_on_alloc and init_on_free are disabled when running KMSAN\n");
  2147. #ifdef CONFIG_DEBUG_PAGEALLOC
  2148. if (debug_pagealloc_enabled()) {
  2149. want_check_pages = true;
  2150. static_branch_enable(&_debug_pagealloc_enabled);
  2151. if (debug_guardpage_minorder())
  2152. static_branch_enable(&_debug_guardpage_enabled);
  2153. }
  2154. #endif
  2155. /*
  2156. * Any page debugging or hardening option also enables sanity checking
  2157. * of struct pages being allocated or freed. With CONFIG_DEBUG_VM it's
  2158. * enabled already.
  2159. */
  2160. if (!IS_ENABLED(CONFIG_DEBUG_VM) && want_check_pages)
  2161. static_branch_enable(&check_pages_enabled);
  2162. }
  2163. /* Report memory auto-initialization states for this boot. */
  2164. static void __init report_meminit(void)
  2165. {
  2166. const char *stack;
  2167. if (IS_ENABLED(CONFIG_INIT_STACK_ALL_PATTERN))
  2168. stack = "all(pattern)";
  2169. else if (IS_ENABLED(CONFIG_INIT_STACK_ALL_ZERO))
  2170. stack = "all(zero)";
  2171. else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL))
  2172. stack = "byref_all(zero)";
  2173. else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF))
  2174. stack = "byref(zero)";
  2175. else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_USER))
  2176. stack = "__user(zero)";
  2177. else
  2178. stack = "off";
  2179. pr_info("mem auto-init: stack:%s, heap alloc:%s, heap free:%s\n",
  2180. stack, want_init_on_alloc(GFP_KERNEL) ? "on" : "off",
  2181. want_init_on_free() ? "on" : "off");
  2182. if (want_init_on_free())
  2183. pr_info("mem auto-init: clearing system memory may take some time...\n");
  2184. }
  2185. static void __init mem_init_print_info(void)
  2186. {
  2187. unsigned long physpages, codesize, datasize, rosize, bss_size;
  2188. unsigned long init_code_size, init_data_size;
  2189. physpages = get_num_physpages();
  2190. codesize = _etext - _stext;
  2191. datasize = _edata - _sdata;
  2192. rosize = __end_rodata - __start_rodata;
  2193. bss_size = __bss_stop - __bss_start;
  2194. init_data_size = __init_end - __init_begin;
  2195. init_code_size = _einittext - _sinittext;
  2196. /*
  2197. * Detect special cases and adjust section sizes accordingly:
  2198. * 1) .init.* may be embedded into .data sections
  2199. * 2) .init.text.* may be out of [__init_begin, __init_end],
  2200. * please refer to arch/tile/kernel/vmlinux.lds.S.
  2201. * 3) .rodata.* may be embedded into .text or .data sections.
  2202. */
  2203. #define adj_init_size(start, end, size, pos, adj) \
  2204. do { \
  2205. if (&start[0] <= &pos[0] && &pos[0] < &end[0] && size > adj) \
  2206. size -= adj; \
  2207. } while (0)
  2208. adj_init_size(__init_begin, __init_end, init_data_size,
  2209. _sinittext, init_code_size);
  2210. adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
  2211. adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
  2212. adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
  2213. adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
  2214. #undef adj_init_size
  2215. pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
  2216. #ifdef CONFIG_HIGHMEM
  2217. ", %luK highmem"
  2218. #endif
  2219. ")\n",
  2220. K(nr_free_pages()), K(physpages),
  2221. codesize / SZ_1K, datasize / SZ_1K, rosize / SZ_1K,
  2222. (init_data_size + init_code_size) / SZ_1K, bss_size / SZ_1K,
  2223. K(physpages - totalram_pages() - totalcma_pages),
  2224. K(totalcma_pages)
  2225. #ifdef CONFIG_HIGHMEM
  2226. , K(totalhigh_pages())
  2227. #endif
  2228. );
  2229. }
  2230. /*
  2231. * Set up kernel memory allocators
  2232. */
  2233. void __init mm_core_init(void)
  2234. {
  2235. /* Initializations relying on SMP setup */
  2236. BUILD_BUG_ON(MAX_ZONELISTS > 2);
  2237. build_all_zonelists(NULL);
  2238. page_alloc_init_cpuhp();
  2239. /*
  2240. * page_ext requires contiguous pages,
  2241. * bigger than MAX_PAGE_ORDER unless SPARSEMEM.
  2242. */
  2243. page_ext_init_flatmem();
  2244. mem_debugging_and_hardening_init();
  2245. kfence_alloc_pool_and_metadata();
  2246. report_meminit();
  2247. kmsan_init_shadow();
  2248. stack_depot_early_init();
  2249. mem_init();
  2250. kmem_cache_init();
  2251. /*
  2252. * page_owner must be initialized after buddy is ready, and also after
  2253. * slab is ready so that stack_depot_init() works properly
  2254. */
  2255. page_ext_init_flatmem_late();
  2256. kmemleak_init();
  2257. ptlock_cache_init();
  2258. pgtable_cache_init();
  2259. debug_objects_mem_init();
  2260. vmalloc_init();
  2261. /* If no deferred init page_ext now, as vmap is fully initialized */
  2262. if (!deferred_struct_pages)
  2263. page_ext_init();
  2264. /* Should be run before the first non-init thread is created */
  2265. init_espfix_bsp();
  2266. /* Should be run after espfix64 is set up. */
  2267. pti_init();
  2268. kmsan_init_runtime();
  2269. mm_cache_init();
  2270. execmem_init();
  2271. }