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