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