mm_init.c 76 KB

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