init.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. #include <linux/gfp.h>
  2. #include <linux/initrd.h>
  3. #include <linux/ioport.h>
  4. #include <linux/swap.h>
  5. #include <linux/memblock.h>
  6. #include <linux/swapfile.h>
  7. #include <linux/swapops.h>
  8. #include <linux/kmemleak.h>
  9. #include <linux/sched/task.h>
  10. #include <asm/set_memory.h>
  11. #include <asm/cpu_device_id.h>
  12. #include <asm/e820/api.h>
  13. #include <asm/init.h>
  14. #include <asm/page.h>
  15. #include <asm/page_types.h>
  16. #include <asm/sections.h>
  17. #include <asm/setup.h>
  18. #include <asm/tlbflush.h>
  19. #include <asm/tlb.h>
  20. #include <asm/proto.h>
  21. #include <asm/dma.h> /* for MAX_DMA_PFN */
  22. #include <asm/microcode.h>
  23. #include <asm/kaslr.h>
  24. #include <asm/hypervisor.h>
  25. #include <asm/cpufeature.h>
  26. #include <asm/pti.h>
  27. #include <asm/text-patching.h>
  28. #include <asm/memtype.h>
  29. #include <asm/paravirt.h>
  30. /*
  31. * We need to define the tracepoints somewhere, and tlb.c
  32. * is only compiled when SMP=y.
  33. */
  34. #include <trace/events/tlb.h>
  35. #include "mm_internal.h"
  36. /*
  37. * Tables translating between page_cache_type_t and pte encoding.
  38. *
  39. * The default values are defined statically as minimal supported mode;
  40. * WC and WT fall back to UC-. pat_init() updates these values to support
  41. * more cache modes, WC and WT, when it is safe to do so. See pat_init()
  42. * for the details. Note, __early_ioremap() used during early boot-time
  43. * takes pgprot_t (pte encoding) and does not use these tables.
  44. *
  45. * Index into __cachemode2pte_tbl[] is the cachemode.
  46. *
  47. * Index into __pte2cachemode_tbl[] are the caching attribute bits of the pte
  48. * (_PAGE_PWT, _PAGE_PCD, _PAGE_PAT) at index bit positions 0, 1, 2.
  49. */
  50. static uint16_t __cachemode2pte_tbl[_PAGE_CACHE_MODE_NUM] = {
  51. [_PAGE_CACHE_MODE_WB ] = 0 | 0 ,
  52. [_PAGE_CACHE_MODE_WC ] = 0 | _PAGE_PCD,
  53. [_PAGE_CACHE_MODE_UC_MINUS] = 0 | _PAGE_PCD,
  54. [_PAGE_CACHE_MODE_UC ] = _PAGE_PWT | _PAGE_PCD,
  55. [_PAGE_CACHE_MODE_WT ] = 0 | _PAGE_PCD,
  56. [_PAGE_CACHE_MODE_WP ] = 0 | _PAGE_PCD,
  57. };
  58. unsigned long cachemode2protval(enum page_cache_mode pcm)
  59. {
  60. if (likely(pcm == 0))
  61. return 0;
  62. return __cachemode2pte_tbl[pcm];
  63. }
  64. EXPORT_SYMBOL(cachemode2protval);
  65. static uint8_t __pte2cachemode_tbl[8] = {
  66. [__pte2cm_idx( 0 | 0 | 0 )] = _PAGE_CACHE_MODE_WB,
  67. [__pte2cm_idx(_PAGE_PWT | 0 | 0 )] = _PAGE_CACHE_MODE_UC_MINUS,
  68. [__pte2cm_idx( 0 | _PAGE_PCD | 0 )] = _PAGE_CACHE_MODE_UC_MINUS,
  69. [__pte2cm_idx(_PAGE_PWT | _PAGE_PCD | 0 )] = _PAGE_CACHE_MODE_UC,
  70. [__pte2cm_idx( 0 | 0 | _PAGE_PAT)] = _PAGE_CACHE_MODE_WB,
  71. [__pte2cm_idx(_PAGE_PWT | 0 | _PAGE_PAT)] = _PAGE_CACHE_MODE_UC_MINUS,
  72. [__pte2cm_idx(0 | _PAGE_PCD | _PAGE_PAT)] = _PAGE_CACHE_MODE_UC_MINUS,
  73. [__pte2cm_idx(_PAGE_PWT | _PAGE_PCD | _PAGE_PAT)] = _PAGE_CACHE_MODE_UC,
  74. };
  75. /*
  76. * Check that the write-protect PAT entry is set for write-protect.
  77. * To do this without making assumptions how PAT has been set up (Xen has
  78. * another layout than the kernel), translate the _PAGE_CACHE_MODE_WP cache
  79. * mode via the __cachemode2pte_tbl[] into protection bits (those protection
  80. * bits will select a cache mode of WP or better), and then translate the
  81. * protection bits back into the cache mode using __pte2cm_idx() and the
  82. * __pte2cachemode_tbl[] array. This will return the really used cache mode.
  83. */
  84. bool x86_has_pat_wp(void)
  85. {
  86. uint16_t prot = __cachemode2pte_tbl[_PAGE_CACHE_MODE_WP];
  87. return __pte2cachemode_tbl[__pte2cm_idx(prot)] == _PAGE_CACHE_MODE_WP;
  88. }
  89. enum page_cache_mode pgprot2cachemode(pgprot_t pgprot)
  90. {
  91. unsigned long masked;
  92. masked = pgprot_val(pgprot) & _PAGE_CACHE_MASK;
  93. if (likely(masked == 0))
  94. return 0;
  95. return __pte2cachemode_tbl[__pte2cm_idx(masked)];
  96. }
  97. static unsigned long __initdata pgt_buf_start;
  98. static unsigned long __initdata pgt_buf_end;
  99. static unsigned long __initdata pgt_buf_top;
  100. static unsigned long min_pfn_mapped;
  101. static bool __initdata can_use_brk_pgt = true;
  102. /*
  103. * Provide a run-time mean of disabling ZONE_DMA32 if it is enabled via
  104. * CONFIG_ZONE_DMA32.
  105. */
  106. static bool disable_dma32 __ro_after_init;
  107. /*
  108. * Pages returned are already directly mapped.
  109. *
  110. * Changing that is likely to break Xen, see commit:
  111. *
  112. * 279b706 x86,xen: introduce x86_init.mapping.pagetable_reserve
  113. *
  114. * for detailed information.
  115. */
  116. __ref void *alloc_low_pages(unsigned int num)
  117. {
  118. unsigned long pfn;
  119. int i;
  120. if (after_bootmem) {
  121. unsigned int order;
  122. order = get_order((unsigned long)num << PAGE_SHIFT);
  123. return (void *)__get_free_pages(GFP_ATOMIC | __GFP_ZERO, order);
  124. }
  125. if ((pgt_buf_end + num) > pgt_buf_top || !can_use_brk_pgt) {
  126. unsigned long ret = 0;
  127. if (min_pfn_mapped < max_pfn_mapped) {
  128. ret = memblock_phys_alloc_range(
  129. PAGE_SIZE * num, PAGE_SIZE,
  130. min_pfn_mapped << PAGE_SHIFT,
  131. max_pfn_mapped << PAGE_SHIFT);
  132. }
  133. if (!ret && can_use_brk_pgt)
  134. ret = __pa(extend_brk(PAGE_SIZE * num, PAGE_SIZE));
  135. if (!ret)
  136. panic("alloc_low_pages: can not alloc memory");
  137. pfn = ret >> PAGE_SHIFT;
  138. } else {
  139. pfn = pgt_buf_end;
  140. pgt_buf_end += num;
  141. }
  142. for (i = 0; i < num; i++) {
  143. void *adr;
  144. adr = __va((pfn + i) << PAGE_SHIFT);
  145. clear_page(adr);
  146. }
  147. return __va(pfn << PAGE_SHIFT);
  148. }
  149. /*
  150. * By default need to be able to allocate page tables below PGD firstly for
  151. * the 0-ISA_END_ADDRESS range and secondly for the initial PMD_SIZE mapping.
  152. * With KASLR memory randomization, depending on the machine e820 memory and the
  153. * PUD alignment, twice that many pages may be needed when KASLR memory
  154. * randomization is enabled.
  155. */
  156. #ifndef CONFIG_X86_5LEVEL
  157. #define INIT_PGD_PAGE_TABLES 3
  158. #else
  159. #define INIT_PGD_PAGE_TABLES 4
  160. #endif
  161. #ifndef CONFIG_RANDOMIZE_MEMORY
  162. #define INIT_PGD_PAGE_COUNT (2 * INIT_PGD_PAGE_TABLES)
  163. #else
  164. #define INIT_PGD_PAGE_COUNT (4 * INIT_PGD_PAGE_TABLES)
  165. #endif
  166. #define INIT_PGT_BUF_SIZE (INIT_PGD_PAGE_COUNT * PAGE_SIZE)
  167. RESERVE_BRK(early_pgt_alloc, INIT_PGT_BUF_SIZE);
  168. void __init early_alloc_pgt_buf(void)
  169. {
  170. unsigned long tables = INIT_PGT_BUF_SIZE;
  171. phys_addr_t base;
  172. base = __pa(extend_brk(tables, PAGE_SIZE));
  173. pgt_buf_start = base >> PAGE_SHIFT;
  174. pgt_buf_end = pgt_buf_start;
  175. pgt_buf_top = pgt_buf_start + (tables >> PAGE_SHIFT);
  176. }
  177. int after_bootmem;
  178. early_param_on_off("gbpages", "nogbpages", direct_gbpages, CONFIG_X86_DIRECT_GBPAGES);
  179. struct map_range {
  180. unsigned long start;
  181. unsigned long end;
  182. unsigned page_size_mask;
  183. };
  184. static int page_size_mask;
  185. /*
  186. * Save some of cr4 feature set we're using (e.g. Pentium 4MB
  187. * enable and PPro Global page enable), so that any CPU's that boot
  188. * up after us can get the correct flags. Invoked on the boot CPU.
  189. */
  190. static inline void cr4_set_bits_and_update_boot(unsigned long mask)
  191. {
  192. mmu_cr4_features |= mask;
  193. if (trampoline_cr4_features)
  194. *trampoline_cr4_features = mmu_cr4_features;
  195. cr4_set_bits(mask);
  196. }
  197. static void __init probe_page_size_mask(void)
  198. {
  199. /*
  200. * For pagealloc debugging, identity mapping will use small pages.
  201. * This will simplify cpa(), which otherwise needs to support splitting
  202. * large pages into small in interrupt context, etc.
  203. */
  204. if (boot_cpu_has(X86_FEATURE_PSE) && !debug_pagealloc_enabled())
  205. page_size_mask |= 1 << PG_LEVEL_2M;
  206. else
  207. direct_gbpages = 0;
  208. /* Enable PSE if available */
  209. if (boot_cpu_has(X86_FEATURE_PSE))
  210. cr4_set_bits_and_update_boot(X86_CR4_PSE);
  211. /* Enable PGE if available */
  212. __supported_pte_mask &= ~_PAGE_GLOBAL;
  213. if (boot_cpu_has(X86_FEATURE_PGE)) {
  214. cr4_set_bits_and_update_boot(X86_CR4_PGE);
  215. __supported_pte_mask |= _PAGE_GLOBAL;
  216. }
  217. /* By the default is everything supported: */
  218. __default_kernel_pte_mask = __supported_pte_mask;
  219. /* Except when with PTI where the kernel is mostly non-Global: */
  220. if (cpu_feature_enabled(X86_FEATURE_PTI))
  221. __default_kernel_pte_mask &= ~_PAGE_GLOBAL;
  222. /* Enable 1 GB linear kernel mappings if available: */
  223. if (direct_gbpages && boot_cpu_has(X86_FEATURE_GBPAGES)) {
  224. printk(KERN_INFO "Using GB pages for direct mapping\n");
  225. page_size_mask |= 1 << PG_LEVEL_1G;
  226. } else {
  227. direct_gbpages = 0;
  228. }
  229. }
  230. #define INTEL_MATCH(_model) { .vendor = X86_VENDOR_INTEL, \
  231. .family = 6, \
  232. .model = _model, \
  233. }
  234. /*
  235. * INVLPG may not properly flush Global entries
  236. * on these CPUs when PCIDs are enabled.
  237. */
  238. static const struct x86_cpu_id invlpg_miss_ids[] = {
  239. INTEL_MATCH(INTEL_FAM6_ALDERLAKE ),
  240. INTEL_MATCH(INTEL_FAM6_ALDERLAKE_L ),
  241. INTEL_MATCH(INTEL_FAM6_ALDERLAKE_N ),
  242. INTEL_MATCH(INTEL_FAM6_RAPTORLAKE ),
  243. INTEL_MATCH(INTEL_FAM6_RAPTORLAKE_P),
  244. INTEL_MATCH(INTEL_FAM6_RAPTORLAKE_S),
  245. {}
  246. };
  247. static void setup_pcid(void)
  248. {
  249. if (!IS_ENABLED(CONFIG_X86_64))
  250. return;
  251. if (!boot_cpu_has(X86_FEATURE_PCID))
  252. return;
  253. if (x86_match_cpu(invlpg_miss_ids)) {
  254. pr_info("Incomplete global flushes, disabling PCID");
  255. setup_clear_cpu_cap(X86_FEATURE_PCID);
  256. return;
  257. }
  258. if (boot_cpu_has(X86_FEATURE_PGE)) {
  259. /*
  260. * This can't be cr4_set_bits_and_update_boot() -- the
  261. * trampoline code can't handle CR4.PCIDE and it wouldn't
  262. * do any good anyway. Despite the name,
  263. * cr4_set_bits_and_update_boot() doesn't actually cause
  264. * the bits in question to remain set all the way through
  265. * the secondary boot asm.
  266. *
  267. * Instead, we brute-force it and set CR4.PCIDE manually in
  268. * start_secondary().
  269. */
  270. cr4_set_bits(X86_CR4_PCIDE);
  271. /*
  272. * INVPCID's single-context modes (2/3) only work if we set
  273. * X86_CR4_PCIDE, *and* we INVPCID support. It's unusable
  274. * on systems that have X86_CR4_PCIDE clear, or that have
  275. * no INVPCID support at all.
  276. */
  277. if (boot_cpu_has(X86_FEATURE_INVPCID))
  278. setup_force_cpu_cap(X86_FEATURE_INVPCID_SINGLE);
  279. } else {
  280. /*
  281. * flush_tlb_all(), as currently implemented, won't work if
  282. * PCID is on but PGE is not. Since that combination
  283. * doesn't exist on real hardware, there's no reason to try
  284. * to fully support it, but it's polite to avoid corrupting
  285. * data if we're on an improperly configured VM.
  286. */
  287. setup_clear_cpu_cap(X86_FEATURE_PCID);
  288. }
  289. }
  290. #ifdef CONFIG_X86_32
  291. #define NR_RANGE_MR 3
  292. #else /* CONFIG_X86_64 */
  293. #define NR_RANGE_MR 5
  294. #endif
  295. static int __meminit save_mr(struct map_range *mr, int nr_range,
  296. unsigned long start_pfn, unsigned long end_pfn,
  297. unsigned long page_size_mask)
  298. {
  299. if (start_pfn < end_pfn) {
  300. if (nr_range >= NR_RANGE_MR)
  301. panic("run out of range for init_memory_mapping\n");
  302. mr[nr_range].start = start_pfn<<PAGE_SHIFT;
  303. mr[nr_range].end = end_pfn<<PAGE_SHIFT;
  304. mr[nr_range].page_size_mask = page_size_mask;
  305. nr_range++;
  306. }
  307. return nr_range;
  308. }
  309. /*
  310. * adjust the page_size_mask for small range to go with
  311. * big page size instead small one if nearby are ram too.
  312. */
  313. static void __ref adjust_range_page_size_mask(struct map_range *mr,
  314. int nr_range)
  315. {
  316. int i;
  317. for (i = 0; i < nr_range; i++) {
  318. if ((page_size_mask & (1<<PG_LEVEL_2M)) &&
  319. !(mr[i].page_size_mask & (1<<PG_LEVEL_2M))) {
  320. unsigned long start = round_down(mr[i].start, PMD_SIZE);
  321. unsigned long end = round_up(mr[i].end, PMD_SIZE);
  322. #ifdef CONFIG_X86_32
  323. if ((end >> PAGE_SHIFT) > max_low_pfn)
  324. continue;
  325. #endif
  326. if (memblock_is_region_memory(start, end - start))
  327. mr[i].page_size_mask |= 1<<PG_LEVEL_2M;
  328. }
  329. if ((page_size_mask & (1<<PG_LEVEL_1G)) &&
  330. !(mr[i].page_size_mask & (1<<PG_LEVEL_1G))) {
  331. unsigned long start = round_down(mr[i].start, PUD_SIZE);
  332. unsigned long end = round_up(mr[i].end, PUD_SIZE);
  333. if (memblock_is_region_memory(start, end - start))
  334. mr[i].page_size_mask |= 1<<PG_LEVEL_1G;
  335. }
  336. }
  337. }
  338. static const char *page_size_string(struct map_range *mr)
  339. {
  340. static const char str_1g[] = "1G";
  341. static const char str_2m[] = "2M";
  342. static const char str_4m[] = "4M";
  343. static const char str_4k[] = "4k";
  344. if (mr->page_size_mask & (1<<PG_LEVEL_1G))
  345. return str_1g;
  346. /*
  347. * 32-bit without PAE has a 4M large page size.
  348. * PG_LEVEL_2M is misnamed, but we can at least
  349. * print out the right size in the string.
  350. */
  351. if (IS_ENABLED(CONFIG_X86_32) &&
  352. !IS_ENABLED(CONFIG_X86_PAE) &&
  353. mr->page_size_mask & (1<<PG_LEVEL_2M))
  354. return str_4m;
  355. if (mr->page_size_mask & (1<<PG_LEVEL_2M))
  356. return str_2m;
  357. return str_4k;
  358. }
  359. static int __meminit split_mem_range(struct map_range *mr, int nr_range,
  360. unsigned long start,
  361. unsigned long end)
  362. {
  363. unsigned long start_pfn, end_pfn, limit_pfn;
  364. unsigned long pfn;
  365. int i;
  366. limit_pfn = PFN_DOWN(end);
  367. /* head if not big page alignment ? */
  368. pfn = start_pfn = PFN_DOWN(start);
  369. #ifdef CONFIG_X86_32
  370. /*
  371. * Don't use a large page for the first 2/4MB of memory
  372. * because there are often fixed size MTRRs in there
  373. * and overlapping MTRRs into large pages can cause
  374. * slowdowns.
  375. */
  376. if (pfn == 0)
  377. end_pfn = PFN_DOWN(PMD_SIZE);
  378. else
  379. end_pfn = round_up(pfn, PFN_DOWN(PMD_SIZE));
  380. #else /* CONFIG_X86_64 */
  381. end_pfn = round_up(pfn, PFN_DOWN(PMD_SIZE));
  382. #endif
  383. if (end_pfn > limit_pfn)
  384. end_pfn = limit_pfn;
  385. if (start_pfn < end_pfn) {
  386. nr_range = save_mr(mr, nr_range, start_pfn, end_pfn, 0);
  387. pfn = end_pfn;
  388. }
  389. /* big page (2M) range */
  390. start_pfn = round_up(pfn, PFN_DOWN(PMD_SIZE));
  391. #ifdef CONFIG_X86_32
  392. end_pfn = round_down(limit_pfn, PFN_DOWN(PMD_SIZE));
  393. #else /* CONFIG_X86_64 */
  394. end_pfn = round_up(pfn, PFN_DOWN(PUD_SIZE));
  395. if (end_pfn > round_down(limit_pfn, PFN_DOWN(PMD_SIZE)))
  396. end_pfn = round_down(limit_pfn, PFN_DOWN(PMD_SIZE));
  397. #endif
  398. if (start_pfn < end_pfn) {
  399. nr_range = save_mr(mr, nr_range, start_pfn, end_pfn,
  400. page_size_mask & (1<<PG_LEVEL_2M));
  401. pfn = end_pfn;
  402. }
  403. #ifdef CONFIG_X86_64
  404. /* big page (1G) range */
  405. start_pfn = round_up(pfn, PFN_DOWN(PUD_SIZE));
  406. end_pfn = round_down(limit_pfn, PFN_DOWN(PUD_SIZE));
  407. if (start_pfn < end_pfn) {
  408. nr_range = save_mr(mr, nr_range, start_pfn, end_pfn,
  409. page_size_mask &
  410. ((1<<PG_LEVEL_2M)|(1<<PG_LEVEL_1G)));
  411. pfn = end_pfn;
  412. }
  413. /* tail is not big page (1G) alignment */
  414. start_pfn = round_up(pfn, PFN_DOWN(PMD_SIZE));
  415. end_pfn = round_down(limit_pfn, PFN_DOWN(PMD_SIZE));
  416. if (start_pfn < end_pfn) {
  417. nr_range = save_mr(mr, nr_range, start_pfn, end_pfn,
  418. page_size_mask & (1<<PG_LEVEL_2M));
  419. pfn = end_pfn;
  420. }
  421. #endif
  422. /* tail is not big page (2M) alignment */
  423. start_pfn = pfn;
  424. end_pfn = limit_pfn;
  425. nr_range = save_mr(mr, nr_range, start_pfn, end_pfn, 0);
  426. if (!after_bootmem)
  427. adjust_range_page_size_mask(mr, nr_range);
  428. /* try to merge same page size and continuous */
  429. for (i = 0; nr_range > 1 && i < nr_range - 1; i++) {
  430. unsigned long old_start;
  431. if (mr[i].end != mr[i+1].start ||
  432. mr[i].page_size_mask != mr[i+1].page_size_mask)
  433. continue;
  434. /* move it */
  435. old_start = mr[i].start;
  436. memmove(&mr[i], &mr[i+1],
  437. (nr_range - 1 - i) * sizeof(struct map_range));
  438. mr[i--].start = old_start;
  439. nr_range--;
  440. }
  441. for (i = 0; i < nr_range; i++)
  442. pr_debug(" [mem %#010lx-%#010lx] page %s\n",
  443. mr[i].start, mr[i].end - 1,
  444. page_size_string(&mr[i]));
  445. return nr_range;
  446. }
  447. struct range pfn_mapped[E820_MAX_ENTRIES];
  448. int nr_pfn_mapped;
  449. static void add_pfn_range_mapped(unsigned long start_pfn, unsigned long end_pfn)
  450. {
  451. nr_pfn_mapped = add_range_with_merge(pfn_mapped, E820_MAX_ENTRIES,
  452. nr_pfn_mapped, start_pfn, end_pfn);
  453. nr_pfn_mapped = clean_sort_range(pfn_mapped, E820_MAX_ENTRIES);
  454. max_pfn_mapped = max(max_pfn_mapped, end_pfn);
  455. if (start_pfn < (1UL<<(32-PAGE_SHIFT)))
  456. max_low_pfn_mapped = max(max_low_pfn_mapped,
  457. min(end_pfn, 1UL<<(32-PAGE_SHIFT)));
  458. }
  459. bool pfn_range_is_mapped(unsigned long start_pfn, unsigned long end_pfn)
  460. {
  461. int i;
  462. for (i = 0; i < nr_pfn_mapped; i++)
  463. if ((start_pfn >= pfn_mapped[i].start) &&
  464. (end_pfn <= pfn_mapped[i].end))
  465. return true;
  466. return false;
  467. }
  468. /*
  469. * Setup the direct mapping of the physical memory at PAGE_OFFSET.
  470. * This runs before bootmem is initialized and gets pages directly from
  471. * the physical memory. To access them they are temporarily mapped.
  472. */
  473. unsigned long __ref init_memory_mapping(unsigned long start,
  474. unsigned long end, pgprot_t prot)
  475. {
  476. struct map_range mr[NR_RANGE_MR];
  477. unsigned long ret = 0;
  478. int nr_range, i;
  479. pr_debug("init_memory_mapping: [mem %#010lx-%#010lx]\n",
  480. start, end - 1);
  481. memset(mr, 0, sizeof(mr));
  482. nr_range = split_mem_range(mr, 0, start, end);
  483. for (i = 0; i < nr_range; i++)
  484. ret = kernel_physical_mapping_init(mr[i].start, mr[i].end,
  485. mr[i].page_size_mask,
  486. prot);
  487. add_pfn_range_mapped(start >> PAGE_SHIFT, ret >> PAGE_SHIFT);
  488. return ret >> PAGE_SHIFT;
  489. }
  490. /*
  491. * We need to iterate through the E820 memory map and create direct mappings
  492. * for only E820_TYPE_RAM and E820_KERN_RESERVED regions. We cannot simply
  493. * create direct mappings for all pfns from [0 to max_low_pfn) and
  494. * [4GB to max_pfn) because of possible memory holes in high addresses
  495. * that cannot be marked as UC by fixed/variable range MTRRs.
  496. * Depending on the alignment of E820 ranges, this may possibly result
  497. * in using smaller size (i.e. 4K instead of 2M or 1G) page tables.
  498. *
  499. * init_mem_mapping() calls init_range_memory_mapping() with big range.
  500. * That range would have hole in the middle or ends, and only ram parts
  501. * will be mapped in init_range_memory_mapping().
  502. */
  503. static unsigned long __init init_range_memory_mapping(
  504. unsigned long r_start,
  505. unsigned long r_end)
  506. {
  507. unsigned long start_pfn, end_pfn;
  508. unsigned long mapped_ram_size = 0;
  509. int i;
  510. for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, NULL) {
  511. u64 start = clamp_val(PFN_PHYS(start_pfn), r_start, r_end);
  512. u64 end = clamp_val(PFN_PHYS(end_pfn), r_start, r_end);
  513. if (start >= end)
  514. continue;
  515. /*
  516. * if it is overlapping with brk pgt, we need to
  517. * alloc pgt buf from memblock instead.
  518. */
  519. can_use_brk_pgt = max(start, (u64)pgt_buf_end<<PAGE_SHIFT) >=
  520. min(end, (u64)pgt_buf_top<<PAGE_SHIFT);
  521. init_memory_mapping(start, end, PAGE_KERNEL);
  522. mapped_ram_size += end - start;
  523. can_use_brk_pgt = true;
  524. }
  525. return mapped_ram_size;
  526. }
  527. static unsigned long __init get_new_step_size(unsigned long step_size)
  528. {
  529. /*
  530. * Initial mapped size is PMD_SIZE (2M).
  531. * We can not set step_size to be PUD_SIZE (1G) yet.
  532. * In worse case, when we cross the 1G boundary, and
  533. * PG_LEVEL_2M is not set, we will need 1+1+512 pages (2M + 8k)
  534. * to map 1G range with PTE. Hence we use one less than the
  535. * difference of page table level shifts.
  536. *
  537. * Don't need to worry about overflow in the top-down case, on 32bit,
  538. * when step_size is 0, round_down() returns 0 for start, and that
  539. * turns it into 0x100000000ULL.
  540. * In the bottom-up case, round_up(x, 0) returns 0 though too, which
  541. * needs to be taken into consideration by the code below.
  542. */
  543. return step_size << (PMD_SHIFT - PAGE_SHIFT - 1);
  544. }
  545. /**
  546. * memory_map_top_down - Map [map_start, map_end) top down
  547. * @map_start: start address of the target memory range
  548. * @map_end: end address of the target memory range
  549. *
  550. * This function will setup direct mapping for memory range
  551. * [map_start, map_end) in top-down. That said, the page tables
  552. * will be allocated at the end of the memory, and we map the
  553. * memory in top-down.
  554. */
  555. static void __init memory_map_top_down(unsigned long map_start,
  556. unsigned long map_end)
  557. {
  558. unsigned long real_end, last_start;
  559. unsigned long step_size;
  560. unsigned long addr;
  561. unsigned long mapped_ram_size = 0;
  562. /*
  563. * Systems that have many reserved areas near top of the memory,
  564. * e.g. QEMU with less than 1G RAM and EFI enabled, or Xen, will
  565. * require lots of 4K mappings which may exhaust pgt_buf.
  566. * Start with top-most PMD_SIZE range aligned at PMD_SIZE to ensure
  567. * there is enough mapped memory that can be allocated from
  568. * memblock.
  569. */
  570. addr = memblock_phys_alloc_range(PMD_SIZE, PMD_SIZE, map_start,
  571. map_end);
  572. memblock_phys_free(addr, PMD_SIZE);
  573. real_end = addr + PMD_SIZE;
  574. /* step_size need to be small so pgt_buf from BRK could cover it */
  575. step_size = PMD_SIZE;
  576. max_pfn_mapped = 0; /* will get exact value next */
  577. min_pfn_mapped = real_end >> PAGE_SHIFT;
  578. last_start = real_end;
  579. /*
  580. * We start from the top (end of memory) and go to the bottom.
  581. * The memblock_find_in_range() gets us a block of RAM from the
  582. * end of RAM in [min_pfn_mapped, max_pfn_mapped) used as new pages
  583. * for page table.
  584. */
  585. while (last_start > map_start) {
  586. unsigned long start;
  587. if (last_start > step_size) {
  588. start = round_down(last_start - 1, step_size);
  589. if (start < map_start)
  590. start = map_start;
  591. } else
  592. start = map_start;
  593. mapped_ram_size += init_range_memory_mapping(start,
  594. last_start);
  595. last_start = start;
  596. min_pfn_mapped = last_start >> PAGE_SHIFT;
  597. if (mapped_ram_size >= step_size)
  598. step_size = get_new_step_size(step_size);
  599. }
  600. if (real_end < map_end)
  601. init_range_memory_mapping(real_end, map_end);
  602. }
  603. /**
  604. * memory_map_bottom_up - Map [map_start, map_end) bottom up
  605. * @map_start: start address of the target memory range
  606. * @map_end: end address of the target memory range
  607. *
  608. * This function will setup direct mapping for memory range
  609. * [map_start, map_end) in bottom-up. Since we have limited the
  610. * bottom-up allocation above the kernel, the page tables will
  611. * be allocated just above the kernel and we map the memory
  612. * in [map_start, map_end) in bottom-up.
  613. */
  614. static void __init memory_map_bottom_up(unsigned long map_start,
  615. unsigned long map_end)
  616. {
  617. unsigned long next, start;
  618. unsigned long mapped_ram_size = 0;
  619. /* step_size need to be small so pgt_buf from BRK could cover it */
  620. unsigned long step_size = PMD_SIZE;
  621. start = map_start;
  622. min_pfn_mapped = start >> PAGE_SHIFT;
  623. /*
  624. * We start from the bottom (@map_start) and go to the top (@map_end).
  625. * The memblock_find_in_range() gets us a block of RAM from the
  626. * end of RAM in [min_pfn_mapped, max_pfn_mapped) used as new pages
  627. * for page table.
  628. */
  629. while (start < map_end) {
  630. if (step_size && map_end - start > step_size) {
  631. next = round_up(start + 1, step_size);
  632. if (next > map_end)
  633. next = map_end;
  634. } else {
  635. next = map_end;
  636. }
  637. mapped_ram_size += init_range_memory_mapping(start, next);
  638. start = next;
  639. if (mapped_ram_size >= step_size)
  640. step_size = get_new_step_size(step_size);
  641. }
  642. }
  643. /*
  644. * The real mode trampoline, which is required for bootstrapping CPUs
  645. * occupies only a small area under the low 1MB. See reserve_real_mode()
  646. * for details.
  647. *
  648. * If KASLR is disabled the first PGD entry of the direct mapping is copied
  649. * to map the real mode trampoline.
  650. *
  651. * If KASLR is enabled, copy only the PUD which covers the low 1MB
  652. * area. This limits the randomization granularity to 1GB for both 4-level
  653. * and 5-level paging.
  654. */
  655. static void __init init_trampoline(void)
  656. {
  657. #ifdef CONFIG_X86_64
  658. /*
  659. * The code below will alias kernel page-tables in the user-range of the
  660. * address space, including the Global bit. So global TLB entries will
  661. * be created when using the trampoline page-table.
  662. */
  663. if (!kaslr_memory_enabled())
  664. trampoline_pgd_entry = init_top_pgt[pgd_index(__PAGE_OFFSET)];
  665. else
  666. init_trampoline_kaslr();
  667. #endif
  668. }
  669. void __init init_mem_mapping(void)
  670. {
  671. unsigned long end;
  672. pti_check_boottime_disable();
  673. probe_page_size_mask();
  674. setup_pcid();
  675. #ifdef CONFIG_X86_64
  676. end = max_pfn << PAGE_SHIFT;
  677. #else
  678. end = max_low_pfn << PAGE_SHIFT;
  679. #endif
  680. /* the ISA range is always mapped regardless of memory holes */
  681. init_memory_mapping(0, ISA_END_ADDRESS, PAGE_KERNEL);
  682. /* Init the trampoline, possibly with KASLR memory offset */
  683. init_trampoline();
  684. /*
  685. * If the allocation is in bottom-up direction, we setup direct mapping
  686. * in bottom-up, otherwise we setup direct mapping in top-down.
  687. */
  688. if (memblock_bottom_up()) {
  689. unsigned long kernel_end = __pa_symbol(_end);
  690. /*
  691. * we need two separate calls here. This is because we want to
  692. * allocate page tables above the kernel. So we first map
  693. * [kernel_end, end) to make memory above the kernel be mapped
  694. * as soon as possible. And then use page tables allocated above
  695. * the kernel to map [ISA_END_ADDRESS, kernel_end).
  696. */
  697. memory_map_bottom_up(kernel_end, end);
  698. memory_map_bottom_up(ISA_END_ADDRESS, kernel_end);
  699. } else {
  700. memory_map_top_down(ISA_END_ADDRESS, end);
  701. }
  702. #ifdef CONFIG_X86_64
  703. if (max_pfn > max_low_pfn) {
  704. /* can we preserve max_low_pfn ?*/
  705. max_low_pfn = max_pfn;
  706. }
  707. #else
  708. early_ioremap_page_table_range_init();
  709. #endif
  710. load_cr3(swapper_pg_dir);
  711. __flush_tlb_all();
  712. x86_init.hyper.init_mem_mapping();
  713. early_memtest(0, max_pfn_mapped << PAGE_SHIFT);
  714. }
  715. /*
  716. * Initialize an mm_struct to be used during poking and a pointer to be used
  717. * during patching.
  718. */
  719. void __init poking_init(void)
  720. {
  721. spinlock_t *ptl;
  722. pte_t *ptep;
  723. poking_mm = mm_alloc();
  724. BUG_ON(!poking_mm);
  725. /* Xen PV guests need the PGD to be pinned. */
  726. paravirt_arch_dup_mmap(NULL, poking_mm);
  727. /*
  728. * Randomize the poking address, but make sure that the following page
  729. * will be mapped at the same PMD. We need 2 pages, so find space for 3,
  730. * and adjust the address if the PMD ends after the first one.
  731. */
  732. poking_addr = TASK_UNMAPPED_BASE;
  733. if (IS_ENABLED(CONFIG_RANDOMIZE_BASE))
  734. poking_addr += (kaslr_get_random_long("Poking") & PAGE_MASK) %
  735. (TASK_SIZE - TASK_UNMAPPED_BASE - 3 * PAGE_SIZE);
  736. if (((poking_addr + PAGE_SIZE) & ~PMD_MASK) == 0)
  737. poking_addr += PAGE_SIZE;
  738. /*
  739. * We need to trigger the allocation of the page-tables that will be
  740. * needed for poking now. Later, poking may be performed in an atomic
  741. * section, which might cause allocation to fail.
  742. */
  743. ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
  744. BUG_ON(!ptep);
  745. pte_unmap_unlock(ptep, ptl);
  746. }
  747. /*
  748. * devmem_is_allowed() checks to see if /dev/mem access to a certain address
  749. * is valid. The argument is a physical page number.
  750. *
  751. * On x86, access has to be given to the first megabyte of RAM because that
  752. * area traditionally contains BIOS code and data regions used by X, dosemu,
  753. * and similar apps. Since they map the entire memory range, the whole range
  754. * must be allowed (for mapping), but any areas that would otherwise be
  755. * disallowed are flagged as being "zero filled" instead of rejected.
  756. * Access has to be given to non-kernel-ram areas as well, these contain the
  757. * PCI mmio resources as well as potential bios/acpi data regions.
  758. */
  759. int devmem_is_allowed(unsigned long pagenr)
  760. {
  761. if (region_intersects(PFN_PHYS(pagenr), PAGE_SIZE,
  762. IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE)
  763. != REGION_DISJOINT) {
  764. /*
  765. * For disallowed memory regions in the low 1MB range,
  766. * request that the page be shown as all zeros.
  767. */
  768. if (pagenr < 256)
  769. return 2;
  770. return 0;
  771. }
  772. /*
  773. * This must follow RAM test, since System RAM is considered a
  774. * restricted resource under CONFIG_STRICT_DEVMEM.
  775. */
  776. if (iomem_is_exclusive(pagenr << PAGE_SHIFT)) {
  777. /* Low 1MB bypasses iomem restrictions. */
  778. if (pagenr < 256)
  779. return 1;
  780. return 0;
  781. }
  782. return 1;
  783. }
  784. void free_init_pages(const char *what, unsigned long begin, unsigned long end)
  785. {
  786. unsigned long begin_aligned, end_aligned;
  787. /* Make sure boundaries are page aligned */
  788. begin_aligned = PAGE_ALIGN(begin);
  789. end_aligned = end & PAGE_MASK;
  790. if (WARN_ON(begin_aligned != begin || end_aligned != end)) {
  791. begin = begin_aligned;
  792. end = end_aligned;
  793. }
  794. if (begin >= end)
  795. return;
  796. /*
  797. * If debugging page accesses then do not free this memory but
  798. * mark them not present - any buggy init-section access will
  799. * create a kernel page fault:
  800. */
  801. if (debug_pagealloc_enabled()) {
  802. pr_info("debug: unmapping init [mem %#010lx-%#010lx]\n",
  803. begin, end - 1);
  804. /*
  805. * Inform kmemleak about the hole in the memory since the
  806. * corresponding pages will be unmapped.
  807. */
  808. kmemleak_free_part((void *)begin, end - begin);
  809. set_memory_np(begin, (end - begin) >> PAGE_SHIFT);
  810. } else {
  811. /*
  812. * We just marked the kernel text read only above, now that
  813. * we are going to free part of that, we need to make that
  814. * writeable and non-executable first.
  815. */
  816. set_memory_nx(begin, (end - begin) >> PAGE_SHIFT);
  817. set_memory_rw(begin, (end - begin) >> PAGE_SHIFT);
  818. free_reserved_area((void *)begin, (void *)end,
  819. POISON_FREE_INITMEM, what);
  820. }
  821. }
  822. /*
  823. * begin/end can be in the direct map or the "high kernel mapping"
  824. * used for the kernel image only. free_init_pages() will do the
  825. * right thing for either kind of address.
  826. */
  827. void free_kernel_image_pages(const char *what, void *begin, void *end)
  828. {
  829. unsigned long begin_ul = (unsigned long)begin;
  830. unsigned long end_ul = (unsigned long)end;
  831. unsigned long len_pages = (end_ul - begin_ul) >> PAGE_SHIFT;
  832. free_init_pages(what, begin_ul, end_ul);
  833. /*
  834. * PTI maps some of the kernel into userspace. For performance,
  835. * this includes some kernel areas that do not contain secrets.
  836. * Those areas might be adjacent to the parts of the kernel image
  837. * being freed, which may contain secrets. Remove the "high kernel
  838. * image mapping" for these freed areas, ensuring they are not even
  839. * potentially vulnerable to Meltdown regardless of the specific
  840. * optimizations PTI is currently using.
  841. *
  842. * The "noalias" prevents unmapping the direct map alias which is
  843. * needed to access the freed pages.
  844. *
  845. * This is only valid for 64bit kernels. 32bit has only one mapping
  846. * which can't be treated in this way for obvious reasons.
  847. */
  848. if (IS_ENABLED(CONFIG_X86_64) && cpu_feature_enabled(X86_FEATURE_PTI))
  849. set_memory_np_noalias(begin_ul, len_pages);
  850. }
  851. void __ref free_initmem(void)
  852. {
  853. e820__reallocate_tables();
  854. mem_encrypt_free_decrypted_mem();
  855. free_kernel_image_pages("unused kernel image (initmem)",
  856. &__init_begin, &__init_end);
  857. }
  858. #ifdef CONFIG_BLK_DEV_INITRD
  859. void __init free_initrd_mem(unsigned long start, unsigned long end)
  860. {
  861. /*
  862. * end could be not aligned, and We can not align that,
  863. * decompressor could be confused by aligned initrd_end
  864. * We already reserve the end partial page before in
  865. * - i386_start_kernel()
  866. * - x86_64_start_kernel()
  867. * - relocate_initrd()
  868. * So here We can do PAGE_ALIGN() safely to get partial page to be freed
  869. */
  870. free_init_pages("initrd", start, PAGE_ALIGN(end));
  871. }
  872. #endif
  873. /*
  874. * Calculate the precise size of the DMA zone (first 16 MB of RAM),
  875. * and pass it to the MM layer - to help it set zone watermarks more
  876. * accurately.
  877. *
  878. * Done on 64-bit systems only for the time being, although 32-bit systems
  879. * might benefit from this as well.
  880. */
  881. void __init memblock_find_dma_reserve(void)
  882. {
  883. #ifdef CONFIG_X86_64
  884. u64 nr_pages = 0, nr_free_pages = 0;
  885. unsigned long start_pfn, end_pfn;
  886. phys_addr_t start_addr, end_addr;
  887. int i;
  888. u64 u;
  889. /*
  890. * Iterate over all memory ranges (free and reserved ones alike),
  891. * to calculate the total number of pages in the first 16 MB of RAM:
  892. */
  893. nr_pages = 0;
  894. for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, NULL) {
  895. start_pfn = min(start_pfn, MAX_DMA_PFN);
  896. end_pfn = min(end_pfn, MAX_DMA_PFN);
  897. nr_pages += end_pfn - start_pfn;
  898. }
  899. /*
  900. * Iterate over free memory ranges to calculate the number of free
  901. * pages in the DMA zone, while not counting potential partial
  902. * pages at the beginning or the end of the range:
  903. */
  904. nr_free_pages = 0;
  905. for_each_free_mem_range(u, NUMA_NO_NODE, MEMBLOCK_NONE, &start_addr, &end_addr, NULL) {
  906. start_pfn = min_t(unsigned long, PFN_UP(start_addr), MAX_DMA_PFN);
  907. end_pfn = min_t(unsigned long, PFN_DOWN(end_addr), MAX_DMA_PFN);
  908. if (start_pfn < end_pfn)
  909. nr_free_pages += end_pfn - start_pfn;
  910. }
  911. set_dma_reserve(nr_pages - nr_free_pages);
  912. #endif
  913. }
  914. void __init zone_sizes_init(void)
  915. {
  916. unsigned long max_zone_pfns[MAX_NR_ZONES];
  917. memset(max_zone_pfns, 0, sizeof(max_zone_pfns));
  918. #ifdef CONFIG_ZONE_DMA
  919. max_zone_pfns[ZONE_DMA] = min(MAX_DMA_PFN, max_low_pfn);
  920. #endif
  921. #ifdef CONFIG_ZONE_DMA32
  922. max_zone_pfns[ZONE_DMA32] = disable_dma32 ? 0 : min(MAX_DMA32_PFN, max_low_pfn);
  923. #endif
  924. max_zone_pfns[ZONE_NORMAL] = max_low_pfn;
  925. #ifdef CONFIG_HIGHMEM
  926. max_zone_pfns[ZONE_HIGHMEM] = max_pfn;
  927. #endif
  928. free_area_init(max_zone_pfns);
  929. }
  930. static int __init early_disable_dma32(char *buf)
  931. {
  932. if (!buf)
  933. return -EINVAL;
  934. if (!strcmp(buf, "on"))
  935. disable_dma32 = true;
  936. return 0;
  937. }
  938. early_param("disable_dma32", early_disable_dma32);
  939. __visible DEFINE_PER_CPU_ALIGNED(struct tlb_state, cpu_tlbstate) = {
  940. .loaded_mm = &init_mm,
  941. .next_asid = 1,
  942. .cr4 = ~0UL, /* fail hard if we screw up cr4 shadow initialization */
  943. };
  944. void update_cache_mode_entry(unsigned entry, enum page_cache_mode cache)
  945. {
  946. /* entry 0 MUST be WB (hardwired to speed up translations) */
  947. BUG_ON(!entry && cache != _PAGE_CACHE_MODE_WB);
  948. __cachemode2pte_tbl[cache] = __cm_idx2pte(entry);
  949. __pte2cachemode_tbl[entry] = cache;
  950. }
  951. #ifdef CONFIG_SWAP
  952. unsigned long arch_max_swapfile_size(void)
  953. {
  954. unsigned long pages;
  955. pages = generic_max_swapfile_size();
  956. if (boot_cpu_has_bug(X86_BUG_L1TF) && l1tf_mitigation != L1TF_MITIGATION_OFF) {
  957. /* Limit the swap file size to MAX_PA/2 for L1TF workaround */
  958. unsigned long long l1tf_limit = l1tf_pfn_limit();
  959. /*
  960. * We encode swap offsets also with 3 bits below those for pfn
  961. * which makes the usable limit higher.
  962. */
  963. #if CONFIG_PGTABLE_LEVELS > 2
  964. l1tf_limit <<= PAGE_SHIFT - SWP_OFFSET_FIRST_BIT;
  965. #endif
  966. pages = min_t(unsigned long long, l1tf_limit, pages);
  967. }
  968. return pages;
  969. }
  970. #endif