Merge branch 'for-upstream' of git://git.kernel.org/pub/scm/linux/kernel/git/bluetoot...
[linux-2.6-microblaze.git] / arch / x86 / boot / compressed / kaslr.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * kaslr.c
4  *
5  * This contains the routines needed to generate a reasonable level of
6  * entropy to choose a randomized kernel base address offset in support
7  * of Kernel Address Space Layout Randomization (KASLR). Additionally
8  * handles walking the physical memory maps (and tracking memory regions
9  * to avoid) in order to select a physical memory location that can
10  * contain the entire properly aligned running kernel image.
11  *
12  */
13
14 /*
15  * isspace() in linux/ctype.h is expected by next_args() to filter
16  * out "space/lf/tab". While boot/ctype.h conflicts with linux/ctype.h,
17  * since isdigit() is implemented in both of them. Hence disable it
18  * here.
19  */
20 #define BOOT_CTYPE_H
21
22 /*
23  * _ctype[] in lib/ctype.c is needed by isspace() of linux/ctype.h.
24  * While both lib/ctype.c and lib/cmdline.c will bring EXPORT_SYMBOL
25  * which is meaningless and will cause compiling error in some cases.
26  */
27 #define __DISABLE_EXPORTS
28
29 #include "misc.h"
30 #include "error.h"
31 #include "../string.h"
32
33 #include <generated/compile.h>
34 #include <linux/module.h>
35 #include <linux/uts.h>
36 #include <linux/utsname.h>
37 #include <linux/ctype.h>
38 #include <linux/efi.h>
39 #include <generated/utsrelease.h>
40 #include <asm/efi.h>
41
42 /* Macros used by the included decompressor code below. */
43 #define STATIC
44 #include <linux/decompress/mm.h>
45
46 #ifdef CONFIG_X86_5LEVEL
47 unsigned int __pgtable_l5_enabled;
48 unsigned int pgdir_shift __ro_after_init = 39;
49 unsigned int ptrs_per_p4d __ro_after_init = 1;
50 #endif
51
52 extern unsigned long get_cmd_line_ptr(void);
53
54 /* Used by PAGE_KERN* macros: */
55 pteval_t __default_kernel_pte_mask __read_mostly = ~0;
56
57 /* Simplified build-specific string for starting entropy. */
58 static const char build_str[] = UTS_RELEASE " (" LINUX_COMPILE_BY "@"
59                 LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION;
60
61 static unsigned long rotate_xor(unsigned long hash, const void *area,
62                                 size_t size)
63 {
64         size_t i;
65         unsigned long *ptr = (unsigned long *)area;
66
67         for (i = 0; i < size / sizeof(hash); i++) {
68                 /* Rotate by odd number of bits and XOR. */
69                 hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7);
70                 hash ^= ptr[i];
71         }
72
73         return hash;
74 }
75
76 /* Attempt to create a simple but unpredictable starting entropy. */
77 static unsigned long get_boot_seed(void)
78 {
79         unsigned long hash = 0;
80
81         hash = rotate_xor(hash, build_str, sizeof(build_str));
82         hash = rotate_xor(hash, boot_params, sizeof(*boot_params));
83
84         return hash;
85 }
86
87 #define KASLR_COMPRESSED_BOOT
88 #include "../../lib/kaslr.c"
89
90
91 /* Only supporting at most 4 unusable memmap regions with kaslr */
92 #define MAX_MEMMAP_REGIONS      4
93
94 static bool memmap_too_large;
95
96
97 /* Store memory limit specified by "mem=nn[KMG]" or "memmap=nn[KMG]" */
98 static unsigned long long mem_limit = ULLONG_MAX;
99
100 /* Number of immovable memory regions */
101 static int num_immovable_mem;
102
103 enum mem_avoid_index {
104         MEM_AVOID_ZO_RANGE = 0,
105         MEM_AVOID_INITRD,
106         MEM_AVOID_CMDLINE,
107         MEM_AVOID_BOOTPARAMS,
108         MEM_AVOID_MEMMAP_BEGIN,
109         MEM_AVOID_MEMMAP_END = MEM_AVOID_MEMMAP_BEGIN + MAX_MEMMAP_REGIONS - 1,
110         MEM_AVOID_MAX,
111 };
112
113 static struct mem_vector mem_avoid[MEM_AVOID_MAX];
114
115 static bool mem_overlaps(struct mem_vector *one, struct mem_vector *two)
116 {
117         /* Item one is entirely before item two. */
118         if (one->start + one->size <= two->start)
119                 return false;
120         /* Item one is entirely after item two. */
121         if (one->start >= two->start + two->size)
122                 return false;
123         return true;
124 }
125
126 char *skip_spaces(const char *str)
127 {
128         while (isspace(*str))
129                 ++str;
130         return (char *)str;
131 }
132 #include "../../../../lib/ctype.c"
133 #include "../../../../lib/cmdline.c"
134
135 enum parse_mode {
136         PARSE_MEMMAP,
137         PARSE_EFI,
138 };
139
140 static int
141 parse_memmap(char *p, unsigned long long *start, unsigned long long *size,
142                 enum parse_mode mode)
143 {
144         char *oldp;
145
146         if (!p)
147                 return -EINVAL;
148
149         /* We don't care about this option here */
150         if (!strncmp(p, "exactmap", 8))
151                 return -EINVAL;
152
153         oldp = p;
154         *size = memparse(p, &p);
155         if (p == oldp)
156                 return -EINVAL;
157
158         switch (*p) {
159         case '#':
160         case '$':
161         case '!':
162                 *start = memparse(p + 1, &p);
163                 return 0;
164         case '@':
165                 if (mode == PARSE_MEMMAP) {
166                         /*
167                          * memmap=nn@ss specifies usable region, should
168                          * be skipped
169                          */
170                         *size = 0;
171                 } else {
172                         unsigned long long flags;
173
174                         /*
175                          * efi_fake_mem=nn@ss:attr the attr specifies
176                          * flags that might imply a soft-reservation.
177                          */
178                         *start = memparse(p + 1, &p);
179                         if (p && *p == ':') {
180                                 p++;
181                                 if (kstrtoull(p, 0, &flags) < 0)
182                                         *size = 0;
183                                 else if (flags & EFI_MEMORY_SP)
184                                         return 0;
185                         }
186                         *size = 0;
187                 }
188                 /* Fall through */
189         default:
190                 /*
191                  * If w/o offset, only size specified, memmap=nn[KMG] has the
192                  * same behaviour as mem=nn[KMG]. It limits the max address
193                  * system can use. Region above the limit should be avoided.
194                  */
195                 *start = 0;
196                 return 0;
197         }
198
199         return -EINVAL;
200 }
201
202 static void mem_avoid_memmap(enum parse_mode mode, char *str)
203 {
204         static int i;
205
206         if (i >= MAX_MEMMAP_REGIONS)
207                 return;
208
209         while (str && (i < MAX_MEMMAP_REGIONS)) {
210                 int rc;
211                 unsigned long long start, size;
212                 char *k = strchr(str, ',');
213
214                 if (k)
215                         *k++ = 0;
216
217                 rc = parse_memmap(str, &start, &size, mode);
218                 if (rc < 0)
219                         break;
220                 str = k;
221
222                 if (start == 0) {
223                         /* Store the specified memory limit if size > 0 */
224                         if (size > 0)
225                                 mem_limit = size;
226
227                         continue;
228                 }
229
230                 mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].start = start;
231                 mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].size = size;
232                 i++;
233         }
234
235         /* More than 4 memmaps, fail kaslr */
236         if ((i >= MAX_MEMMAP_REGIONS) && str)
237                 memmap_too_large = true;
238 }
239
240 /* Store the number of 1GB huge pages which users specified: */
241 static unsigned long max_gb_huge_pages;
242
243 static void parse_gb_huge_pages(char *param, char *val)
244 {
245         static bool gbpage_sz;
246         char *p;
247
248         if (!strcmp(param, "hugepagesz")) {
249                 p = val;
250                 if (memparse(p, &p) != PUD_SIZE) {
251                         gbpage_sz = false;
252                         return;
253                 }
254
255                 if (gbpage_sz)
256                         warn("Repeatedly set hugeTLB page size of 1G!\n");
257                 gbpage_sz = true;
258                 return;
259         }
260
261         if (!strcmp(param, "hugepages") && gbpage_sz) {
262                 p = val;
263                 max_gb_huge_pages = simple_strtoull(p, &p, 0);
264                 return;
265         }
266 }
267
268 static void handle_mem_options(void)
269 {
270         char *args = (char *)get_cmd_line_ptr();
271         size_t len = strlen((char *)args);
272         char *tmp_cmdline;
273         char *param, *val;
274         u64 mem_size;
275
276         if (!strstr(args, "memmap=") && !strstr(args, "mem=") &&
277                 !strstr(args, "hugepages"))
278                 return;
279
280         tmp_cmdline = malloc(len + 1);
281         if (!tmp_cmdline)
282                 error("Failed to allocate space for tmp_cmdline");
283
284         memcpy(tmp_cmdline, args, len);
285         tmp_cmdline[len] = 0;
286         args = tmp_cmdline;
287
288         /* Chew leading spaces */
289         args = skip_spaces(args);
290
291         while (*args) {
292                 args = next_arg(args, &param, &val);
293                 /* Stop at -- */
294                 if (!val && strcmp(param, "--") == 0) {
295                         warn("Only '--' specified in cmdline");
296                         goto out;
297                 }
298
299                 if (!strcmp(param, "memmap")) {
300                         mem_avoid_memmap(PARSE_MEMMAP, val);
301                 } else if (strstr(param, "hugepages")) {
302                         parse_gb_huge_pages(param, val);
303                 } else if (!strcmp(param, "mem")) {
304                         char *p = val;
305
306                         if (!strcmp(p, "nopentium"))
307                                 continue;
308                         mem_size = memparse(p, &p);
309                         if (mem_size == 0)
310                                 goto out;
311
312                         mem_limit = mem_size;
313                 } else if (!strcmp(param, "efi_fake_mem")) {
314                         mem_avoid_memmap(PARSE_EFI, val);
315                 }
316         }
317
318 out:
319         free(tmp_cmdline);
320         return;
321 }
322
323 /*
324  * In theory, KASLR can put the kernel anywhere in the range of [16M, 64T).
325  * The mem_avoid array is used to store the ranges that need to be avoided
326  * when KASLR searches for an appropriate random address. We must avoid any
327  * regions that are unsafe to overlap with during decompression, and other
328  * things like the initrd, cmdline and boot_params. This comment seeks to
329  * explain mem_avoid as clearly as possible since incorrect mem_avoid
330  * memory ranges lead to really hard to debug boot failures.
331  *
332  * The initrd, cmdline, and boot_params are trivial to identify for
333  * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
334  * MEM_AVOID_BOOTPARAMS respectively below.
335  *
336  * What is not obvious how to avoid is the range of memory that is used
337  * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
338  * the compressed kernel (ZO) and its run space, which is used to extract
339  * the uncompressed kernel (VO) and relocs.
340  *
341  * ZO's full run size sits against the end of the decompression buffer, so
342  * we can calculate where text, data, bss, etc of ZO are positioned more
343  * easily.
344  *
345  * For additional background, the decompression calculations can be found
346  * in header.S, and the memory diagram is based on the one found in misc.c.
347  *
348  * The following conditions are already enforced by the image layouts and
349  * associated code:
350  *  - input + input_size >= output + output_size
351  *  - kernel_total_size <= init_size
352  *  - kernel_total_size <= output_size (see Note below)
353  *  - output + init_size >= output + output_size
354  *
355  * (Note that kernel_total_size and output_size have no fundamental
356  * relationship, but output_size is passed to choose_random_location
357  * as a maximum of the two. The diagram is showing a case where
358  * kernel_total_size is larger than output_size, but this case is
359  * handled by bumping output_size.)
360  *
361  * The above conditions can be illustrated by a diagram:
362  *
363  * 0   output            input            input+input_size    output+init_size
364  * |     |                 |                             |             |
365  * |     |                 |                             |             |
366  * |-----|--------|--------|--------------|-----------|--|-------------|
367  *                |                       |           |
368  *                |                       |           |
369  * output+init_size-ZO_INIT_SIZE  output+output_size  output+kernel_total_size
370  *
371  * [output, output+init_size) is the entire memory range used for
372  * extracting the compressed image.
373  *
374  * [output, output+kernel_total_size) is the range needed for the
375  * uncompressed kernel (VO) and its run size (bss, brk, etc).
376  *
377  * [output, output+output_size) is VO plus relocs (i.e. the entire
378  * uncompressed payload contained by ZO). This is the area of the buffer
379  * written to during decompression.
380  *
381  * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
382  * range of the copied ZO and decompression code. (i.e. the range
383  * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
384  *
385  * [input, input+input_size) is the original copied compressed image (ZO)
386  * (i.e. it does not include its run size). This range must be avoided
387  * because it contains the data used for decompression.
388  *
389  * [input+input_size, output+init_size) is [_text, _end) for ZO. This
390  * range includes ZO's heap and stack, and must be avoided since it
391  * performs the decompression.
392  *
393  * Since the above two ranges need to be avoided and they are adjacent,
394  * they can be merged, resulting in: [input, output+init_size) which
395  * becomes the MEM_AVOID_ZO_RANGE below.
396  */
397 static void mem_avoid_init(unsigned long input, unsigned long input_size,
398                            unsigned long output)
399 {
400         unsigned long init_size = boot_params->hdr.init_size;
401         u64 initrd_start, initrd_size;
402         u64 cmd_line, cmd_line_size;
403         char *ptr;
404
405         /*
406          * Avoid the region that is unsafe to overlap during
407          * decompression.
408          */
409         mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
410         mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
411         add_identity_map(mem_avoid[MEM_AVOID_ZO_RANGE].start,
412                          mem_avoid[MEM_AVOID_ZO_RANGE].size);
413
414         /* Avoid initrd. */
415         initrd_start  = (u64)boot_params->ext_ramdisk_image << 32;
416         initrd_start |= boot_params->hdr.ramdisk_image;
417         initrd_size  = (u64)boot_params->ext_ramdisk_size << 32;
418         initrd_size |= boot_params->hdr.ramdisk_size;
419         mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
420         mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
421         /* No need to set mapping for initrd, it will be handled in VO. */
422
423         /* Avoid kernel command line. */
424         cmd_line  = (u64)boot_params->ext_cmd_line_ptr << 32;
425         cmd_line |= boot_params->hdr.cmd_line_ptr;
426         /* Calculate size of cmd_line. */
427         ptr = (char *)(unsigned long)cmd_line;
428         for (cmd_line_size = 0; ptr[cmd_line_size++];)
429                 ;
430         mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
431         mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
432         add_identity_map(mem_avoid[MEM_AVOID_CMDLINE].start,
433                          mem_avoid[MEM_AVOID_CMDLINE].size);
434
435         /* Avoid boot parameters. */
436         mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
437         mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
438         add_identity_map(mem_avoid[MEM_AVOID_BOOTPARAMS].start,
439                          mem_avoid[MEM_AVOID_BOOTPARAMS].size);
440
441         /* We don't need to set a mapping for setup_data. */
442
443         /* Mark the memmap regions we need to avoid */
444         handle_mem_options();
445
446         /* Enumerate the immovable memory regions */
447         num_immovable_mem = count_immovable_mem_regions();
448
449 #ifdef CONFIG_X86_VERBOSE_BOOTUP
450         /* Make sure video RAM can be used. */
451         add_identity_map(0, PMD_SIZE);
452 #endif
453 }
454
455 /*
456  * Does this memory vector overlap a known avoided area? If so, record the
457  * overlap region with the lowest address.
458  */
459 static bool mem_avoid_overlap(struct mem_vector *img,
460                               struct mem_vector *overlap)
461 {
462         int i;
463         struct setup_data *ptr;
464         unsigned long earliest = img->start + img->size;
465         bool is_overlapping = false;
466
467         for (i = 0; i < MEM_AVOID_MAX; i++) {
468                 if (mem_overlaps(img, &mem_avoid[i]) &&
469                     mem_avoid[i].start < earliest) {
470                         *overlap = mem_avoid[i];
471                         earliest = overlap->start;
472                         is_overlapping = true;
473                 }
474         }
475
476         /* Avoid all entries in the setup_data linked list. */
477         ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
478         while (ptr) {
479                 struct mem_vector avoid;
480
481                 avoid.start = (unsigned long)ptr;
482                 avoid.size = sizeof(*ptr) + ptr->len;
483
484                 if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
485                         *overlap = avoid;
486                         earliest = overlap->start;
487                         is_overlapping = true;
488                 }
489
490                 if (ptr->type == SETUP_INDIRECT &&
491                     ((struct setup_indirect *)ptr->data)->type != SETUP_INDIRECT) {
492                         avoid.start = ((struct setup_indirect *)ptr->data)->addr;
493                         avoid.size = ((struct setup_indirect *)ptr->data)->len;
494
495                         if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
496                                 *overlap = avoid;
497                                 earliest = overlap->start;
498                                 is_overlapping = true;
499                         }
500                 }
501
502                 ptr = (struct setup_data *)(unsigned long)ptr->next;
503         }
504
505         return is_overlapping;
506 }
507
508 struct slot_area {
509         unsigned long addr;
510         int num;
511 };
512
513 #define MAX_SLOT_AREA 100
514
515 static struct slot_area slot_areas[MAX_SLOT_AREA];
516
517 static unsigned long slot_max;
518
519 static unsigned long slot_area_index;
520
521 static void store_slot_info(struct mem_vector *region, unsigned long image_size)
522 {
523         struct slot_area slot_area;
524
525         if (slot_area_index == MAX_SLOT_AREA)
526                 return;
527
528         slot_area.addr = region->start;
529         slot_area.num = (region->size - image_size) /
530                         CONFIG_PHYSICAL_ALIGN + 1;
531
532         if (slot_area.num > 0) {
533                 slot_areas[slot_area_index++] = slot_area;
534                 slot_max += slot_area.num;
535         }
536 }
537
538 /*
539  * Skip as many 1GB huge pages as possible in the passed region
540  * according to the number which users specified:
541  */
542 static void
543 process_gb_huge_pages(struct mem_vector *region, unsigned long image_size)
544 {
545         unsigned long addr, size = 0;
546         struct mem_vector tmp;
547         int i = 0;
548
549         if (!max_gb_huge_pages) {
550                 store_slot_info(region, image_size);
551                 return;
552         }
553
554         addr = ALIGN(region->start, PUD_SIZE);
555         /* Did we raise the address above the passed in memory entry? */
556         if (addr < region->start + region->size)
557                 size = region->size - (addr - region->start);
558
559         /* Check how many 1GB huge pages can be filtered out: */
560         while (size > PUD_SIZE && max_gb_huge_pages) {
561                 size -= PUD_SIZE;
562                 max_gb_huge_pages--;
563                 i++;
564         }
565
566         /* No good 1GB huge pages found: */
567         if (!i) {
568                 store_slot_info(region, image_size);
569                 return;
570         }
571
572         /*
573          * Skip those 'i'*1GB good huge pages, and continue checking and
574          * processing the remaining head or tail part of the passed region
575          * if available.
576          */
577
578         if (addr >= region->start + image_size) {
579                 tmp.start = region->start;
580                 tmp.size = addr - region->start;
581                 store_slot_info(&tmp, image_size);
582         }
583
584         size  = region->size - (addr - region->start) - i * PUD_SIZE;
585         if (size >= image_size) {
586                 tmp.start = addr + i * PUD_SIZE;
587                 tmp.size = size;
588                 store_slot_info(&tmp, image_size);
589         }
590 }
591
592 static unsigned long slots_fetch_random(void)
593 {
594         unsigned long slot;
595         int i;
596
597         /* Handle case of no slots stored. */
598         if (slot_max == 0)
599                 return 0;
600
601         slot = kaslr_get_random_long("Physical") % slot_max;
602
603         for (i = 0; i < slot_area_index; i++) {
604                 if (slot >= slot_areas[i].num) {
605                         slot -= slot_areas[i].num;
606                         continue;
607                 }
608                 return slot_areas[i].addr + slot * CONFIG_PHYSICAL_ALIGN;
609         }
610
611         if (i == slot_area_index)
612                 debug_putstr("slots_fetch_random() failed!?\n");
613         return 0;
614 }
615
616 static void __process_mem_region(struct mem_vector *entry,
617                                  unsigned long minimum,
618                                  unsigned long image_size)
619 {
620         struct mem_vector region, overlap;
621         unsigned long start_orig, end;
622         struct mem_vector cur_entry;
623
624         /* On 32-bit, ignore entries entirely above our maximum. */
625         if (IS_ENABLED(CONFIG_X86_32) && entry->start >= KERNEL_IMAGE_SIZE)
626                 return;
627
628         /* Ignore entries entirely below our minimum. */
629         if (entry->start + entry->size < minimum)
630                 return;
631
632         /* Ignore entries above memory limit */
633         end = min(entry->size + entry->start, mem_limit);
634         if (entry->start >= end)
635                 return;
636         cur_entry.start = entry->start;
637         cur_entry.size = end - entry->start;
638
639         region.start = cur_entry.start;
640         region.size = cur_entry.size;
641
642         /* Give up if slot area array is full. */
643         while (slot_area_index < MAX_SLOT_AREA) {
644                 start_orig = region.start;
645
646                 /* Potentially raise address to minimum location. */
647                 if (region.start < minimum)
648                         region.start = minimum;
649
650                 /* Potentially raise address to meet alignment needs. */
651                 region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
652
653                 /* Did we raise the address above the passed in memory entry? */
654                 if (region.start > cur_entry.start + cur_entry.size)
655                         return;
656
657                 /* Reduce size by any delta from the original address. */
658                 region.size -= region.start - start_orig;
659
660                 /* On 32-bit, reduce region size to fit within max size. */
661                 if (IS_ENABLED(CONFIG_X86_32) &&
662                     region.start + region.size > KERNEL_IMAGE_SIZE)
663                         region.size = KERNEL_IMAGE_SIZE - region.start;
664
665                 /* Return if region can't contain decompressed kernel */
666                 if (region.size < image_size)
667                         return;
668
669                 /* If nothing overlaps, store the region and return. */
670                 if (!mem_avoid_overlap(&region, &overlap)) {
671                         process_gb_huge_pages(&region, image_size);
672                         return;
673                 }
674
675                 /* Store beginning of region if holds at least image_size. */
676                 if (overlap.start > region.start + image_size) {
677                         struct mem_vector beginning;
678
679                         beginning.start = region.start;
680                         beginning.size = overlap.start - region.start;
681                         process_gb_huge_pages(&beginning, image_size);
682                 }
683
684                 /* Return if overlap extends to or past end of region. */
685                 if (overlap.start + overlap.size >= region.start + region.size)
686                         return;
687
688                 /* Clip off the overlapping region and start over. */
689                 region.size -= overlap.start - region.start + overlap.size;
690                 region.start = overlap.start + overlap.size;
691         }
692 }
693
694 static bool process_mem_region(struct mem_vector *region,
695                                unsigned long long minimum,
696                                unsigned long long image_size)
697 {
698         int i;
699         /*
700          * If no immovable memory found, or MEMORY_HOTREMOVE disabled,
701          * use @region directly.
702          */
703         if (!num_immovable_mem) {
704                 __process_mem_region(region, minimum, image_size);
705
706                 if (slot_area_index == MAX_SLOT_AREA) {
707                         debug_putstr("Aborted e820/efi memmap scan (slot_areas full)!\n");
708                         return 1;
709                 }
710                 return 0;
711         }
712
713 #if defined(CONFIG_MEMORY_HOTREMOVE) && defined(CONFIG_ACPI)
714         /*
715          * If immovable memory found, filter the intersection between
716          * immovable memory and @region.
717          */
718         for (i = 0; i < num_immovable_mem; i++) {
719                 unsigned long long start, end, entry_end, region_end;
720                 struct mem_vector entry;
721
722                 if (!mem_overlaps(region, &immovable_mem[i]))
723                         continue;
724
725                 start = immovable_mem[i].start;
726                 end = start + immovable_mem[i].size;
727                 region_end = region->start + region->size;
728
729                 entry.start = clamp(region->start, start, end);
730                 entry_end = clamp(region_end, start, end);
731                 entry.size = entry_end - entry.start;
732
733                 __process_mem_region(&entry, minimum, image_size);
734
735                 if (slot_area_index == MAX_SLOT_AREA) {
736                         debug_putstr("Aborted e820/efi memmap scan when walking immovable regions(slot_areas full)!\n");
737                         return 1;
738                 }
739         }
740 #endif
741         return 0;
742 }
743
744 #ifdef CONFIG_EFI
745 /*
746  * Returns true if mirror region found (and must have been processed
747  * for slots adding)
748  */
749 static bool
750 process_efi_entries(unsigned long minimum, unsigned long image_size)
751 {
752         struct efi_info *e = &boot_params->efi_info;
753         bool efi_mirror_found = false;
754         struct mem_vector region;
755         efi_memory_desc_t *md;
756         unsigned long pmap;
757         char *signature;
758         u32 nr_desc;
759         int i;
760
761         signature = (char *)&e->efi_loader_signature;
762         if (strncmp(signature, EFI32_LOADER_SIGNATURE, 4) &&
763             strncmp(signature, EFI64_LOADER_SIGNATURE, 4))
764                 return false;
765
766 #ifdef CONFIG_X86_32
767         /* Can't handle data above 4GB at this time */
768         if (e->efi_memmap_hi) {
769                 warn("EFI memmap is above 4GB, can't be handled now on x86_32. EFI should be disabled.\n");
770                 return false;
771         }
772         pmap =  e->efi_memmap;
773 #else
774         pmap = (e->efi_memmap | ((__u64)e->efi_memmap_hi << 32));
775 #endif
776
777         nr_desc = e->efi_memmap_size / e->efi_memdesc_size;
778         for (i = 0; i < nr_desc; i++) {
779                 md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);
780                 if (md->attribute & EFI_MEMORY_MORE_RELIABLE) {
781                         efi_mirror_found = true;
782                         break;
783                 }
784         }
785
786         for (i = 0; i < nr_desc; i++) {
787                 md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);
788
789                 /*
790                  * Here we are more conservative in picking free memory than
791                  * the EFI spec allows:
792                  *
793                  * According to the spec, EFI_BOOT_SERVICES_{CODE|DATA} are also
794                  * free memory and thus available to place the kernel image into,
795                  * but in practice there's firmware where using that memory leads
796                  * to crashes.
797                  *
798                  * Only EFI_CONVENTIONAL_MEMORY is guaranteed to be free.
799                  */
800                 if (md->type != EFI_CONVENTIONAL_MEMORY)
801                         continue;
802
803                 if (efi_soft_reserve_enabled() &&
804                     (md->attribute & EFI_MEMORY_SP))
805                         continue;
806
807                 if (efi_mirror_found &&
808                     !(md->attribute & EFI_MEMORY_MORE_RELIABLE))
809                         continue;
810
811                 region.start = md->phys_addr;
812                 region.size = md->num_pages << EFI_PAGE_SHIFT;
813                 if (process_mem_region(&region, minimum, image_size))
814                         break;
815         }
816         return true;
817 }
818 #else
819 static inline bool
820 process_efi_entries(unsigned long minimum, unsigned long image_size)
821 {
822         return false;
823 }
824 #endif
825
826 static void process_e820_entries(unsigned long minimum,
827                                  unsigned long image_size)
828 {
829         int i;
830         struct mem_vector region;
831         struct boot_e820_entry *entry;
832
833         /* Verify potential e820 positions, appending to slots list. */
834         for (i = 0; i < boot_params->e820_entries; i++) {
835                 entry = &boot_params->e820_table[i];
836                 /* Skip non-RAM entries. */
837                 if (entry->type != E820_TYPE_RAM)
838                         continue;
839                 region.start = entry->addr;
840                 region.size = entry->size;
841                 if (process_mem_region(&region, minimum, image_size))
842                         break;
843         }
844 }
845
846 static unsigned long find_random_phys_addr(unsigned long minimum,
847                                            unsigned long image_size)
848 {
849         /* Check if we had too many memmaps. */
850         if (memmap_too_large) {
851                 debug_putstr("Aborted memory entries scan (more than 4 memmap= args)!\n");
852                 return 0;
853         }
854
855         /* Make sure minimum is aligned. */
856         minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
857
858         if (process_efi_entries(minimum, image_size))
859                 return slots_fetch_random();
860
861         process_e820_entries(minimum, image_size);
862         return slots_fetch_random();
863 }
864
865 static unsigned long find_random_virt_addr(unsigned long minimum,
866                                            unsigned long image_size)
867 {
868         unsigned long slots, random_addr;
869
870         /* Make sure minimum is aligned. */
871         minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
872         /* Align image_size for easy slot calculations. */
873         image_size = ALIGN(image_size, CONFIG_PHYSICAL_ALIGN);
874
875         /*
876          * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
877          * that can hold image_size within the range of minimum to
878          * KERNEL_IMAGE_SIZE?
879          */
880         slots = (KERNEL_IMAGE_SIZE - minimum - image_size) /
881                  CONFIG_PHYSICAL_ALIGN + 1;
882
883         random_addr = kaslr_get_random_long("Virtual") % slots;
884
885         return random_addr * CONFIG_PHYSICAL_ALIGN + minimum;
886 }
887
888 /*
889  * Since this function examines addresses much more numerically,
890  * it takes the input and output pointers as 'unsigned long'.
891  */
892 void choose_random_location(unsigned long input,
893                             unsigned long input_size,
894                             unsigned long *output,
895                             unsigned long output_size,
896                             unsigned long *virt_addr)
897 {
898         unsigned long random_addr, min_addr;
899
900         if (cmdline_find_option_bool("nokaslr")) {
901                 warn("KASLR disabled: 'nokaslr' on cmdline.");
902                 return;
903         }
904
905 #ifdef CONFIG_X86_5LEVEL
906         if (__read_cr4() & X86_CR4_LA57) {
907                 __pgtable_l5_enabled = 1;
908                 pgdir_shift = 48;
909                 ptrs_per_p4d = 512;
910         }
911 #endif
912
913         boot_params->hdr.loadflags |= KASLR_FLAG;
914
915         /* Prepare to add new identity pagetables on demand. */
916         initialize_identity_maps();
917
918         /* Record the various known unsafe memory ranges. */
919         mem_avoid_init(input, input_size, *output);
920
921         /*
922          * Low end of the randomization range should be the
923          * smaller of 512M or the initial kernel image
924          * location:
925          */
926         min_addr = min(*output, 512UL << 20);
927
928         /* Walk available memory entries to find a random address. */
929         random_addr = find_random_phys_addr(min_addr, output_size);
930         if (!random_addr) {
931                 warn("Physical KASLR disabled: no suitable memory region!");
932         } else {
933                 /* Update the new physical address location. */
934                 if (*output != random_addr) {
935                         add_identity_map(random_addr, output_size);
936                         *output = random_addr;
937                 }
938
939                 /*
940                  * This loads the identity mapping page table.
941                  * This should only be done if a new physical address
942                  * is found for the kernel, otherwise we should keep
943                  * the old page table to make it be like the "nokaslr"
944                  * case.
945                  */
946                 finalize_identity_maps();
947         }
948
949
950         /* Pick random virtual address starting from LOAD_PHYSICAL_ADDR. */
951         if (IS_ENABLED(CONFIG_X86_64))
952                 random_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, output_size);
953         *virt_addr = random_addr;
954 }