kaslr.c 24.6 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2 3 4 5 6 7 8 9 10 11 12
/*
 * kaslr.c
 *
 * This contains the routines needed to generate a reasonable level of
 * entropy to choose a randomized kernel base address offset in support
 * of Kernel Address Space Layout Randomization (KASLR). Additionally
 * handles walking the physical memory maps (and tracking memory regions
 * to avoid) in order to select a physical memory location that can
 * contain the entire properly aligned running kernel image.
 *
 */
13 14 15 16 17 18 19 20 21 22 23 24 25 26

/*
 * isspace() in linux/ctype.h is expected by next_args() to filter
 * out "space/lf/tab". While boot/ctype.h conflicts with linux/ctype.h,
 * since isdigit() is implemented in both of them. Hence disable it
 * here.
 */
#define BOOT_CTYPE_H

/*
 * _ctype[] in lib/ctype.c is needed by isspace() of linux/ctype.h.
 * While both lib/ctype.c and lib/cmdline.c will bring EXPORT_SYMBOL
 * which is meaningless and will cause compiling error in some cases.
 */
27
#define __DISABLE_EXPORTS
28

29
#include "misc.h"
30
#include "error.h"
31
#include "../string.h"
32

33 34 35 36
#include <generated/compile.h>
#include <linux/module.h>
#include <linux/uts.h>
#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 43 44 45
/* Macros used by the included decompressor code below. */
#define STATIC
#include <linux/decompress/mm.h>

46
#ifdef CONFIG_X86_5LEVEL
47
unsigned int __pgtable_l5_enabled;
48 49
unsigned int pgdir_shift __ro_after_init = 39;
unsigned int ptrs_per_p4d __ro_after_init = 1;
50 51
#endif

52 53
extern unsigned long get_cmd_line_ptr(void);

54 55 56
/* Used by PAGE_KERN* macros: */
pteval_t __default_kernel_pte_mask __read_mostly = ~0;

57
/* Simplified build-specific string for starting entropy. */
58
static const char build_str[] = UTS_RELEASE " (" LINUX_COMPILE_BY "@"
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
		LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION;

static unsigned long rotate_xor(unsigned long hash, const void *area,
				size_t size)
{
	size_t i;
	unsigned long *ptr = (unsigned long *)area;

	for (i = 0; i < size / sizeof(hash); i++) {
		/* Rotate by odd number of bits and XOR. */
		hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7);
		hash ^= ptr[i];
	}

	return hash;
}

/* Attempt to create a simple but unpredictable starting entropy. */
77
static unsigned long get_boot_seed(void)
78 79 80 81
{
	unsigned long hash = 0;

	hash = rotate_xor(hash, build_str, sizeof(build_str));
82
	hash = rotate_xor(hash, boot_params, sizeof(*boot_params));
83 84 85 86

	return hash;
}

87 88
#define KASLR_COMPRESSED_BOOT
#include "../../lib/kaslr.c"
89

90

91 92 93 94 95
/* Only supporting at most 4 unusable memmap regions with kaslr */
#define MAX_MEMMAP_REGIONS	4

static bool memmap_too_large;

96

97 98 99 100 101
/*
 * Store memory limit: MAXMEM on 64-bit and KERNEL_IMAGE_SIZE on 32-bit.
 * It may be reduced by "mem=nn[KMG]" or "memmap=nn[KMG]" command line options.
 */
static unsigned long long mem_limit;
102

103 104
/* Number of immovable memory regions */
static int num_immovable_mem;
105

106 107 108 109 110
enum mem_avoid_index {
	MEM_AVOID_ZO_RANGE = 0,
	MEM_AVOID_INITRD,
	MEM_AVOID_CMDLINE,
	MEM_AVOID_BOOTPARAMS,
111 112
	MEM_AVOID_MEMMAP_BEGIN,
	MEM_AVOID_MEMMAP_END = MEM_AVOID_MEMMAP_BEGIN + MAX_MEMMAP_REGIONS - 1,
113 114 115
	MEM_AVOID_MAX,
};

116
static struct mem_vector mem_avoid[MEM_AVOID_MAX];
117 118 119 120 121 122 123 124 125 126 127 128

static bool mem_overlaps(struct mem_vector *one, struct mem_vector *two)
{
	/* Item one is entirely before item two. */
	if (one->start + one->size <= two->start)
		return false;
	/* Item one is entirely after item two. */
	if (one->start >= two->start + two->size)
		return false;
	return true;
}

129
char *skip_spaces(const char *str)
130
{
131 132 133
	while (isspace(*str))
		++str;
	return (char *)str;
134
}
135 136
#include "../../../../lib/ctype.c"
#include "../../../../lib/cmdline.c"
137

138 139 140 141 142
enum parse_mode {
	PARSE_MEMMAP,
	PARSE_EFI,
};

143
static int
144 145
parse_memmap(char *p, unsigned long long *start, unsigned long long *size,
		enum parse_mode mode)
146 147 148 149 150 151 152 153 154 155 156
{
	char *oldp;

	if (!p)
		return -EINVAL;

	/* We don't care about this option here */
	if (!strncmp(p, "exactmap", 8))
		return -EINVAL;

	oldp = p;
157
	*size = memparse(p, &p);
158 159 160 161 162 163 164
	if (p == oldp)
		return -EINVAL;

	switch (*p) {
	case '#':
	case '$':
	case '!':
165
		*start = memparse(p + 1, &p);
166
		return 0;
167
	case '@':
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
		if (mode == PARSE_MEMMAP) {
			/*
			 * memmap=nn@ss specifies usable region, should
			 * be skipped
			 */
			*size = 0;
		} else {
			unsigned long long flags;

			/*
			 * efi_fake_mem=nn@ss:attr the attr specifies
			 * flags that might imply a soft-reservation.
			 */
			*start = memparse(p + 1, &p);
			if (p && *p == ':') {
				p++;
				if (kstrtoull(p, 0, &flags) < 0)
					*size = 0;
				else if (flags & EFI_MEMORY_SP)
					return 0;
			}
			*size = 0;
		}
191 192 193 194 195 196 197 198
		/* Fall through */
	default:
		/*
		 * If w/o offset, only size specified, memmap=nn[KMG] has the
		 * same behaviour as mem=nn[KMG]. It limits the max address
		 * system can use. Region above the limit should be avoided.
		 */
		*start = 0;
199 200 201 202 203 204
		return 0;
	}

	return -EINVAL;
}

205
static void mem_avoid_memmap(enum parse_mode mode, char *str)
206
{
207
	static int i;
208

209
	if (i >= MAX_MEMMAP_REGIONS)
210 211 212 213 214 215 216 217 218 219
		return;

	while (str && (i < MAX_MEMMAP_REGIONS)) {
		int rc;
		unsigned long long start, size;
		char *k = strchr(str, ',');

		if (k)
			*k++ = 0;

220
		rc = parse_memmap(str, &start, &size, mode);
221 222 223
		if (rc < 0)
			break;
		str = k;
224 225 226

		if (start == 0) {
			/* Store the specified memory limit if size > 0 */
227
			if (size > 0 && size < mem_limit)
228 229
				mem_limit = size;

230
			continue;
231
		}
232 233 234 235 236 237 238 239 240 241 242

		mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].start = start;
		mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].size = size;
		i++;
	}

	/* More than 4 memmaps, fail kaslr */
	if ((i >= MAX_MEMMAP_REGIONS) && str)
		memmap_too_large = true;
}

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
/* Store the number of 1GB huge pages which users specified: */
static unsigned long max_gb_huge_pages;

static void parse_gb_huge_pages(char *param, char *val)
{
	static bool gbpage_sz;
	char *p;

	if (!strcmp(param, "hugepagesz")) {
		p = val;
		if (memparse(p, &p) != PUD_SIZE) {
			gbpage_sz = false;
			return;
		}

		if (gbpage_sz)
			warn("Repeatedly set hugeTLB page size of 1G!\n");
		gbpage_sz = true;
		return;
	}

	if (!strcmp(param, "hugepages") && gbpage_sz) {
		p = val;
		max_gb_huge_pages = simple_strtoull(p, &p, 0);
		return;
	}
}

271
static void handle_mem_options(void)
272 273
{
	char *args = (char *)get_cmd_line_ptr();
274
	size_t len;
275 276
	char *tmp_cmdline;
	char *param, *val;
277
	u64 mem_size;
278

279 280 281
	if (!args)
		return;

282 283
	if (!strstr(args, "memmap=") && !strstr(args, "mem=") &&
		!strstr(args, "hugepages"))
284
		return;
285

286
	len = strlen(args);
287
	tmp_cmdline = malloc(len + 1);
288
	if (!tmp_cmdline)
289 290 291 292 293 294 295 296 297 298 299 300
		error("Failed to allocate space for tmp_cmdline");

	memcpy(tmp_cmdline, args, len);
	tmp_cmdline[len] = 0;
	args = tmp_cmdline;

	/* Chew leading spaces */
	args = skip_spaces(args);

	while (*args) {
		args = next_arg(args, &param, &val);
		/* Stop at -- */
301 302
		if (!val && strcmp(param, "--") == 0)
			break;
303

304
		if (!strcmp(param, "memmap")) {
305
			mem_avoid_memmap(PARSE_MEMMAP, val);
306 307
		} else if (strstr(param, "hugepages")) {
			parse_gb_huge_pages(param, val);
308 309 310 311 312 313
		} else if (!strcmp(param, "mem")) {
			char *p = val;

			if (!strcmp(p, "nopentium"))
				continue;
			mem_size = memparse(p, &p);
314
			if (mem_size == 0)
315
				break;
316

317 318
			if (mem_size < mem_limit)
				mem_limit = mem_size;
319 320
		} else if (!strcmp(param, "efi_fake_mem")) {
			mem_avoid_memmap(PARSE_EFI, val);
321
		}
322 323 324
	}

	free(tmp_cmdline);
325
	return;
326 327
}

328
/*
329 330 331
 * In theory, KASLR can put the kernel anywhere in the range of [16M, MAXMEM)
 * on 64-bit, and [16M, KERNEL_IMAGE_SIZE) on 32-bit.
 *
332 333
 * The mem_avoid array is used to store the ranges that need to be avoided
 * when KASLR searches for an appropriate random address. We must avoid any
334
 * regions that are unsafe to overlap with during decompression, and other
335 336 337 338 339
 * things like the initrd, cmdline and boot_params. This comment seeks to
 * explain mem_avoid as clearly as possible since incorrect mem_avoid
 * memory ranges lead to really hard to debug boot failures.
 *
 * The initrd, cmdline, and boot_params are trivial to identify for
340
 * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
 * MEM_AVOID_BOOTPARAMS respectively below.
 *
 * What is not obvious how to avoid is the range of memory that is used
 * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
 * the compressed kernel (ZO) and its run space, which is used to extract
 * the uncompressed kernel (VO) and relocs.
 *
 * ZO's full run size sits against the end of the decompression buffer, so
 * we can calculate where text, data, bss, etc of ZO are positioned more
 * easily.
 *
 * For additional background, the decompression calculations can be found
 * in header.S, and the memory diagram is based on the one found in misc.c.
 *
 * The following conditions are already enforced by the image layouts and
 * associated code:
 *  - input + input_size >= output + output_size
 *  - kernel_total_size <= init_size
 *  - kernel_total_size <= output_size (see Note below)
 *  - output + init_size >= output + output_size
361
 *
362 363 364 365 366
 * (Note that kernel_total_size and output_size have no fundamental
 * relationship, but output_size is passed to choose_random_location
 * as a maximum of the two. The diagram is showing a case where
 * kernel_total_size is larger than output_size, but this case is
 * handled by bumping output_size.)
367
 *
368
 * The above conditions can be illustrated by a diagram:
369
 *
370 371 372 373 374 375 376
 * 0   output            input            input+input_size    output+init_size
 * |     |                 |                             |             |
 * |     |                 |                             |             |
 * |-----|--------|--------|--------------|-----------|--|-------------|
 *                |                       |           |
 *                |                       |           |
 * output+init_size-ZO_INIT_SIZE  output+output_size  output+kernel_total_size
377
 *
378 379
 * [output, output+init_size) is the entire memory range used for
 * extracting the compressed image.
380
 *
381 382
 * [output, output+kernel_total_size) is the range needed for the
 * uncompressed kernel (VO) and its run size (bss, brk, etc).
383
 *
384 385 386
 * [output, output+output_size) is VO plus relocs (i.e. the entire
 * uncompressed payload contained by ZO). This is the area of the buffer
 * written to during decompression.
387
 *
388 389 390
 * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
 * range of the copied ZO and decompression code. (i.e. the range
 * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
391
 *
392 393 394
 * [input, input+input_size) is the original copied compressed image (ZO)
 * (i.e. it does not include its run size). This range must be avoided
 * because it contains the data used for decompression.
395
 *
396 397 398
 * [input+input_size, output+init_size) is [_text, _end) for ZO. This
 * range includes ZO's heap and stack, and must be avoided since it
 * performs the decompression.
399
 *
400 401 402
 * Since the above two ranges need to be avoided and they are adjacent,
 * they can be merged, resulting in: [input, output+init_size) which
 * becomes the MEM_AVOID_ZO_RANGE below.
403
 */
404
static void mem_avoid_init(unsigned long input, unsigned long input_size,
405
			   unsigned long output)
406
{
407
	unsigned long init_size = boot_params->hdr.init_size;
408
	u64 initrd_start, initrd_size;
409
	unsigned long cmd_line, cmd_line_size;
410 411 412

	/*
	 * Avoid the region that is unsafe to overlap during
413
	 * decompression.
414
	 */
415 416
	mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
	mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
417 418
	add_identity_map(mem_avoid[MEM_AVOID_ZO_RANGE].start,
			 mem_avoid[MEM_AVOID_ZO_RANGE].size);
419 420

	/* Avoid initrd. */
421 422 423 424
	initrd_start  = (u64)boot_params->ext_ramdisk_image << 32;
	initrd_start |= boot_params->hdr.ramdisk_image;
	initrd_size  = (u64)boot_params->ext_ramdisk_size << 32;
	initrd_size |= boot_params->hdr.ramdisk_size;
425 426
	mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
	mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
427
	/* No need to set mapping for initrd, it will be handled in VO. */
428 429

	/* Avoid kernel command line. */
430
	cmd_line = get_cmd_line_ptr();
431
	/* Calculate size of cmd_line. */
432 433 434 435 436 437 438
	if (cmd_line) {
		cmd_line_size = strlen((char *)cmd_line) + 1;
		mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
		mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
		add_identity_map(mem_avoid[MEM_AVOID_CMDLINE].start,
				 mem_avoid[MEM_AVOID_CMDLINE].size);
	}
439

440 441 442
	/* Avoid boot parameters. */
	mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
	mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
443 444 445 446 447
	add_identity_map(mem_avoid[MEM_AVOID_BOOTPARAMS].start,
			 mem_avoid[MEM_AVOID_BOOTPARAMS].size);

	/* We don't need to set a mapping for setup_data. */

448
	/* Mark the memmap regions we need to avoid */
449
	handle_mem_options();
450

451 452 453
	/* Enumerate the immovable memory regions */
	num_immovable_mem = count_immovable_mem_regions();

454 455 456 457
#ifdef CONFIG_X86_VERBOSE_BOOTUP
	/* Make sure video RAM can be used. */
	add_identity_map(0, PMD_SIZE);
#endif
458 459
}

460 461 462 463 464 465
/*
 * Does this memory vector overlap a known avoided area? If so, record the
 * overlap region with the lowest address.
 */
static bool mem_avoid_overlap(struct mem_vector *img,
			      struct mem_vector *overlap)
466 467
{
	int i;
468
	struct setup_data *ptr;
469 470
	unsigned long earliest = img->start + img->size;
	bool is_overlapping = false;
471 472

	for (i = 0; i < MEM_AVOID_MAX; i++) {
473 474 475
		if (mem_overlaps(img, &mem_avoid[i]) &&
		    mem_avoid[i].start < earliest) {
			*overlap = mem_avoid[i];
476
			earliest = overlap->start;
477 478
			is_overlapping = true;
		}
479 480
	}

481
	/* Avoid all entries in the setup_data linked list. */
482
	ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
483 484 485
	while (ptr) {
		struct mem_vector avoid;

486
		avoid.start = (unsigned long)ptr;
487 488
		avoid.size = sizeof(*ptr) + ptr->len;

489 490
		if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
			*overlap = avoid;
491
			earliest = overlap->start;
492 493
			is_overlapping = true;
		}
494

495 496 497 498 499 500 501 502 503 504 505 506
		if (ptr->type == SETUP_INDIRECT &&
		    ((struct setup_indirect *)ptr->data)->type != SETUP_INDIRECT) {
			avoid.start = ((struct setup_indirect *)ptr->data)->addr;
			avoid.size = ((struct setup_indirect *)ptr->data)->len;

			if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
				*overlap = avoid;
				earliest = overlap->start;
				is_overlapping = true;
			}
		}

507 508 509
		ptr = (struct setup_data *)(unsigned long)ptr->next;
	}

510
	return is_overlapping;
511 512
}

513 514 515 516 517 518 519 520 521
struct slot_area {
	unsigned long addr;
	int num;
};

#define MAX_SLOT_AREA 100

static struct slot_area slot_areas[MAX_SLOT_AREA];

522
static unsigned long slot_max;
523

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
static unsigned long slot_area_index;

static void store_slot_info(struct mem_vector *region, unsigned long image_size)
{
	struct slot_area slot_area;

	if (slot_area_index == MAX_SLOT_AREA)
		return;

	slot_area.addr = region->start;
	slot_area.num = (region->size - image_size) /
			CONFIG_PHYSICAL_ALIGN + 1;

	if (slot_area.num > 0) {
		slot_areas[slot_area_index++] = slot_area;
		slot_max += slot_area.num;
	}
}

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
/*
 * Skip as many 1GB huge pages as possible in the passed region
 * according to the number which users specified:
 */
static void
process_gb_huge_pages(struct mem_vector *region, unsigned long image_size)
{
	unsigned long addr, size = 0;
	struct mem_vector tmp;
	int i = 0;

	if (!max_gb_huge_pages) {
		store_slot_info(region, image_size);
		return;
	}

	addr = ALIGN(region->start, PUD_SIZE);
	/* Did we raise the address above the passed in memory entry? */
	if (addr < region->start + region->size)
		size = region->size - (addr - region->start);

	/* Check how many 1GB huge pages can be filtered out: */
	while (size > PUD_SIZE && max_gb_huge_pages) {
		size -= PUD_SIZE;
		max_gb_huge_pages--;
		i++;
	}

	/* No good 1GB huge pages found: */
	if (!i) {
		store_slot_info(region, image_size);
		return;
	}

	/*
	 * Skip those 'i'*1GB good huge pages, and continue checking and
	 * processing the remaining head or tail part of the passed region
	 * if available.
	 */

	if (addr >= region->start + image_size) {
		tmp.start = region->start;
		tmp.size = addr - region->start;
		store_slot_info(&tmp, image_size);
	}

	size  = region->size - (addr - region->start) - i * PUD_SIZE;
	if (size >= image_size) {
		tmp.start = addr + i * PUD_SIZE;
		tmp.size = size;
		store_slot_info(&tmp, image_size);
	}
}

597 598
static unsigned long slots_fetch_random(void)
{
599 600 601
	unsigned long slot;
	int i;

602 603 604 605
	/* Handle case of no slots stored. */
	if (slot_max == 0)
		return 0;

606
	slot = kaslr_get_random_long("Physical") % slot_max;
607 608 609 610 611 612 613 614 615 616 617 618

	for (i = 0; i < slot_area_index; i++) {
		if (slot >= slot_areas[i].num) {
			slot -= slot_areas[i].num;
			continue;
		}
		return slot_areas[i].addr + slot * CONFIG_PHYSICAL_ALIGN;
	}

	if (i == slot_area_index)
		debug_putstr("slots_fetch_random() failed!?\n");
	return 0;
619 620
}

621 622 623
static void __process_mem_region(struct mem_vector *entry,
				 unsigned long minimum,
				 unsigned long image_size)
624
{
625
	struct mem_vector region, overlap;
626
	unsigned long region_end;
627

628 629 630
	/* Enforce minimum and memory limit. */
	region.start = max_t(unsigned long long, entry->start, minimum);
	region_end = min(entry->start + entry->size, mem_limit);
631

632 633 634 635
	/* Give up if slot area array is full. */
	while (slot_area_index < MAX_SLOT_AREA) {
		/* Potentially raise address to meet alignment needs. */
		region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
636

637
		/* Did we raise the address above the passed in memory entry? */
638
		if (region.start > region_end)
639
			return;
640

641
		/* Reduce size by any delta from the original address. */
642
		region.size = region_end - region.start;
643

644 645 646 647 648 649
		/* Return if region can't contain decompressed kernel */
		if (region.size < image_size)
			return;

		/* If nothing overlaps, store the region and return. */
		if (!mem_avoid_overlap(&region, &overlap)) {
650
			process_gb_huge_pages(&region, image_size);
651 652 653 654
			return;
		}

		/* Store beginning of region if holds at least image_size. */
655
		if (overlap.start >= region.start + image_size) {
656 657
			region.size = overlap.start - region.start;
			process_gb_huge_pages(&region, image_size);
658 659 660 661
		}

		/* Clip off the overlapping region and start over. */
		region.start = overlap.start + overlap.size;
662 663 664
	}
}

665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
static bool process_mem_region(struct mem_vector *region,
			       unsigned long long minimum,
			       unsigned long long image_size)
{
	int i;
	/*
	 * If no immovable memory found, or MEMORY_HOTREMOVE disabled,
	 * use @region directly.
	 */
	if (!num_immovable_mem) {
		__process_mem_region(region, minimum, image_size);

		if (slot_area_index == MAX_SLOT_AREA) {
			debug_putstr("Aborted e820/efi memmap scan (slot_areas full)!\n");
			return 1;
		}
		return 0;
	}

684
#if defined(CONFIG_MEMORY_HOTREMOVE) && defined(CONFIG_ACPI)
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
	/*
	 * If immovable memory found, filter the intersection between
	 * immovable memory and @region.
	 */
	for (i = 0; i < num_immovable_mem; i++) {
		unsigned long long start, end, entry_end, region_end;
		struct mem_vector entry;

		if (!mem_overlaps(region, &immovable_mem[i]))
			continue;

		start = immovable_mem[i].start;
		end = start + immovable_mem[i].size;
		region_end = region->start + region->size;

		entry.start = clamp(region->start, start, end);
		entry_end = clamp(region_end, start, end);
		entry.size = entry_end - entry.start;

		__process_mem_region(&entry, minimum, image_size);

		if (slot_area_index == MAX_SLOT_AREA) {
			debug_putstr("Aborted e820/efi memmap scan when walking immovable regions(slot_areas full)!\n");
			return 1;
		}
	}
#endif
712
	return 0;
713 714
}

715 716
#ifdef CONFIG_EFI
/*
717 718
 * Returns true if we processed the EFI memmap, which we prefer over the E820
 * table if it is available.
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
 */
static bool
process_efi_entries(unsigned long minimum, unsigned long image_size)
{
	struct efi_info *e = &boot_params->efi_info;
	bool efi_mirror_found = false;
	struct mem_vector region;
	efi_memory_desc_t *md;
	unsigned long pmap;
	char *signature;
	u32 nr_desc;
	int i;

	signature = (char *)&e->efi_loader_signature;
	if (strncmp(signature, EFI32_LOADER_SIGNATURE, 4) &&
	    strncmp(signature, EFI64_LOADER_SIGNATURE, 4))
		return false;

#ifdef CONFIG_X86_32
	/* Can't handle data above 4GB at this time */
	if (e->efi_memmap_hi) {
		warn("EFI memmap is above 4GB, can't be handled now on x86_32. EFI should be disabled.\n");
		return false;
	}
	pmap =  e->efi_memmap;
#else
	pmap = (e->efi_memmap | ((__u64)e->efi_memmap_hi << 32));
#endif

	nr_desc = e->efi_memmap_size / e->efi_memdesc_size;
	for (i = 0; i < nr_desc; i++) {
		md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);
		if (md->attribute & EFI_MEMORY_MORE_RELIABLE) {
			efi_mirror_found = true;
753
			break;
754 755 756
		}
	}

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
	for (i = 0; i < nr_desc; i++) {
		md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);

		/*
		 * Here we are more conservative in picking free memory than
		 * the EFI spec allows:
		 *
		 * According to the spec, EFI_BOOT_SERVICES_{CODE|DATA} are also
		 * free memory and thus available to place the kernel image into,
		 * but in practice there's firmware where using that memory leads
		 * to crashes.
		 *
		 * Only EFI_CONVENTIONAL_MEMORY is guaranteed to be free.
		 */
		if (md->type != EFI_CONVENTIONAL_MEMORY)
			continue;

774 775 776 777
		if (efi_soft_reserve_enabled() &&
		    (md->attribute & EFI_MEMORY_SP))
			continue;

778 779 780 781 782 783
		if (efi_mirror_found &&
		    !(md->attribute & EFI_MEMORY_MORE_RELIABLE))
			continue;

		region.start = md->phys_addr;
		region.size = md->num_pages << EFI_PAGE_SHIFT;
784
		if (process_mem_region(&region, minimum, image_size))
785 786 787
			break;
	}
	return true;
788 789 790 791 792 793 794 795 796
}
#else
static inline bool
process_efi_entries(unsigned long minimum, unsigned long image_size)
{
	return false;
}
#endif

797 798
static void process_e820_entries(unsigned long minimum,
				 unsigned long image_size)
799 800
{
	int i;
801
	struct mem_vector region;
802 803 804 805 806 807 808 809
	struct boot_e820_entry *entry;

	/* Verify potential e820 positions, appending to slots list. */
	for (i = 0; i < boot_params->e820_entries; i++) {
		entry = &boot_params->e820_table[i];
		/* Skip non-RAM entries. */
		if (entry->type != E820_TYPE_RAM)
			continue;
810 811
		region.start = entry->addr;
		region.size = entry->size;
812
		if (process_mem_region(&region, minimum, image_size))
813 814 815
			break;
	}
}
816

817 818 819
static unsigned long find_random_phys_addr(unsigned long minimum,
					   unsigned long image_size)
{
820 821 822 823
	/* Bail out early if it's impossible to succeed. */
	if (minimum + image_size > mem_limit)
		return 0;

824 825
	/* Check if we had too many memmaps. */
	if (memmap_too_large) {
826
		debug_putstr("Aborted memory entries scan (more than 4 memmap= args)!\n");
827 828 829
		return 0;
	}

830 831 832
	if (process_efi_entries(minimum, image_size))
		return slots_fetch_random();

833
	process_e820_entries(minimum, image_size);
834 835 836
	return slots_fetch_random();
}

837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
static unsigned long find_random_virt_addr(unsigned long minimum,
					   unsigned long image_size)
{
	unsigned long slots, random_addr;

	/* Align image_size for easy slot calculations. */
	image_size = ALIGN(image_size, CONFIG_PHYSICAL_ALIGN);

	/*
	 * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
	 * that can hold image_size within the range of minimum to
	 * KERNEL_IMAGE_SIZE?
	 */
	slots = (KERNEL_IMAGE_SIZE - minimum - image_size) /
		 CONFIG_PHYSICAL_ALIGN + 1;

853
	random_addr = kaslr_get_random_long("Virtual") % slots;
854 855 856 857

	return random_addr * CONFIG_PHYSICAL_ALIGN + minimum;
}

858 859 860 861
/*
 * Since this function examines addresses much more numerically,
 * it takes the input and output pointers as 'unsigned long'.
 */
862 863 864 865 866
void choose_random_location(unsigned long input,
			    unsigned long input_size,
			    unsigned long *output,
			    unsigned long output_size,
			    unsigned long *virt_addr)
867
{
868
	unsigned long random_addr, min_addr;
869 870

	if (cmdline_find_option_bool("nokaslr")) {
871
		warn("KASLR disabled: 'nokaslr' on cmdline.");
872
		return;
873 874
	}

875 876
#ifdef CONFIG_X86_5LEVEL
	if (__read_cr4() & X86_CR4_LA57) {
877
		__pgtable_l5_enabled = 1;
878 879
		pgdir_shift = 48;
		ptrs_per_p4d = 512;
880 881 882
	}
#endif

883
	boot_params->hdr.loadflags |= KASLR_FLAG;
884

885 886 887
	/* Prepare to add new identity pagetables on demand. */
	initialize_identity_maps();

888 889 890 891 892
	if (IS_ENABLED(CONFIG_X86_32))
		mem_limit = KERNEL_IMAGE_SIZE;
	else
		mem_limit = MAXMEM;

893
	/* Record the various known unsafe memory ranges. */
894
	mem_avoid_init(input, input_size, *output);
895

896 897 898 899 900 901
	/*
	 * Low end of the randomization range should be the
	 * smaller of 512M or the initial kernel image
	 * location:
	 */
	min_addr = min(*output, 512UL << 20);
902 903
	/* Make sure minimum is aligned. */
	min_addr = ALIGN(min_addr, CONFIG_PHYSICAL_ALIGN);
904

905
	/* Walk available memory entries to find a random address. */
906
	random_addr = find_random_phys_addr(min_addr, output_size);
907
	if (!random_addr) {
908
		warn("Physical KASLR disabled: no suitable memory region!");
909 910 911 912 913 914
	} else {
		/* Update the new physical address location. */
		if (*output != random_addr) {
			add_identity_map(random_addr, output_size);
			*output = random_addr;
		}
915 916 917 918 919 920 921 922 923

		/*
		 * This loads the identity mapping page table.
		 * This should only be done if a new physical address
		 * is found for the kernel, otherwise we should keep
		 * the old page table to make it be like the "nokaslr"
		 * case.
		 */
		finalize_identity_maps();
924 925
	}

926 927 928 929 930

	/* Pick random virtual address starting from LOAD_PHYSICAL_ADDR. */
	if (IS_ENABLED(CONFIG_X86_64))
		random_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, output_size);
	*virt_addr = random_addr;
931
}