cleanup.c 27.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * MTRR (Memory Type Range Register) cleanup
 *
 *  Copyright (C) 2009 Yinghai Lu
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
20 21 22 23 24 25
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/smp.h>
#include <linux/cpu.h>
#include <linux/sort.h>
26 27 28
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/kvm_para.h>
29

30
#include <asm/processor.h>
31 32 33
#include <asm/e820.h>
#include <asm/mtrr.h>
#include <asm/msr.h>
34

35 36 37
#include "mtrr.h"

struct res_range {
38 39
	unsigned long	start;
	unsigned long	end;
40 41
};

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
struct var_mtrr_range_state {
	unsigned long	base_pfn;
	unsigned long	size_pfn;
	mtrr_type	type;
};

struct var_mtrr_state {
	unsigned long	range_startk;
	unsigned long	range_sizek;
	unsigned long	chunk_sizek;
	unsigned long	gran_sizek;
	unsigned int	reg;
};

/* Should be related to MTRR_VAR_RANGES nums */
#define RANGE_NUM				256

static struct res_range __initdata		range[RANGE_NUM];
static int __initdata				nr_range;

static struct var_mtrr_range_state __initdata	range_state[RANGE_NUM];

static int __initdata debug_print;
#define Dprintk(x...) do { if (debug_print) printk(KERN_DEBUG x); } while (0)


68
static int __init
69 70
add_range(struct res_range *range, int nr_range,
	  unsigned long start, unsigned long end)
71
{
72
	/* Out of slots: */
73 74 75 76 77 78 79 80 81 82 83 84
	if (nr_range >= RANGE_NUM)
		return nr_range;

	range[nr_range].start = start;
	range[nr_range].end = end;

	nr_range++;

	return nr_range;
}

static int __init
85 86
add_range_with_merge(struct res_range *range, int nr_range,
		     unsigned long start, unsigned long end)
87 88 89
{
	int i;

90
	/* Try to merge it with old one: */
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
	for (i = 0; i < nr_range; i++) {
		unsigned long final_start, final_end;
		unsigned long common_start, common_end;

		if (!range[i].end)
			continue;

		common_start = max(range[i].start, start);
		common_end = min(range[i].end, end);
		if (common_start > common_end + 1)
			continue;

		final_start = min(range[i].start, start);
		final_end = max(range[i].end, end);

		range[i].start = final_start;
		range[i].end =  final_end;
		return nr_range;
	}

111
	/* Need to add it: */
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
	return add_range(range, nr_range, start, end);
}

static void __init
subtract_range(struct res_range *range, unsigned long start, unsigned long end)
{
	int i, j;

	for (j = 0; j < RANGE_NUM; j++) {
		if (!range[j].end)
			continue;

		if (start <= range[j].start && end >= range[j].end) {
			range[j].start = 0;
			range[j].end = 0;
			continue;
		}

		if (start <= range[j].start && end < range[j].end &&
		    range[j].start < end + 1) {
			range[j].start = end + 1;
			continue;
		}


		if (start > range[j].start && end >= range[j].end &&
		    range[j].end > start - 1) {
			range[j].end = start - 1;
			continue;
		}

		if (start > range[j].start && end < range[j].end) {
144
			/* Find the new spare: */
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
			for (i = 0; i < RANGE_NUM; i++) {
				if (range[i].end == 0)
					break;
			}
			if (i < RANGE_NUM) {
				range[i].end = range[j].end;
				range[i].start = end + 1;
			} else {
				printk(KERN_ERR "run of slot in ranges\n");
			}
			range[j].end = start - 1;
			continue;
		}
	}
}

static int __init cmp_range(const void *x1, const void *x2)
{
	const struct res_range *r1 = x1;
	const struct res_range *r2 = x2;
	long start1, start2;

	start1 = r1->start;
	start2 = r2->start;

	return start1 - start2;
}

173 174
#define BIOS_BUG_MSG KERN_WARNING \
	"WARNING: BIOS bug: VAR MTRR %d contains strange UC entry under 1M, check with your system vendor!\n"
175 176 177 178 179 180

static int __init
x86_get_mtrr_mem_range(struct res_range *range, int nr_range,
		       unsigned long extra_remove_base,
		       unsigned long extra_remove_size)
{
181
	unsigned long base, size;
182
	mtrr_type type;
183
	int i;
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

	for (i = 0; i < num_var_ranges; i++) {
		type = range_state[i].type;
		if (type != MTRR_TYPE_WRBACK)
			continue;
		base = range_state[i].base_pfn;
		size = range_state[i].size_pfn;
		nr_range = add_range_with_merge(range, nr_range, base,
						base + size - 1);
	}
	if (debug_print) {
		printk(KERN_DEBUG "After WB checking\n");
		for (i = 0; i < nr_range; i++)
			printk(KERN_DEBUG "MTRR MAP PFN: %016lx - %016lx\n",
				 range[i].start, range[i].end + 1);
	}

201
	/* Take out UC ranges: */
202 203 204 205 206 207 208 209 210
	for (i = 0; i < num_var_ranges; i++) {
		type = range_state[i].type;
		if (type != MTRR_TYPE_UNCACHABLE &&
		    type != MTRR_TYPE_WRPROT)
			continue;
		size = range_state[i].size_pfn;
		if (!size)
			continue;
		base = range_state[i].base_pfn;
211 212 213
		if (base < (1<<(20-PAGE_SHIFT)) && mtrr_state.have_fixed &&
		    (mtrr_state.enabled & 1)) {
			/* Var MTRR contains UC entry below 1M? Skip it: */
214
			printk(BIOS_BUG_MSG, i);
215 216 217 218 219
			if (base + size <= (1<<(20-PAGE_SHIFT)))
				continue;
			size -= (1<<(20-PAGE_SHIFT)) - base;
			base = 1<<(20-PAGE_SHIFT);
		}
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
		subtract_range(range, base, base + size - 1);
	}
	if (extra_remove_size)
		subtract_range(range, extra_remove_base,
				 extra_remove_base + extra_remove_size  - 1);

	/* get new range num */
	nr_range = 0;
	for (i = 0; i < RANGE_NUM; i++) {
		if (!range[i].end)
			continue;
		nr_range++;
	}
	if  (debug_print) {
		printk(KERN_DEBUG "After UC checking\n");
		for (i = 0; i < nr_range; i++)
			printk(KERN_DEBUG "MTRR MAP PFN: %016lx - %016lx\n",
				 range[i].start, range[i].end + 1);
	}

	/* sort the ranges */
	sort(range, nr_range, sizeof(struct res_range), cmp_range, NULL);
	if  (debug_print) {
		printk(KERN_DEBUG "After sorting\n");
		for (i = 0; i < nr_range; i++)
			printk(KERN_DEBUG "MTRR MAP PFN: %016lx - %016lx\n",
				 range[i].start, range[i].end + 1);
	}

	/* clear those is not used */
	for (i = nr_range; i < RANGE_NUM; i++)
		memset(&range[i], 0, sizeof(range[i]));

	return nr_range;
}

#ifdef CONFIG_MTRR_SANITIZER

static unsigned long __init sum_ranges(struct res_range *range, int nr_range)
{
260
	unsigned long sum = 0;
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
	int i;

	for (i = 0; i < nr_range; i++)
		sum += range[i].end + 1 - range[i].start;

	return sum;
}

static int enable_mtrr_cleanup __initdata =
	CONFIG_MTRR_SANITIZER_ENABLE_DEFAULT;

static int __init disable_mtrr_cleanup_setup(char *str)
{
	enable_mtrr_cleanup = 0;
	return 0;
}
early_param("disable_mtrr_cleanup", disable_mtrr_cleanup_setup);

static int __init enable_mtrr_cleanup_setup(char *str)
{
	enable_mtrr_cleanup = 1;
	return 0;
}
early_param("enable_mtrr_cleanup", enable_mtrr_cleanup_setup);

static int __init mtrr_cleanup_debug_setup(char *str)
{
	debug_print = 1;
	return 0;
}
early_param("mtrr_cleanup_debug", mtrr_cleanup_debug_setup);

static void __init
set_var_mtrr(unsigned int reg, unsigned long basek, unsigned long sizek,
295
	     unsigned char type, unsigned int address_bits)
296 297 298 299 300 301 302 303 304 305 306 307
{
	u32 base_lo, base_hi, mask_lo, mask_hi;
	u64 base, mask;

	if (!sizek) {
		fill_mtrr_var_range(reg, 0, 0, 0, 0);
		return;
	}

	mask = (1ULL << address_bits) - 1;
	mask &= ~((((u64)sizek) << 10) - 1);

308
	base = ((u64)basek) << 10;
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

	base |= type;
	mask |= 0x800;

	base_lo = base & ((1ULL<<32) - 1);
	base_hi = base >> 32;

	mask_lo = mask & ((1ULL<<32) - 1);
	mask_hi = mask >> 32;

	fill_mtrr_var_range(reg, base_lo, base_hi, mask_lo, mask_hi);
}

static void __init
save_var_mtrr(unsigned int reg, unsigned long basek, unsigned long sizek,
324
	      unsigned char type)
325 326 327 328 329 330
{
	range_state[reg].base_pfn = basek >> (PAGE_SHIFT - 10);
	range_state[reg].size_pfn = sizek >> (PAGE_SHIFT - 10);
	range_state[reg].type = type;
}

331
static void __init set_var_mtrr_all(unsigned int address_bits)
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
{
	unsigned long basek, sizek;
	unsigned char type;
	unsigned int reg;

	for (reg = 0; reg < num_var_ranges; reg++) {
		basek = range_state[reg].base_pfn << (PAGE_SHIFT - 10);
		sizek = range_state[reg].size_pfn << (PAGE_SHIFT - 10);
		type = range_state[reg].type;

		set_var_mtrr(reg, basek, sizek, type, address_bits);
	}
}

static unsigned long to_size_factor(unsigned long sizek, char *factorp)
{
	unsigned long base = sizek;
349
	char factor;
350 351

	if (base & ((1<<10) - 1)) {
352
		/* Not MB-aligned: */
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
		factor = 'K';
	} else if (base & ((1<<20) - 1)) {
		factor = 'M';
		base >>= 10;
	} else {
		factor = 'G';
		base >>= 20;
	}

	*factorp = factor;

	return base;
}

static unsigned int __init
range_to_mtrr(unsigned int reg, unsigned long range_startk,
	      unsigned long range_sizek, unsigned char type)
{
	if (!range_sizek || (reg >= num_var_ranges))
		return reg;

	while (range_sizek) {
		unsigned long max_align, align;
		unsigned long sizek;

378
		/* Compute the maximum size with which we can make a range: */
379 380 381 382
		if (range_startk)
			max_align = ffs(range_startk) - 1;
		else
			max_align = 32;
383

384 385 386 387 388 389 390 391 392
		align = fls(range_sizek) - 1;
		if (align > max_align)
			align = max_align;

		sizek = 1 << align;
		if (debug_print) {
			char start_factor = 'K', size_factor = 'K';
			unsigned long start_base, size_base;

393 394
			start_base = to_size_factor(range_startk, &start_factor);
			size_base = to_size_factor(sizek, &size_factor);
395

396
			Dprintk("Setting variable MTRR %d, "
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
				"base: %ld%cB, range: %ld%cB, type %s\n",
				reg, start_base, start_factor,
				size_base, size_factor,
				(type == MTRR_TYPE_UNCACHABLE) ? "UC" :
				   ((type == MTRR_TYPE_WRBACK) ? "WB" : "Other")
				);
		}
		save_var_mtrr(reg++, range_startk, sizek, type);
		range_startk += sizek;
		range_sizek -= sizek;
		if (reg >= num_var_ranges)
			break;
	}
	return reg;
}

static unsigned __init
range_to_mtrr_with_hole(struct var_mtrr_state *state, unsigned long basek,
			unsigned long sizek)
{
	unsigned long hole_basek, hole_sizek;
	unsigned long second_basek, second_sizek;
	unsigned long range0_basek, range0_sizek;
	unsigned long range_basek, range_sizek;
	unsigned long chunk_sizek;
	unsigned long gran_sizek;

	hole_basek = 0;
	hole_sizek = 0;
	second_basek = 0;
	second_sizek = 0;
	chunk_sizek = state->chunk_sizek;
	gran_sizek = state->gran_sizek;

431
	/* Align with gran size, prevent small block used up MTRRs: */
432 433 434
	range_basek = ALIGN(state->range_startk, gran_sizek);
	if ((range_basek > basek) && basek)
		return second_sizek;
435

436 437 438 439 440 441 442 443 444 445
	state->range_sizek -= (range_basek - state->range_startk);
	range_sizek = ALIGN(state->range_sizek, gran_sizek);

	while (range_sizek > state->range_sizek) {
		range_sizek -= gran_sizek;
		if (!range_sizek)
			return 0;
	}
	state->range_sizek = range_sizek;

446
	/* Try to append some small hole: */
447 448 449
	range0_basek = state->range_startk;
	range0_sizek = ALIGN(state->range_sizek, chunk_sizek);

450
	/* No increase: */
451
	if (range0_sizek == state->range_sizek) {
452 453 454
		Dprintk("rangeX: %016lx - %016lx\n",
			range0_basek<<10,
			(range0_basek + state->range_sizek)<<10);
455 456 457 458 459
		state->reg = range_to_mtrr(state->reg, range0_basek,
				state->range_sizek, MTRR_TYPE_WRBACK);
		return 0;
	}

460
	/* Only cut back when it is not the last: */
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
	if (sizek) {
		while (range0_basek + range0_sizek > (basek + sizek)) {
			if (range0_sizek >= chunk_sizek)
				range0_sizek -= chunk_sizek;
			else
				range0_sizek = 0;

			if (!range0_sizek)
				break;
		}
	}

second_try:
	range_basek = range0_basek + range0_sizek;

476
	/* One hole in the middle: */
477 478 479 480 481
	if (range_basek > basek && range_basek <= (basek + sizek))
		second_sizek = range_basek - basek;

	if (range0_sizek > state->range_sizek) {

482
		/* One hole in middle or at the end: */
483 484
		hole_sizek = range0_sizek - state->range_sizek - second_sizek;

485
		/* Hole size should be less than half of range0 size: */
486 487 488 489 490 491 492 493 494 495 496
		if (hole_sizek >= (range0_sizek >> 1) &&
		    range0_sizek >= chunk_sizek) {
			range0_sizek -= chunk_sizek;
			second_sizek = 0;
			hole_sizek = 0;

			goto second_try;
		}
	}

	if (range0_sizek) {
497 498 499
		Dprintk("range0: %016lx - %016lx\n",
			range0_basek<<10,
			(range0_basek + range0_sizek)<<10);
500 501 502 503 504
		state->reg = range_to_mtrr(state->reg, range0_basek,
				range0_sizek, MTRR_TYPE_WRBACK);
	}

	if (range0_sizek < state->range_sizek) {
505
		/* Need to handle left over range: */
506 507
		range_sizek = state->range_sizek - range0_sizek;

508 509 510 511
		Dprintk("range: %016lx - %016lx\n",
			 range_basek<<10,
			 (range_basek + range_sizek)<<10);

512 513 514 515 516 517
		state->reg = range_to_mtrr(state->reg, range_basek,
				 range_sizek, MTRR_TYPE_WRBACK);
	}

	if (hole_sizek) {
		hole_basek = range_basek - hole_sizek - second_sizek;
518 519 520
		Dprintk("hole: %016lx - %016lx\n",
			 hole_basek<<10,
			 (hole_basek + hole_sizek)<<10);
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
		state->reg = range_to_mtrr(state->reg, hole_basek,
				 hole_sizek, MTRR_TYPE_UNCACHABLE);
	}

	return second_sizek;
}

static void __init
set_var_mtrr_range(struct var_mtrr_state *state, unsigned long base_pfn,
		   unsigned long size_pfn)
{
	unsigned long basek, sizek;
	unsigned long second_sizek = 0;

	if (state->reg >= num_var_ranges)
		return;

	basek = base_pfn << (PAGE_SHIFT - 10);
	sizek = size_pfn << (PAGE_SHIFT - 10);

541
	/* See if I can merge with the last range: */
542 543 544 545 546 547
	if ((basek <= 1024) ||
	    (state->range_startk + state->range_sizek == basek)) {
		unsigned long endk = basek + sizek;
		state->range_sizek = endk - state->range_startk;
		return;
	}
548
	/* Write the range mtrrs: */
549 550 551
	if (state->range_sizek != 0)
		second_sizek = range_to_mtrr_with_hole(state, basek, sizek);

552
	/* Allocate an msr: */
553 554 555 556
	state->range_startk = basek + second_sizek;
	state->range_sizek  = sizek - second_sizek;
}

557
/* Mininum size of mtrr block that can take hole: */
558 559 560 561 562 563 564 565 566 567 568
static u64 mtrr_chunk_size __initdata = (256ULL<<20);

static int __init parse_mtrr_chunk_size_opt(char *p)
{
	if (!p)
		return -EINVAL;
	mtrr_chunk_size = memparse(p, &p);
	return 0;
}
early_param("mtrr_chunk_size", parse_mtrr_chunk_size_opt);

569
/* Granularity of mtrr of block: */
570 571 572 573 574 575 576 577 578 579 580
static u64 mtrr_gran_size __initdata;

static int __init parse_mtrr_gran_size_opt(char *p)
{
	if (!p)
		return -EINVAL;
	mtrr_gran_size = memparse(p, &p);
	return 0;
}
early_param("mtrr_gran_size", parse_mtrr_gran_size_opt);

581
static unsigned long nr_mtrr_spare_reg __initdata =
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
				 CONFIG_MTRR_SANITIZER_SPARE_REG_NR_DEFAULT;

static int __init parse_mtrr_spare_reg(char *arg)
{
	if (arg)
		nr_mtrr_spare_reg = simple_strtoul(arg, NULL, 0);
	return 0;
}
early_param("mtrr_spare_reg_nr", parse_mtrr_spare_reg);

static int __init
x86_setup_var_mtrrs(struct res_range *range, int nr_range,
		    u64 chunk_size, u64 gran_size)
{
	struct var_mtrr_state var_state;
	int num_reg;
598
	int i;
599 600 601 602 603 604 605 606 607

	var_state.range_startk	= 0;
	var_state.range_sizek	= 0;
	var_state.reg		= 0;
	var_state.chunk_sizek	= chunk_size >> 10;
	var_state.gran_sizek	= gran_size >> 10;

	memset(range_state, 0, sizeof(range_state));

608 609
	/* Write the range: */
	for (i = 0; i < nr_range; i++) {
610 611
		set_var_mtrr_range(&var_state, range[i].start,
				   range[i].end - range[i].start + 1);
612
	}
613

614
	/* Write the last range: */
615 616 617 618
	if (var_state.range_sizek != 0)
		range_to_mtrr_with_hole(&var_state, 0, 0);

	num_reg = var_state.reg;
619
	/* Clear out the extra MTRR's: */
620 621 622 623 624 625 626 627 628
	while (var_state.reg < num_var_ranges) {
		save_var_mtrr(var_state.reg, 0, 0, 0);
		var_state.reg++;
	}

	return num_reg;
}

struct mtrr_cleanup_result {
629 630 631 632 633
	unsigned long	gran_sizek;
	unsigned long	chunk_sizek;
	unsigned long	lose_cover_sizek;
	unsigned int	num_reg;
	int		bad;
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
};

/*
 * gran_size: 64K, 128K, 256K, 512K, 1M, 2M, ..., 2G
 * chunk size: gran_size, ..., 2G
 * so we need (1+16)*8
 */
#define NUM_RESULT	136
#define PSHIFT		(PAGE_SHIFT - 10)

static struct mtrr_cleanup_result __initdata result[NUM_RESULT];
static unsigned long __initdata min_loss_pfn[RANGE_NUM];

static void __init print_out_mtrr_range_state(void)
{
	char start_factor = 'K', size_factor = 'K';
	unsigned long start_base, size_base;
	mtrr_type type;
652
	int i;
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679

	for (i = 0; i < num_var_ranges; i++) {

		size_base = range_state[i].size_pfn << (PAGE_SHIFT - 10);
		if (!size_base)
			continue;

		size_base = to_size_factor(size_base, &size_factor),
		start_base = range_state[i].base_pfn << (PAGE_SHIFT - 10);
		start_base = to_size_factor(start_base, &start_factor),
		type = range_state[i].type;

		printk(KERN_DEBUG "reg %d, base: %ld%cB, range: %ld%cB, type %s\n",
			i, start_base, start_factor,
			size_base, size_factor,
			(type == MTRR_TYPE_UNCACHABLE) ? "UC" :
			    ((type == MTRR_TYPE_WRPROT) ? "WP" :
			     ((type == MTRR_TYPE_WRBACK) ? "WB" : "Other"))
			);
	}
}

static int __init mtrr_need_cleanup(void)
{
	int i;
	mtrr_type type;
	unsigned long size;
680
	/* Extra one for all 0: */
681 682
	int num[MTRR_NUM_TYPES + 1];

683
	/* Check entries number: */
684 685 686 687 688 689 690 691 692 693 694
	memset(num, 0, sizeof(num));
	for (i = 0; i < num_var_ranges; i++) {
		type = range_state[i].type;
		size = range_state[i].size_pfn;
		if (type >= MTRR_NUM_TYPES)
			continue;
		if (!size)
			type = MTRR_NUM_TYPES;
		num[type]++;
	}

695
	/* Check if we got UC entries: */
696 697 698
	if (!num[MTRR_TYPE_UNCACHABLE])
		return 0;

699
	/* Check if we only had WB and UC */
700
	if (num[MTRR_TYPE_WRBACK] + num[MTRR_TYPE_UNCACHABLE] !=
701
	    num_var_ranges - num[MTRR_NUM_TYPES])
702 703 704 705 706 707
		return 0;

	return 1;
}

static unsigned long __initdata range_sums;
708 709 710 711 712

static void __init
mtrr_calc_range_state(u64 chunk_size, u64 gran_size,
		      unsigned long x_remove_base,
		      unsigned long x_remove_size, int i)
713 714 715
{
	static struct res_range range_new[RANGE_NUM];
	unsigned long range_sums_new;
716 717
	static int nr_range_new;
	int num_reg;
718

719 720
	/* Convert ranges to var ranges state: */
	num_reg = x86_setup_var_mtrrs(range, nr_range, chunk_size, gran_size);
721

722
	/* We got new setting in range_state, check it: */
723 724
	memset(range_new, 0, sizeof(range_new));
	nr_range_new = x86_get_mtrr_mem_range(range_new, 0,
725
				x_remove_base, x_remove_size);
726 727 728 729 730
	range_sums_new = sum_ranges(range_new, nr_range_new);

	result[i].chunk_sizek = chunk_size >> 10;
	result[i].gran_sizek = gran_size >> 10;
	result[i].num_reg = num_reg;
731

732
	if (range_sums < range_sums_new) {
733
		result[i].lose_cover_sizek = (range_sums_new - range_sums) << PSHIFT;
734
		result[i].bad = 1;
735 736 737
	} else {
		result[i].lose_cover_sizek = (range_sums - range_sums_new) << PSHIFT;
	}
738

739
	/* Double check it: */
740
	if (!result[i].bad && !result[i].lose_cover_sizek) {
741 742
		if (nr_range_new != nr_range || memcmp(range, range_new, sizeof(range)))
			result[i].bad = 1;
743 744
	}

745 746
	if (!result[i].bad && (range_sums - range_sums_new < min_loss_pfn[num_reg]))
		min_loss_pfn[num_reg] = range_sums - range_sums_new;
747 748 749 750 751
}

static void __init mtrr_print_out_one_result(int i)
{
	unsigned long gran_base, chunk_base, lose_base;
752
	char gran_factor, chunk_factor, lose_factor;
753 754 755 756

	gran_base = to_size_factor(result[i].gran_sizek, &gran_factor),
	chunk_base = to_size_factor(result[i].chunk_sizek, &chunk_factor),
	lose_base = to_size_factor(result[i].lose_cover_sizek, &lose_factor),
757 758 759 760 761 762 763

	pr_info("%sgran_size: %ld%c \tchunk_size: %ld%c \t",
		result[i].bad ? "*BAD*" : " ",
		gran_base, gran_factor, chunk_base, chunk_factor);
	pr_cont("num_reg: %d  \tlose cover RAM: %s%ld%c\n",
		result[i].num_reg, result[i].bad ? "-" : "",
		lose_base, lose_factor);
764 765 766 767 768 769
}

static int __init mtrr_search_optimal_index(void)
{
	int num_reg_good;
	int index_good;
770
	int i;
771 772 773

	if (nr_mtrr_spare_reg >= num_var_ranges)
		nr_mtrr_spare_reg = num_var_ranges - 1;
774

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
	num_reg_good = -1;
	for (i = num_var_ranges - nr_mtrr_spare_reg; i > 0; i--) {
		if (!min_loss_pfn[i])
			num_reg_good = i;
	}

	index_good = -1;
	if (num_reg_good != -1) {
		for (i = 0; i < NUM_RESULT; i++) {
			if (!result[i].bad &&
			    result[i].num_reg == num_reg_good &&
			    !result[i].lose_cover_sizek) {
				index_good = i;
				break;
			}
		}
	}

	return index_good;
}

int __init mtrr_cleanup(unsigned address_bits)
{
798
	unsigned long x_remove_base, x_remove_size;
799 800
	unsigned long base, size, def, dummy;
	u64 chunk_size, gran_size;
801
	mtrr_type type;
802 803 804 805 806
	int index_good;
	int i;

	if (!is_cpu(INTEL) || enable_mtrr_cleanup < 1)
		return 0;
807

808
	rdmsr(MSR_MTRRdefType, def, dummy);
809 810 811 812
	def &= 0xff;
	if (def != MTRR_TYPE_UNCACHABLE)
		return 0;

813
	/* Get it and store it aside: */
814 815 816 817 818 819 820 821
	memset(range_state, 0, sizeof(range_state));
	for (i = 0; i < num_var_ranges; i++) {
		mtrr_if->get(i, &base, &size, &type);
		range_state[i].base_pfn = base;
		range_state[i].size_pfn = size;
		range_state[i].type = type;
	}

822
	/* Check if we need handle it and can handle it: */
823 824 825
	if (!mtrr_need_cleanup())
		return 0;

826
	/* Print original var MTRRs at first, for debugging: */
827 828 829 830
	printk(KERN_DEBUG "original variable MTRRs\n");
	print_out_mtrr_range_state();

	memset(range, 0, sizeof(range));
831 832
	x_remove_size = 0;
	x_remove_base = 1 << (32 - PAGE_SHIFT);
833
	if (mtrr_tom2)
834 835 836
		x_remove_size = (mtrr_tom2 >> PAGE_SHIFT) - x_remove_base;

	nr_range = x86_get_mtrr_mem_range(range, 0, x_remove_base, x_remove_size);
837
	/*
838 839
	 * [0, 1M) should always be covered by var mtrr with WB
	 * and fixed mtrrs should take effect before var mtrr for it:
840 841 842
	 */
	nr_range = add_range_with_merge(range, nr_range, 0,
					(1ULL<<(20 - PAGE_SHIFT)) - 1);
843
	/* Sort the ranges: */
844 845 846 847 848 849 850 851 852
	sort(range, nr_range, sizeof(struct res_range), cmp_range, NULL);

	range_sums = sum_ranges(range, nr_range);
	printk(KERN_INFO "total RAM coverred: %ldM\n",
	       range_sums >> (20 - PAGE_SHIFT));

	if (mtrr_chunk_size && mtrr_gran_size) {
		i = 0;
		mtrr_calc_range_state(mtrr_chunk_size, mtrr_gran_size,
853
				      x_remove_base, x_remove_size, i);
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

		mtrr_print_out_one_result(i);

		if (!result[i].bad) {
			set_var_mtrr_all(address_bits);
			printk(KERN_DEBUG "New variable MTRRs\n");
			print_out_mtrr_range_state();
			return 1;
		}
		printk(KERN_INFO "invalid mtrr_gran_size or mtrr_chunk_size, "
		       "will find optimal one\n");
	}

	i = 0;
	memset(min_loss_pfn, 0xff, sizeof(min_loss_pfn));
	memset(result, 0, sizeof(result));
	for (gran_size = (1ULL<<16); gran_size < (1ULL<<32); gran_size <<= 1) {

		for (chunk_size = gran_size; chunk_size < (1ULL<<32);
		     chunk_size <<= 1) {

			if (i >= NUM_RESULT)
				continue;

			mtrr_calc_range_state(chunk_size, gran_size,
879
				      x_remove_base, x_remove_size, i);
880 881 882 883 884 885 886 887 888
			if (debug_print) {
				mtrr_print_out_one_result(i);
				printk(KERN_INFO "\n");
			}

			i++;
		}
	}

889
	/* Try to find the optimal index: */
890 891 892 893 894 895 896
	index_good = mtrr_search_optimal_index();

	if (index_good != -1) {
		printk(KERN_INFO "Found optimal setting for mtrr clean up\n");
		i = index_good;
		mtrr_print_out_one_result(i);

897
		/* Convert ranges to var ranges state: */
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
		chunk_size = result[i].chunk_sizek;
		chunk_size <<= 10;
		gran_size = result[i].gran_sizek;
		gran_size <<= 10;
		x86_setup_var_mtrrs(range, nr_range, chunk_size, gran_size);
		set_var_mtrr_all(address_bits);
		printk(KERN_DEBUG "New variable MTRRs\n");
		print_out_mtrr_range_state();
		return 1;
	} else {
		/* print out all */
		for (i = 0; i < NUM_RESULT; i++)
			mtrr_print_out_one_result(i);
	}

	printk(KERN_INFO "mtrr_cleanup: can not find optimal value\n");
	printk(KERN_INFO "please specify mtrr_gran_size/mtrr_chunk_size\n");

	return 0;
}
#else
int __init mtrr_cleanup(unsigned address_bits)
{
	return 0;
}
#endif

static int disable_mtrr_trim;

static int __init disable_mtrr_trim_setup(char *str)
{
	disable_mtrr_trim = 1;
	return 0;
}
early_param("disable_mtrr_trim", disable_mtrr_trim_setup);

/*
 * Newer AMD K8s and later CPUs have a special magic MSR way to force WB
 * for memory >4GB. Check for that here.
 * Note this won't check if the MTRRs < 4GB where the magic bit doesn't
 * apply to are wrong, but so far we don't know of any such case in the wild.
 */
940 941
#define Tom2Enabled		(1U << 21)
#define Tom2ForceMemTypeWB	(1U << 22)
942 943 944 945 946 947 948 949 950

int __init amd_special_default_mtrr(void)
{
	u32 l, h;

	if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD)
		return 0;
	if (boot_cpu_data.x86 < 0xf || boot_cpu_data.x86 > 0x11)
		return 0;
951
	/* In case some hypervisor doesn't pass SYSCFG through: */
952 953 954 955 956 957 958 959 960 961 962 963
	if (rdmsr_safe(MSR_K8_SYSCFG, &l, &h) < 0)
		return 0;
	/*
	 * Memory between 4GB and top of mem is forced WB by this magic bit.
	 * Reserved before K8RevF, but should be zero there.
	 */
	if ((l & (Tom2Enabled | Tom2ForceMemTypeWB)) ==
		 (Tom2Enabled | Tom2ForceMemTypeWB))
		return 1;
	return 0;
}

964 965
static u64 __init
real_trim_memory(unsigned long start_pfn, unsigned long limit_pfn)
966 967
{
	u64 trim_start, trim_size;
968

969 970
	trim_start = start_pfn;
	trim_start <<= PAGE_SHIFT;
971

972 973 974 975
	trim_size = limit_pfn;
	trim_size <<= PAGE_SHIFT;
	trim_size -= trim_start;

976
	return e820_update_range(trim_start, trim_size, E820_RAM, E820_RESERVED);
977
}
978

979 980 981 982 983 984 985
/**
 * mtrr_trim_uncached_memory - trim RAM not covered by MTRRs
 * @end_pfn: ending page frame number
 *
 * Some buggy BIOSes don't setup the MTRRs properly for systems with certain
 * memory configurations.  This routine checks that the highest MTRR matches
 * the end of memory, to make sure the MTRRs having a write back type cover
986
 * all of the memory the kernel is intending to use.  If not, it'll trim any
987 988 989 990 991 992 993 994 995 996
 * memory off the end by adjusting end_pfn, removing it from the kernel's
 * allocation pools, warning the user with an obnoxious message.
 */
int __init mtrr_trim_uncached_memory(unsigned long end_pfn)
{
	unsigned long i, base, size, highest_pfn = 0, def, dummy;
	mtrr_type type;
	u64 total_trim_size;
	/* extra one for all 0 */
	int num[MTRR_NUM_TYPES + 1];
997

998 999 1000 1001 1002 1003
	/*
	 * Make sure we only trim uncachable memory on machines that
	 * support the Intel MTRR architecture:
	 */
	if (!is_cpu(INTEL) || disable_mtrr_trim)
		return 0;
1004

1005
	rdmsr(MSR_MTRRdefType, def, dummy);
1006 1007 1008 1009
	def &= 0xff;
	if (def != MTRR_TYPE_UNCACHABLE)
		return 0;

1010
	/* Get it and store it aside: */
1011 1012 1013 1014 1015 1016 1017 1018
	memset(range_state, 0, sizeof(range_state));
	for (i = 0; i < num_var_ranges; i++) {
		mtrr_if->get(i, &base, &size, &type);
		range_state[i].base_pfn = base;
		range_state[i].size_pfn = size;
		range_state[i].type = type;
	}

1019
	/* Find highest cached pfn: */
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
	for (i = 0; i < num_var_ranges; i++) {
		type = range_state[i].type;
		if (type != MTRR_TYPE_WRBACK)
			continue;
		base = range_state[i].base_pfn;
		size = range_state[i].size_pfn;
		if (highest_pfn < base + size)
			highest_pfn = base + size;
	}

1030
	/* kvm/qemu doesn't have mtrr set right, don't trim them all: */
1031 1032 1033 1034 1035
	if (!highest_pfn) {
		printk(KERN_INFO "CPU MTRRs all blank - virtualized system.\n");
		return 0;
	}

1036
	/* Check entries number: */
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
	memset(num, 0, sizeof(num));
	for (i = 0; i < num_var_ranges; i++) {
		type = range_state[i].type;
		if (type >= MTRR_NUM_TYPES)
			continue;
		size = range_state[i].size_pfn;
		if (!size)
			type = MTRR_NUM_TYPES;
		num[type]++;
	}

1048
	/* No entry for WB? */
1049 1050 1051
	if (!num[MTRR_TYPE_WRBACK])
		return 0;

1052
	/* Check if we only had WB and UC: */
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
	if (num[MTRR_TYPE_WRBACK] + num[MTRR_TYPE_UNCACHABLE] !=
		num_var_ranges - num[MTRR_NUM_TYPES])
		return 0;

	memset(range, 0, sizeof(range));
	nr_range = 0;
	if (mtrr_tom2) {
		range[nr_range].start = (1ULL<<(32 - PAGE_SHIFT));
		range[nr_range].end = (mtrr_tom2 >> PAGE_SHIFT) - 1;
		if (highest_pfn < range[nr_range].end + 1)
			highest_pfn = range[nr_range].end + 1;
		nr_range++;
	}
	nr_range = x86_get_mtrr_mem_range(range, nr_range, 0, 0);

1068
	/* Check the head: */
1069 1070 1071
	total_trim_size = 0;
	if (range[0].start)
		total_trim_size += real_trim_memory(0, range[0].start);
1072 1073

	/* Check the holes: */
1074 1075 1076 1077 1078
	for (i = 0; i < nr_range - 1; i++) {
		if (range[i].end + 1 < range[i+1].start)
			total_trim_size += real_trim_memory(range[i].end + 1,
							    range[i+1].start);
	}
1079 1080

	/* Check the top: */
1081 1082 1083 1084 1085 1086
	i = nr_range - 1;
	if (range[i].end + 1 < end_pfn)
		total_trim_size += real_trim_memory(range[i].end + 1,
							 end_pfn);

	if (total_trim_size) {
1087
		pr_warning("WARNING: BIOS bug: CPU MTRRs don't cover all of memory, losing %lluMB of RAM.\n", total_trim_size >> 20);
1088 1089 1090 1091

		if (!changed_by_mtrr_cleanup)
			WARN_ON(1);

1092
		pr_info("update e820 for mtrr\n");
1093 1094 1095 1096 1097 1098 1099
		update_e820();

		return 1;
	}

	return 0;
}