main.c 45.9 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/*  Generic MTRR (Memory Type Range Register) driver.

    Copyright (C) 1997-2000  Richard Gooch
    Copyright (c) 2002	     Patrick Mochel

    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.

    Richard Gooch may be reached by email at  rgooch@atnf.csiro.au
    The postal address is:
      Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia.

    Source: "Pentium Pro Family Developer's Manual, Volume 3:
    Operating System Writer's Guide" (Intel document number 242692),
    section 11.11.7

    This was cleaned and made readable by Patrick Mochel <mochel@osdl.org> 
    on 6-7 March 2002. 
    Source: Intel Architecture Software Developers Manual, Volume 3: 
    System Programming Guide; Section 9.11. (1997 edition - PPro).
*/

#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/smp.h>
#include <linux/cpu.h>
39
#include <linux/mutex.h>
40
#include <linux/sort.h>
L
Linus Torvalds 已提交
41

42
#include <asm/e820.h>
L
Linus Torvalds 已提交
43 44 45 46
#include <asm/mtrr.h>
#include <asm/uaccess.h>
#include <asm/processor.h>
#include <asm/msr.h>
47
#include <asm/kvm_para.h>
L
Linus Torvalds 已提交
48 49 50 51
#include "mtrr.h"

u32 num_var_ranges = 0;

52
unsigned int mtrr_usage_table[MTRR_MAX_VAR_RANGES];
53
static DEFINE_MUTEX(mtrr_mutex);
L
Linus Torvalds 已提交
54

55
u64 size_or_mask, size_and_mask;
L
Linus Torvalds 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

static struct mtrr_ops * mtrr_ops[X86_VENDOR_NUM] = {};

struct mtrr_ops * mtrr_if = NULL;

static void set_mtrr(unsigned int reg, unsigned long base,
		     unsigned long size, mtrr_type type);

void set_mtrr_ops(struct mtrr_ops * ops)
{
	if (ops->vendor && ops->vendor < X86_VENDOR_NUM)
		mtrr_ops[ops->vendor] = ops;
}

/*  Returns non-zero if we have the write-combining memory type  */
static int have_wrcomb(void)
{
	struct pci_dev *dev;
74
	u8 rev;
L
Linus Torvalds 已提交
75 76
	
	if ((dev = pci_get_class(PCI_CLASS_BRIDGE_HOST << 8, NULL)) != NULL) {
77
		/* ServerWorks LE chipsets < rev 6 have problems with write-combining
L
Linus Torvalds 已提交
78 79 80
		   Don't allow it and leave room for other chipsets to be tagged */
		if (dev->vendor == PCI_VENDOR_ID_SERVERWORKS &&
		    dev->device == PCI_DEVICE_ID_SERVERWORKS_LE) {
81 82 83 84 85 86
			pci_read_config_byte(dev, PCI_CLASS_REVISION, &rev);
			if (rev <= 5) {
				printk(KERN_INFO "mtrr: Serverworks LE rev < 6 detected. Write-combining disabled.\n");
				pci_dev_put(dev);
				return 0;
			}
L
Linus Torvalds 已提交
87
		}
88
		/* Intel 450NX errata # 23. Non ascending cacheline evictions to
L
Linus Torvalds 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
		   write combining memory may resulting in data corruption */
		if (dev->vendor == PCI_VENDOR_ID_INTEL &&
		    dev->device == PCI_DEVICE_ID_INTEL_82451NX) {
			printk(KERN_INFO "mtrr: Intel 450NX MMC detected. Write-combining disabled.\n");
			pci_dev_put(dev);
			return 0;
		}
		pci_dev_put(dev);
	}		
	return (mtrr_if->have_wrcomb ? mtrr_if->have_wrcomb() : 0);
}

/*  This function returns the number of variable MTRRs  */
static void __init set_num_var_ranges(void)
{
	unsigned long config = 0, dummy;

	if (use_intel()) {
		rdmsr(MTRRcap_MSR, config, dummy);
	} else if (is_cpu(AMD))
		config = 2;
	else if (is_cpu(CYRIX) || is_cpu(CENTAUR))
		config = 8;
	num_var_ranges = config & 0xff;
}

static void __init init_table(void)
{
	int i, max;

	max = num_var_ranges;
	for (i = 0; i < max; i++)
121
		mtrr_usage_table[i] = 1;
L
Linus Torvalds 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
}

struct set_mtrr_data {
	atomic_t	count;
	atomic_t	gate;
	unsigned long	smp_base;
	unsigned long	smp_size;
	unsigned int	smp_reg;
	mtrr_type	smp_type;
};

static void ipi_handler(void *info)
/*  [SUMMARY] Synchronisation handler. Executed by "other" CPUs.
    [RETURNS] Nothing.
*/
{
138
#ifdef CONFIG_SMP
L
Linus Torvalds 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
	struct set_mtrr_data *data = info;
	unsigned long flags;

	local_irq_save(flags);

	atomic_dec(&data->count);
	while(!atomic_read(&data->gate))
		cpu_relax();

	/*  The master has cleared me to execute  */
	if (data->smp_reg != ~0U) 
		mtrr_if->set(data->smp_reg, data->smp_base, 
			     data->smp_size, data->smp_type);
	else
		mtrr_if->set_all();

	atomic_dec(&data->count);
	while(atomic_read(&data->gate))
		cpu_relax();

	atomic_dec(&data->count);
	local_irq_restore(flags);
#endif
162
}
L
Linus Torvalds 已提交
163

J
Jan Beulich 已提交
164 165 166 167 168 169 170
static inline int types_compatible(mtrr_type type1, mtrr_type type2) {
	return type1 == MTRR_TYPE_UNCACHABLE ||
	       type2 == MTRR_TYPE_UNCACHABLE ||
	       (type1 == MTRR_TYPE_WRTHROUGH && type2 == MTRR_TYPE_WRBACK) ||
	       (type1 == MTRR_TYPE_WRBACK && type2 == MTRR_TYPE_WRTHROUGH);
}

L
Linus Torvalds 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
/**
 * set_mtrr - update mtrrs on all processors
 * @reg:	mtrr in question
 * @base:	mtrr base
 * @size:	mtrr size
 * @type:	mtrr type
 *
 * This is kinda tricky, but fortunately, Intel spelled it out for us cleanly:
 * 
 * 1. Send IPI to do the following:
 * 2. Disable Interrupts
 * 3. Wait for all procs to do so 
 * 4. Enter no-fill cache mode
 * 5. Flush caches
 * 6. Clear PGE bit
 * 7. Flush all TLBs
 * 8. Disable all range registers
 * 9. Update the MTRRs
 * 10. Enable all range registers
 * 11. Flush all TLBs and caches again
 * 12. Enter normal cache mode and reenable caching
 * 13. Set PGE 
 * 14. Wait for buddies to catch up
 * 15. Enable interrupts.
 * 
 * What does that mean for us? Well, first we set data.count to the number
 * of CPUs. As each CPU disables interrupts, it'll decrement it once. We wait
 * until it hits 0 and proceed. We set the data.gate flag and reset data.count.
 * Meanwhile, they are waiting for that flag to be set. Once it's set, each 
 * CPU goes through the transition of updating MTRRs. The CPU vendors may each do it 
 * differently, so we call mtrr_if->set() callback and let them take care of it.
 * When they're done, they again decrement data->count and wait for data.gate to 
 * be reset. 
 * When we finish, we wait for data.count to hit 0 and toggle the data.gate flag.
 * Everyone then enables interrupts and we all continue on.
 *
 * Note that the mechanism is the same for UP systems, too; all the SMP stuff
 * becomes nops.
 */
static void set_mtrr(unsigned int reg, unsigned long base,
		     unsigned long size, mtrr_type type)
{
	struct set_mtrr_data data;
	unsigned long flags;

	data.smp_reg = reg;
	data.smp_base = base;
	data.smp_size = size;
	data.smp_type = type;
	atomic_set(&data.count, num_booting_cpus() - 1);
221 222
	/* make sure data.count is visible before unleashing other CPUs */
	smp_wmb();
L
Linus Torvalds 已提交
223 224 225
	atomic_set(&data.gate,0);

	/*  Start the ball rolling on other CPUs  */
226
	if (smp_call_function(ipi_handler, &data, 0) != 0)
L
Linus Torvalds 已提交
227 228 229 230 231 232 233 234 235
		panic("mtrr: timed out waiting for other CPUs\n");

	local_irq_save(flags);

	while(atomic_read(&data.count))
		cpu_relax();

	/* ok, reset count and toggle gate */
	atomic_set(&data.count, num_booting_cpus() - 1);
236
	smp_wmb();
L
Linus Torvalds 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
	atomic_set(&data.gate,1);

	/* do our MTRR business */

	/* HACK!
	 * We use this same function to initialize the mtrrs on boot.
	 * The state of the boot cpu's mtrrs has been saved, and we want
	 * to replicate across all the APs. 
	 * If we're doing that @reg is set to something special...
	 */
	if (reg != ~0U) 
		mtrr_if->set(reg,base,size,type);

	/* wait for the others */
	while(atomic_read(&data.count))
		cpu_relax();

	atomic_set(&data.count, num_booting_cpus() - 1);
255
	smp_wmb();
L
Linus Torvalds 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269
	atomic_set(&data.gate,0);

	/*
	 * Wait here for everyone to have seen the gate change
	 * So we're the last ones to touch 'data'
	 */
	while(atomic_read(&data.count))
		cpu_relax();

	local_irq_restore(flags);
}

/**
 *	mtrr_add_page - Add a memory type region
270 271
 *	@base: Physical base address of region in pages (in units of 4 kB!)
 *	@size: Physical size of region in pages (4 kB)
L
Linus Torvalds 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
 *	@type: Type of MTRR desired
 *	@increment: If this is true do usage counting on the region
 *
 *	Memory type region registers control the caching on newer Intel and
 *	non Intel processors. This function allows drivers to request an
 *	MTRR is added. The details and hardware specifics of each processor's
 *	implementation are hidden from the caller, but nevertheless the 
 *	caller should expect to need to provide a power of two size on an
 *	equivalent power of two boundary.
 *
 *	If the region cannot be added either because all regions are in use
 *	or the CPU cannot support it a negative value is returned. On success
 *	the register number for this entry is returned, but should be treated
 *	as a cookie only.
 *
 *	On a multiprocessor machine the changes are made to all processors.
 *	This is required on x86 by the Intel processors.
 *
 *	The available types are
 *
 *	%MTRR_TYPE_UNCACHABLE	-	No caching
 *
 *	%MTRR_TYPE_WRBACK	-	Write data back in bursts whenever
 *
 *	%MTRR_TYPE_WRCOMB	-	Write data back soon but allow bursts
 *
 *	%MTRR_TYPE_WRTHROUGH	-	Cache reads but not writes
 *
 *	BUGS: Needs a quiet flag for the cases where drivers do not mind
 *	failures and do not wish system log messages to be sent.
 */

int mtrr_add_page(unsigned long base, unsigned long size, 
305
		  unsigned int type, bool increment)
L
Linus Torvalds 已提交
306
{
J
Jan Beulich 已提交
307
	int i, replace, error;
L
Linus Torvalds 已提交
308
	mtrr_type ltype;
J
Jan Beulich 已提交
309
	unsigned long lbase, lsize;
L
Linus Torvalds 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

	if (!mtrr_if)
		return -ENXIO;
		
	if ((error = mtrr_if->validate_add_page(base,size,type)))
		return error;

	if (type >= MTRR_NUM_TYPES) {
		printk(KERN_WARNING "mtrr: type: %u invalid\n", type);
		return -EINVAL;
	}

	/*  If the type is WC, check that this processor supports it  */
	if ((type == MTRR_TYPE_WRCOMB) && !have_wrcomb()) {
		printk(KERN_WARNING
		       "mtrr: your processor doesn't support write-combining\n");
		return -ENOSYS;
	}

J
Jan Beulich 已提交
329 330 331 332 333
	if (!size) {
		printk(KERN_WARNING "mtrr: zero sized request\n");
		return -EINVAL;
	}

L
Linus Torvalds 已提交
334 335 336 337 338 339
	if (base & size_or_mask || size & size_or_mask) {
		printk(KERN_WARNING "mtrr: base or size exceeds the MTRR width\n");
		return -EINVAL;
	}

	error = -EINVAL;
J
Jan Beulich 已提交
340
	replace = -1;
L
Linus Torvalds 已提交
341

S
Shaohua Li 已提交
342
	/* No CPU hotplug when we change MTRR entries */
343
	get_online_cpus();
L
Linus Torvalds 已提交
344
	/*  Search for existing MTRR  */
345
	mutex_lock(&mtrr_mutex);
L
Linus Torvalds 已提交
346 347
	for (i = 0; i < num_var_ranges; ++i) {
		mtrr_if->get(i, &lbase, &lsize, &ltype);
J
Jan Beulich 已提交
348
		if (!lsize || base > lbase + lsize - 1 || base + size - 1 < lbase)
L
Linus Torvalds 已提交
349 350
			continue;
		/*  At this point we know there is some kind of overlap/enclosure  */
J
Jan Beulich 已提交
351 352 353 354 355 356 357 358 359 360
		if (base < lbase || base + size - 1 > lbase + lsize - 1) {
			if (base <= lbase && base + size - 1 >= lbase + lsize - 1) {
				/*  New region encloses an existing region  */
				if (type == ltype) {
					replace = replace == -1 ? i : -2;
					continue;
				}
				else if (types_compatible(type, ltype))
					continue;
			}
L
Linus Torvalds 已提交
361 362
			printk(KERN_WARNING
			       "mtrr: 0x%lx000,0x%lx000 overlaps existing"
J
Jan Beulich 已提交
363
			       " 0x%lx000,0x%lx000\n", base, size, lbase,
L
Linus Torvalds 已提交
364 365 366 367 368
			       lsize);
			goto out;
		}
		/*  New region is enclosed by an existing region  */
		if (ltype != type) {
J
Jan Beulich 已提交
369
			if (types_compatible(type, ltype))
L
Linus Torvalds 已提交
370 371 372 373 374 375 376
				continue;
			printk (KERN_WARNING "mtrr: type mismatch for %lx000,%lx000 old: %s new: %s\n",
			     base, size, mtrr_attrib_to_str(ltype),
			     mtrr_attrib_to_str(type));
			goto out;
		}
		if (increment)
377
			++mtrr_usage_table[i];
L
Linus Torvalds 已提交
378 379 380 381
		error = i;
		goto out;
	}
	/*  Search for an empty MTRR  */
J
Jan Beulich 已提交
382
	i = mtrr_if->get_free_region(base, size, replace);
L
Linus Torvalds 已提交
383 384
	if (i >= 0) {
		set_mtrr(i, base, size, type);
385 386 387 388
		if (likely(replace < 0)) {
			mtrr_usage_table[i] = 1;
		} else {
			mtrr_usage_table[i] = mtrr_usage_table[replace];
389
			if (increment)
390
				mtrr_usage_table[i]++;
J
Jan Beulich 已提交
391 392
			if (unlikely(replace != i)) {
				set_mtrr(replace, 0, 0, 0);
393
				mtrr_usage_table[replace] = 0;
J
Jan Beulich 已提交
394 395
			}
		}
L
Linus Torvalds 已提交
396 397 398 399
	} else
		printk(KERN_INFO "mtrr: no more MTRRs available\n");
	error = i;
 out:
400
	mutex_unlock(&mtrr_mutex);
401
	put_online_cpus();
L
Linus Torvalds 已提交
402 403 404
	return error;
}

405 406 407 408 409 410 411 412 413 414 415 416 417
static int mtrr_check(unsigned long base, unsigned long size)
{
	if ((base & (PAGE_SIZE - 1)) || (size & (PAGE_SIZE - 1))) {
		printk(KERN_WARNING
			"mtrr: size and base must be multiples of 4 kiB\n");
		printk(KERN_DEBUG
			"mtrr: size: 0x%lx  base: 0x%lx\n", size, base);
		dump_stack();
		return -1;
	}
	return 0;
}

L
Linus Torvalds 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
/**
 *	mtrr_add - Add a memory type region
 *	@base: Physical base address of region
 *	@size: Physical size of region
 *	@type: Type of MTRR desired
 *	@increment: If this is true do usage counting on the region
 *
 *	Memory type region registers control the caching on newer Intel and
 *	non Intel processors. This function allows drivers to request an
 *	MTRR is added. The details and hardware specifics of each processor's
 *	implementation are hidden from the caller, but nevertheless the 
 *	caller should expect to need to provide a power of two size on an
 *	equivalent power of two boundary.
 *
 *	If the region cannot be added either because all regions are in use
 *	or the CPU cannot support it a negative value is returned. On success
 *	the register number for this entry is returned, but should be treated
 *	as a cookie only.
 *
 *	On a multiprocessor machine the changes are made to all processors.
 *	This is required on x86 by the Intel processors.
 *
 *	The available types are
 *
 *	%MTRR_TYPE_UNCACHABLE	-	No caching
 *
 *	%MTRR_TYPE_WRBACK	-	Write data back in bursts whenever
 *
 *	%MTRR_TYPE_WRCOMB	-	Write data back soon but allow bursts
 *
 *	%MTRR_TYPE_WRTHROUGH	-	Cache reads but not writes
 *
 *	BUGS: Needs a quiet flag for the cases where drivers do not mind
 *	failures and do not wish system log messages to be sent.
 */

int
mtrr_add(unsigned long base, unsigned long size, unsigned int type,
456
	 bool increment)
L
Linus Torvalds 已提交
457
{
458
	if (mtrr_check(base, size))
L
Linus Torvalds 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
		return -EINVAL;
	return mtrr_add_page(base >> PAGE_SHIFT, size >> PAGE_SHIFT, type,
			     increment);
}

/**
 *	mtrr_del_page - delete a memory type region
 *	@reg: Register returned by mtrr_add
 *	@base: Physical base address
 *	@size: Size of region
 *
 *	If register is supplied then base and size are ignored. This is
 *	how drivers should call it.
 *
 *	Releases an MTRR region. If the usage count drops to zero the 
 *	register is freed and the region returns to default state.
 *	On success the register is returned, on failure a negative error
 *	code.
 */

int mtrr_del_page(int reg, unsigned long base, unsigned long size)
{
	int i, max;
	mtrr_type ltype;
J
Jan Beulich 已提交
483
	unsigned long lbase, lsize;
L
Linus Torvalds 已提交
484 485 486 487 488 489
	int error = -EINVAL;

	if (!mtrr_if)
		return -ENXIO;

	max = num_var_ranges;
S
Shaohua Li 已提交
490
	/* No CPU hotplug when we change MTRR entries */
491
	get_online_cpus();
492
	mutex_lock(&mtrr_mutex);
L
Linus Torvalds 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
	if (reg < 0) {
		/*  Search for existing MTRR  */
		for (i = 0; i < max; ++i) {
			mtrr_if->get(i, &lbase, &lsize, &ltype);
			if (lbase == base && lsize == size) {
				reg = i;
				break;
			}
		}
		if (reg < 0) {
			printk(KERN_DEBUG "mtrr: no MTRR for %lx000,%lx000 found\n", base,
			       size);
			goto out;
		}
	}
	if (reg >= max) {
		printk(KERN_WARNING "mtrr: register: %d too big\n", reg);
		goto out;
	}
	mtrr_if->get(reg, &lbase, &lsize, &ltype);
	if (lsize < 1) {
		printk(KERN_WARNING "mtrr: MTRR %d not used\n", reg);
		goto out;
	}
517
	if (mtrr_usage_table[reg] < 1) {
L
Linus Torvalds 已提交
518 519 520
		printk(KERN_WARNING "mtrr: reg: %d has count=0\n", reg);
		goto out;
	}
521
	if (--mtrr_usage_table[reg] < 1)
L
Linus Torvalds 已提交
522 523 524
		set_mtrr(reg, 0, 0, 0);
	error = reg;
 out:
525
	mutex_unlock(&mtrr_mutex);
526
	put_online_cpus();
L
Linus Torvalds 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
	return error;
}
/**
 *	mtrr_del - delete a memory type region
 *	@reg: Register returned by mtrr_add
 *	@base: Physical base address
 *	@size: Size of region
 *
 *	If register is supplied then base and size are ignored. This is
 *	how drivers should call it.
 *
 *	Releases an MTRR region. If the usage count drops to zero the 
 *	register is freed and the region returns to default state.
 *	On success the register is returned, on failure a negative error
 *	code.
 */

int
mtrr_del(int reg, unsigned long base, unsigned long size)
{
547
	if (mtrr_check(base, size))
L
Linus Torvalds 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560
		return -EINVAL;
	return mtrr_del_page(reg, base >> PAGE_SHIFT, size >> PAGE_SHIFT);
}

EXPORT_SYMBOL(mtrr_add);
EXPORT_SYMBOL(mtrr_del);

/* HACK ALERT!
 * These should be called implicitly, but we can't yet until all the initcall
 * stuff is done...
 */
static void __init init_ifs(void)
{
561
#ifndef CONFIG_X86_64
L
Linus Torvalds 已提交
562 563 564
	amd_init_mtrr();
	cyrix_init_mtrr();
	centaur_init_mtrr();
565
#endif
L
Linus Torvalds 已提交
566 567
}

S
Shaohua Li 已提交
568 569 570
/* The suspend/resume methods are only for CPU without MTRR. CPU using generic
 * MTRR driver doesn't require this
 */
L
Linus Torvalds 已提交
571 572 573
struct mtrr_value {
	mtrr_type	ltype;
	unsigned long	lbase;
J
Jan Beulich 已提交
574
	unsigned long	lsize;
L
Linus Torvalds 已提交
575 576
};

577
static struct mtrr_value mtrr_state[MTRR_MAX_VAR_RANGES];
L
Linus Torvalds 已提交
578

579
static int mtrr_save(struct sys_device * sysdev, pm_message_t state)
L
Linus Torvalds 已提交
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
{
	int i;

	for (i = 0; i < num_var_ranges; i++) {
		mtrr_if->get(i,
			     &mtrr_state[i].lbase,
			     &mtrr_state[i].lsize,
			     &mtrr_state[i].ltype);
	}
	return 0;
}

static int mtrr_restore(struct sys_device * sysdev)
{
	int i;

	for (i = 0; i < num_var_ranges; i++) {
		if (mtrr_state[i].lsize) 
			set_mtrr(i,
				 mtrr_state[i].lbase,
				 mtrr_state[i].lsize,
				 mtrr_state[i].ltype);
	}
	return 0;
}



static struct sysdev_driver mtrr_sysdev_driver = {
	.suspend	= mtrr_save,
	.resume		= mtrr_restore,
};

613
/* should be related to MTRR_VAR_RANGES nums */
614 615 616 617 618 619 620
#define RANGE_NUM 256

struct res_range {
	unsigned long start;
	unsigned long end;
};

621 622 623
static int __init
add_range(struct res_range *range, int nr_range, unsigned long start,
			      unsigned long end)
624
{
625 626 627
	/* out of slots */
	if (nr_range >= RANGE_NUM)
		return nr_range;
628

629 630 631 632 633 634 635 636 637 638 639 640 641
	range[nr_range].start = start;
	range[nr_range].end = end;

	nr_range++;

	return nr_range;
}

static int __init
add_range_with_merge(struct res_range *range, int nr_range, unsigned long start,
			      unsigned long end)
{
	int i;
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664

	/* try to merge it with old one */
	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;
	}

	/* need to add that */
665
	return add_range(range, nr_range, start, end);
666
}
667 668 669

static void __init
subtract_range(struct res_range *range, unsigned long start, unsigned long end)
670
{
671
	int i, j;
672 673 674 675 676 677 678 679 680 681 682

	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;
		}

683 684
		if (start <= range[j].start && end < range[j].end &&
		    range[j].start < end + 1) {
685 686 687 688 689
			range[j].start = end + 1;
			continue;
		}


690 691
		if (start > range[j].start && end >= range[j].end &&
		    range[j].end > start - 1) {
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
			range[j].end = start - 1;
			continue;
		}

		if (start > range[j].start && end < range[j].end) {
			/* find the new spare */
			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;
}

726 727 728 729 730 731
struct var_mtrr_range_state {
	unsigned long base_pfn;
	unsigned long size_pfn;
	mtrr_type type;
};

732
static struct var_mtrr_range_state __initdata range_state[RANGE_NUM];
733
static int __initdata debug_print;
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751

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)
{
	unsigned long i, base, size;
	mtrr_type type;

	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);
	}
752 753 754 755
	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",
756
				 range[i].start, range[i].end + 1);
757
	}
758 759 760 761

	/* take out UC ranges */
	for (i = 0; i < num_var_ranges; i++) {
		type = range_state[i].type;
762 763
		if (type != MTRR_TYPE_UNCACHABLE &&
		    type != MTRR_TYPE_WRPROT)
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
			continue;
		size = range_state[i].size_pfn;
		if (!size)
			continue;
		base = range_state[i].base_pfn;
		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++;
	}
782 783 784 785 786 787
	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);
	}
788 789 790

	/* sort the ranges */
	sort(range, nr_range, sizeof(struct res_range), cmp_range, NULL);
791 792 793 794
	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",
795
				 range[i].start, range[i].end + 1);
796
	}
797 798 799 800 801 802 803 804 805

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

	return nr_range;
}

static struct res_range __initdata range[RANGE_NUM];
806
static int __initdata nr_range;
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826

#ifdef CONFIG_MTRR_SANITIZER

static unsigned long __init sum_ranges(struct res_range *range, int nr_range)
{
	unsigned long sum;
	int i;

	sum = 0;
	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)
{
827
	enable_mtrr_cleanup = 0;
828 829 830 831 832 833
	return 0;
}
early_param("disable_mtrr_cleanup", disable_mtrr_cleanup_setup);

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

839 840 841 842 843 844
static int __init mtrr_cleanup_debug_setup(char *str)
{
	debug_print = 1;
	return 0;
}
early_param("mtrr_cleanup_debug", mtrr_cleanup_debug_setup);
845

846
struct var_mtrr_state {
847 848 849 850 851
	unsigned long	range_startk;
	unsigned long	range_sizek;
	unsigned long	chunk_sizek;
	unsigned long	gran_sizek;
	unsigned int	reg;
852 853
};

854 855
static void __init
set_var_mtrr(unsigned int reg, unsigned long basek, unsigned long sizek,
856
		unsigned char type, unsigned int address_bits)
857 858
{
	u32 base_lo, base_hi, mask_lo, mask_hi;
859
	u64 base, mask;
860 861 862 863 864 865

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

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

869
	base  = ((u64)basek) << 10;
870

871 872 873 874 875 876 877 878
	base |= type;
	mask |= 0x800;

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

	mask_lo = mask & ((1ULL<<32) - 1);
	mask_hi = mask >> 32;
879 880 881 882

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

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
static void __init
save_var_mtrr(unsigned int reg, unsigned long basek, unsigned long sizek,
		unsigned char type)
{
	range_state[reg].base_pfn = basek >> (PAGE_SHIFT - 10);
	range_state[reg].size_pfn = sizek >> (PAGE_SHIFT - 10);
	range_state[reg].type = type;
}

static void __init
set_var_mtrr_all(unsigned int address_bits)
{
	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);
	}
}

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
static unsigned long to_size_factor(unsigned long sizek, char *factorp)
{
	char factor;
	unsigned long base = sizek;

	if (base & ((1<<10) - 1)) {
		/* not MB alignment */
		factor = 'K';
	} else if (base & ((1<<20) - 1)){
		factor = 'M';
		base >>= 10;
	} else {
		factor = 'G';
		base >>= 20;
	}

	*factorp = factor;

	return base;
}

929 930
static unsigned int __init
range_to_mtrr(unsigned int reg, unsigned long range_startk,
931
	      unsigned long range_sizek, unsigned char type)
932 933 934 935 936 937 938
{
	if (!range_sizek || (reg >= num_var_ranges))
		return reg;

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

940 941 942 943 944 945 946 947 948 949
		/* Compute the maximum size I can make a range */
		if (range_startk)
			max_align = ffs(range_startk) - 1;
		else
			max_align = 32;
		align = fls(range_sizek) - 1;
		if (align > max_align)
			align = max_align;

		sizek = 1 << align;
950 951 952 953 954 955 956
		if (debug_print) {
			char start_factor = 'K', size_factor = 'K';
			unsigned long start_base, size_base;

			start_base = to_size_factor(range_startk, &start_factor),
			size_base = to_size_factor(sizek, &size_factor),

957
			printk(KERN_DEBUG "Setting variable MTRR %d, "
958 959 960
				"base: %ld%cB, range: %ld%cB, type %s\n",
				reg, start_base, start_factor,
				size_base, size_factor,
961 962 963
				(type == MTRR_TYPE_UNCACHABLE)?"UC":
				    ((type == MTRR_TYPE_WRBACK)?"WB":"Other")
				);
964
		}
965
		save_var_mtrr(reg++, range_startk, sizek, type);
966 967 968 969 970 971 972 973
		range_startk += sizek;
		range_sizek -= sizek;
		if (reg >= num_var_ranges)
			break;
	}
	return reg;
}

974 975 976
static unsigned __init
range_to_mtrr_with_hole(struct var_mtrr_state *state, unsigned long basek,
			unsigned long sizek)
977 978
{
	unsigned long hole_basek, hole_sizek;
979
	unsigned long second_basek, second_sizek;
980 981 982 983 984 985 986
	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;
987 988
	second_basek = 0;
	second_sizek = 0;
989 990 991 992 993 994
	chunk_sizek = state->chunk_sizek;
	gran_sizek = state->gran_sizek;

	/* align with gran size, prevent small block used up MTRRs */
	range_basek = ALIGN(state->range_startk, gran_sizek);
	if ((range_basek > basek) && basek)
995 996 997
		return second_sizek;
	state->range_sizek -= (range_basek - state->range_startk);
	range_sizek = ALIGN(state->range_sizek, gran_sizek);
998

999
	while (range_sizek > state->range_sizek) {
1000 1001
		range_sizek -= gran_sizek;
		if (!range_sizek)
1002
			return 0;
1003 1004 1005 1006 1007 1008
	}
	state->range_sizek = range_sizek;

	/* try to append some small hole */
	range0_basek = state->range_startk;
	range0_sizek = ALIGN(state->range_sizek, chunk_sizek);
Y
Yinghai Lu 已提交
1009 1010

	/* no increase */
1011
	if (range0_sizek == state->range_sizek) {
1012 1013 1014
		if (debug_print)
			printk(KERN_DEBUG "rangeX: %016lx - %016lx\n",
				range0_basek<<10,
1015 1016 1017 1018 1019 1020
				(range0_basek + state->range_sizek)<<10);
		state->reg = range_to_mtrr(state->reg, range0_basek,
				state->range_sizek, MTRR_TYPE_WRBACK);
		return 0;
	}

Y
Yinghai Lu 已提交
1021 1022 1023
	/* only cut back, when it is not the last */
	if (sizek) {
		while (range0_basek + range0_sizek > (basek + sizek)) {
1024 1025 1026 1027 1028
			if (range0_sizek >= chunk_sizek)
				range0_sizek -= chunk_sizek;
			else
				range0_sizek = 0;

Y
Yinghai Lu 已提交
1029 1030 1031
			if (!range0_sizek)
				break;
		}
1032 1033
	}

1034
second_try:
1035
	range_basek = range0_basek + range0_sizek;
1036

Y
Yinghai Lu 已提交
1037 1038 1039 1040 1041 1042 1043 1044
	/* one hole in the middle */
	if (range_basek > basek && range_basek <= (basek + sizek))
		second_sizek = range_basek - basek;

	if (range0_sizek > state->range_sizek) {

		/* one hole in middle or at end */
		hole_sizek = range0_sizek - state->range_sizek - second_sizek;
1045 1046

		/* hole size should be less than half of range0 size */
1047
		if (hole_sizek >= (range0_sizek >> 1) &&
1048 1049 1050 1051 1052 1053
		    range0_sizek >= chunk_sizek) {
			range0_sizek -= chunk_sizek;
			second_sizek = 0;
			hole_sizek = 0;

			goto second_try;
Y
Yinghai Lu 已提交
1054
		}
1055 1056
	}

1057
	if (range0_sizek) {
1058 1059 1060
		if (debug_print)
			printk(KERN_DEBUG "range0: %016lx - %016lx\n",
				range0_basek<<10,
1061 1062 1063 1064 1065
				(range0_basek + range0_sizek)<<10);
		state->reg = range_to_mtrr(state->reg, range0_basek,
				range0_sizek, MTRR_TYPE_WRBACK);
	}

1066
	if (range0_sizek < state->range_sizek) {
Y
Yinghai Lu 已提交
1067
		/* need to handle left over */
1068 1069
		range_sizek = state->range_sizek - range0_sizek;

1070 1071 1072 1073 1074 1075
		if (debug_print)
			printk(KERN_DEBUG "range: %016lx - %016lx\n",
				 range_basek<<10,
				 (range_basek + range_sizek)<<10);
		state->reg = range_to_mtrr(state->reg, range_basek,
				 range_sizek, MTRR_TYPE_WRBACK);
1076
	}
1077 1078

	if (hole_sizek) {
1079
		hole_basek = range_basek - hole_sizek - second_sizek;
1080 1081
		if (debug_print)
			printk(KERN_DEBUG "hole: %016lx - %016lx\n",
1082 1083 1084 1085
				 hole_basek<<10,
				 (hole_basek + hole_sizek)<<10);
		state->reg = range_to_mtrr(state->reg, hole_basek,
				 hole_sizek, MTRR_TYPE_UNCACHABLE);
1086
	}
1087 1088

	return second_sizek;
1089 1090
}

1091 1092 1093
static void __init
set_var_mtrr_range(struct var_mtrr_state *state, unsigned long base_pfn,
		   unsigned long size_pfn)
1094 1095
{
	unsigned long basek, sizek;
1096
	unsigned long second_sizek = 0;
1097 1098 1099 1100 1101 1102 1103 1104

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

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

	/* See if I can merge with the last range */
1105 1106
	if ((basek <= 1024) ||
	    (state->range_startk + state->range_sizek == basek)) {
1107 1108 1109 1110 1111
		unsigned long endk = basek + sizek;
		state->range_sizek = endk - state->range_startk;
		return;
	}
	/* Write the range mtrrs */
1112 1113
	if (state->range_sizek != 0)
		second_sizek = range_to_mtrr_with_hole(state, basek, sizek);
1114 1115

	/* Allocate an msr */
1116 1117
	state->range_startk = basek + second_sizek;
	state->range_sizek  = sizek - second_sizek;
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
}

/* mininum size of mtrr block that can take hole */
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);

/* granity of mtrr of block */
1133
static u64 mtrr_gran_size __initdata;
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143

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);

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
static int nr_mtrr_spare_reg __initdata =
				 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
1157
x86_setup_var_mtrrs(struct res_range *range, int nr_range,
1158
		    u64 chunk_size, u64 gran_size)
1159 1160 1161
{
	struct var_mtrr_state var_state;
	int i;
1162
	int num_reg;
1163

1164 1165 1166
	var_state.range_startk	= 0;
	var_state.range_sizek	= 0;
	var_state.reg		= 0;
1167 1168 1169 1170
	var_state.chunk_sizek	= chunk_size >> 10;
	var_state.gran_sizek	= gran_size >> 10;

	memset(range_state, 0, sizeof(range_state));
1171 1172 1173

	/* Write the range etc */
	for (i = 0; i < nr_range; i++)
1174 1175
		set_var_mtrr_range(&var_state, range[i].start,
				   range[i].end - range[i].start + 1);
1176 1177

	/* Write the last range */
1178 1179 1180 1181
	if (var_state.range_sizek != 0)
		range_to_mtrr_with_hole(&var_state, 0, 0);

	num_reg = var_state.reg;
1182
	/* Clear out the extra MTRR's */
1183
	while (var_state.reg < num_var_ranges) {
1184
		save_var_mtrr(var_state.reg, 0, 0, 0);
1185 1186
		var_state.reg++;
	}
1187

1188 1189
	return num_reg;
}
1190

1191 1192 1193 1194 1195 1196 1197
struct mtrr_cleanup_result {
	unsigned long gran_sizek;
	unsigned long chunk_sizek;
	unsigned long lose_cover_sizek;
	unsigned int num_reg;
	int bad;
};
1198

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

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

1210
static void __init print_out_mtrr_range_state(void)
1211
{
1212
	int i;
1213 1214 1215
	char start_factor = 'K', size_factor = 'K';
	unsigned long start_base, size_base;
	mtrr_type type;
1216

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

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

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
		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"))
			);
1235
	}
1236 1237 1238 1239 1240 1241 1242 1243 1244
}

static int __init mtrr_need_cleanup(void)
{
	int i;
	mtrr_type type;
	unsigned long size;
	/* extra one for all 0 */
	int num[MTRR_NUM_TYPES + 1];
1245

1246 1247 1248
	/* check entries number */
	memset(num, 0, sizeof(num));
	for (i = 0; i < num_var_ranges; i++) {
1249 1250
		type = range_state[i].type;
		size = range_state[i].size_pfn;
1251 1252 1253 1254
		if (type >= MTRR_NUM_TYPES)
			continue;
		if (!size)
			type = MTRR_NUM_TYPES;
1255 1256
		if (type == MTRR_TYPE_WRPROT)
			type = MTRR_TYPE_UNCACHABLE;
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
		num[type]++;
	}

	/* check if we got UC entries */
	if (!num[MTRR_TYPE_UNCACHABLE])
		return 0;

	/* check if we only had WB and UC */
	if (num[MTRR_TYPE_WRBACK] + num[MTRR_TYPE_UNCACHABLE] !=
		num_var_ranges - num[MTRR_NUM_TYPES])
		return 0;

1269 1270
	return 1;
}
1271

1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
static unsigned long __initdata range_sums;
static void __init mtrr_calc_range_state(u64 chunk_size, u64 gran_size,
					 unsigned long extra_remove_base,
					 unsigned long extra_remove_size,
					 int i)
{
	int num_reg;
	static struct res_range range_new[RANGE_NUM];
	static int nr_range_new;
	unsigned long range_sums_new;

	/* convert ranges to var ranges state */
	num_reg = x86_setup_var_mtrrs(range, nr_range,
						chunk_size, gran_size);

	/* we got new setting in range_state, check it */
	memset(range_new, 0, sizeof(range_new));
	nr_range_new = x86_get_mtrr_mem_range(range_new, 0,
				extra_remove_base, extra_remove_size);
	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;
	if (range_sums < range_sums_new) {
		result[i].lose_cover_sizek =
			(range_sums_new - range_sums) << PSHIFT;
		result[i].bad = 1;
	} else
		result[i].lose_cover_sizek =
			(range_sums - range_sums_new) << PSHIFT;
1303

1304 1305 1306 1307 1308 1309
	/* double check it */
	if (!result[i].bad && !result[i].lose_cover_sizek) {
		if (nr_range_new != nr_range ||
			memcmp(range, range_new, sizeof(range)))
				result[i].bad = 1;
	}
1310

1311 1312 1313 1314
	if (!result[i].bad && (range_sums - range_sums_new <
				min_loss_pfn[num_reg])) {
		min_loss_pfn[num_reg] =
			range_sums - range_sums_new;
1315
	}
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
}

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

	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),
	printk(KERN_INFO "%sgran_size: %ld%c \tchunk_size: %ld%c \t",
			result[i].bad ? "*BAD*" : " ",
			gran_base, gran_factor, chunk_base, chunk_factor);
	printk(KERN_CONT "num_reg: %d  \tlose cover RAM: %s%ld%c\n",
			result[i].num_reg, result[i].bad ? "-" : "",
			lose_base, lose_factor);
}

static int __init mtrr_search_optimal_index(void)
{
	int i;
	int num_reg_good;
	int index_good;

	if (nr_mtrr_spare_reg >= num_var_ranges)
		nr_mtrr_spare_reg = num_var_ranges - 1;
	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;
}


static int __init mtrr_cleanup(unsigned address_bits)
{
	unsigned long extra_remove_base, extra_remove_size;
	unsigned long base, size, def, dummy;
	mtrr_type type;
	u64 chunk_size, gran_size;
	int index_good;
	int i;

	if (!is_cpu(INTEL) || enable_mtrr_cleanup < 1)
		return 0;
	rdmsr(MTRRdefType_MSR, def, dummy);
	def &= 0xff;
	if (def != MTRR_TYPE_UNCACHABLE)
		return 0;

	/* get it and store it aside */
	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;
	}

	/* check if we need handle it and can handle it */
	if (!mtrr_need_cleanup())
		return 0;

	/* print original var MTRRs at first, for debugging: */
	printk(KERN_DEBUG "original variable MTRRs\n");
	print_out_mtrr_range_state();
1396

1397 1398
	memset(range, 0, sizeof(range));
	extra_remove_size = 0;
1399 1400
	extra_remove_base = 1 << (32 - PAGE_SHIFT);
	if (mtrr_tom2)
1401 1402 1403 1404
		extra_remove_size =
			(mtrr_tom2 >> PAGE_SHIFT) - extra_remove_base;
	nr_range = x86_get_mtrr_mem_range(range, 0, extra_remove_base,
					  extra_remove_size);
1405 1406 1407 1408 1409 1410 1411 1412 1413
	/*
	 * [0, 1M) should always be coverred by var mtrr with WB
	 * and fixed mtrrs should take effective before var mtrr for it
	 */
	nr_range = add_range_with_merge(range, nr_range, 0,
					(1ULL<<(20 - PAGE_SHIFT)) - 1);
	/* sort the ranges */
	sort(range, nr_range, sizeof(struct res_range), cmp_range, NULL);

1414 1415 1416 1417 1418
	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) {
1419 1420 1421
		i = 0;
		mtrr_calc_range_state(mtrr_chunk_size, mtrr_gran_size,
				      extra_remove_base, extra_remove_size, i);
1422

1423
		mtrr_print_out_one_result(i);
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435

		if (!result[i].bad) {
			set_var_mtrr_all(address_bits);
			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));
1436
	for (gran_size = (1ULL<<16); gran_size < (1ULL<<32); gran_size <<= 1) {
1437

1438
		for (chunk_size = gran_size; chunk_size < (1ULL<<32);
1439 1440 1441 1442 1443
		     chunk_size <<= 1) {

			if (i >= NUM_RESULT)
				continue;

1444 1445 1446 1447 1448
			mtrr_calc_range_state(chunk_size, gran_size,
				      extra_remove_base, extra_remove_size, i);
			if (debug_print) {
				mtrr_print_out_one_result(i);
				printk(KERN_INFO "\n");
1449 1450 1451 1452
			}

			i++;
		}
1453 1454
	}

1455
	/* try to find the optimal index */
1456
	index_good = mtrr_search_optimal_index();
1457 1458 1459 1460

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

1463 1464 1465 1466 1467 1468 1469
		/* convert ranges to var ranges state */
		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);
1470 1471
		printk(KERN_DEBUG "New variable MTRRs\n");
		print_out_mtrr_range_state();
1472
		return 1;
1473 1474 1475 1476
	} else {
		/* print out all */
		for (i = 0; i < NUM_RESULT; i++)
			mtrr_print_out_one_result(i);
1477 1478 1479 1480 1481 1482
	}

	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;
1483
}
1484 1485 1486 1487 1488 1489 1490 1491
#else
static int __init mtrr_cleanup(unsigned address_bits)
{
	return 0;
}
#endif

static int __initdata changed_by_mtrr_cleanup;
1492

1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
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.
 */
#define Tom2Enabled (1U << 21)
#define Tom2ForceMemTypeWB (1U << 22)

1511
int __init amd_special_default_mtrr(void)
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
{
	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;
	/* In case some hypervisor doesn't pass SYSCFG through */
	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;
}

1532 1533
static u64 __init real_trim_memory(unsigned long start_pfn,
				   unsigned long limit_pfn)
1534 1535
{
	u64 trim_start, trim_size;
1536
	trim_start = start_pfn;
1537 1538 1539 1540
	trim_start <<= PAGE_SHIFT;
	trim_size = limit_pfn;
	trim_size <<= PAGE_SHIFT;
	trim_size -= trim_start;
1541

1542
	return e820_update_range(trim_start, trim_size, E820_RAM,
1543 1544
				E820_RESERVED);
}
1545 1546
/**
 * mtrr_trim_uncached_memory - trim RAM not covered by MTRRs
1547
 * @end_pfn: ending page frame number
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
 *
 * 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
 * all of the memory the kernel is intending to use. If not, it'll trim any
 * 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)
{
Y
Yinghai Lu 已提交
1558
	unsigned long i, base, size, highest_pfn = 0, def, dummy;
1559
	mtrr_type type;
1560
	u64 total_trim_size;
1561

1562 1563
	/* extra one for all 0 */
	int num[MTRR_NUM_TYPES + 1];
1564 1565 1566 1567
	/*
	 * Make sure we only trim uncachable memory on machines that
	 * support the Intel MTRR architecture:
	 */
1568 1569
	if (!is_cpu(INTEL) || disable_mtrr_trim)
		return 0;
1570 1571
	rdmsr(MTRRdefType_MSR, def, dummy);
	def &= 0xff;
1572 1573 1574
	if (def != MTRR_TYPE_UNCACHABLE)
		return 0;

1575 1576
	/* get it and store it aside */
	memset(range_state, 0, sizeof(range_state));
1577 1578
	for (i = 0; i < num_var_ranges; i++) {
		mtrr_if->get(i, &base, &size, &type);
1579 1580 1581 1582 1583 1584 1585 1586
		range_state[i].base_pfn = base;
		range_state[i].size_pfn = size;
		range_state[i].type = type;
	}

	/* Find highest cached pfn */
	for (i = 0; i < num_var_ranges; i++) {
		type = range_state[i].type;
1587 1588
		if (type != MTRR_TYPE_WRBACK)
			continue;
1589 1590
		base = range_state[i].base_pfn;
		size = range_state[i].size_pfn;
Y
Yinghai Lu 已提交
1591 1592
		if (highest_pfn < base + size)
			highest_pfn = base + size;
1593 1594
	}

1595
	/* kvm/qemu doesn't have mtrr set right, don't trim them all */
Y
Yinghai Lu 已提交
1596
	if (!highest_pfn) {
1597
		WARN(!kvm_para_available(), KERN_WARNING
1598
				"WARNING: strange, CPU MTRRs all blank?\n");
1599
		return 0;
1600
	}
1601

1602 1603 1604
	/* check entries number */
	memset(num, 0, sizeof(num));
	for (i = 0; i < num_var_ranges; i++) {
1605
		type = range_state[i].type;
1606 1607
		if (type >= MTRR_NUM_TYPES)
			continue;
1608
		size = range_state[i].size_pfn;
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
		if (!size)
			type = MTRR_NUM_TYPES;
		num[type]++;
	}

	/* no entry for WB? */
	if (!num[MTRR_TYPE_WRBACK])
		return 0;

	/* check if we only had WB and UC */
	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);

1634
	total_trim_size = 0;
1635
	/* check the head */
1636
	if (range[0].start)
1637
		total_trim_size += real_trim_memory(0, range[0].start);
1638 1639
	/* check the holes */
	for (i = 0; i < nr_range - 1; i++) {
1640
		if (range[i].end + 1 < range[i+1].start)
1641 1642
			total_trim_size += real_trim_memory(range[i].end + 1,
							    range[i+1].start);
1643
	}
1644 1645 1646
	/* check the top */
	i = nr_range - 1;
	if (range[i].end + 1 < end_pfn)
1647 1648
		total_trim_size += real_trim_memory(range[i].end + 1,
							 end_pfn);
1649

1650
	if (total_trim_size) {
1651 1652
		printk(KERN_WARNING "WARNING: BIOS bug: CPU MTRRs don't cover"
			" all of memory, losing %lluMB of RAM.\n",
1653
			total_trim_size >> 20);
1654

1655
		if (!changed_by_mtrr_cleanup)
1656
			WARN_ON(1);
1657

1658
		printk(KERN_INFO "update e820 for mtrr\n");
1659
		update_e820();
1660 1661

		return 1;
1662 1663
	}

1664
	return 0;
1665
}
L
Linus Torvalds 已提交
1666 1667

/**
S
Shaohua Li 已提交
1668
 * mtrr_bp_init - initialize mtrrs on the boot CPU
L
Linus Torvalds 已提交
1669 1670 1671 1672 1673
 *
 * This needs to be called early; before any of the other CPUs are 
 * initialized (i.e. before smp_init()).
 * 
 */
1674
void __init mtrr_bp_init(void)
L
Linus Torvalds 已提交
1675
{
1676
	u32 phys_addr;
L
Linus Torvalds 已提交
1677 1678
	init_ifs();

1679 1680
	phys_addr = 32;

L
Linus Torvalds 已提交
1681 1682 1683 1684
	if (cpu_has_mtrr) {
		mtrr_if = &generic_mtrr_ops;
		size_or_mask = 0xff000000;	/* 36 bits */
		size_and_mask = 0x00f00000;
1685
		phys_addr = 36;
1686 1687 1688 1689 1690 1691

		/* This is an AMD specific MSR, but we assume(hope?) that
		   Intel will implement it to when they extend the address
		   bus of the Xeon. */
		if (cpuid_eax(0x80000000) >= 0x80000008) {
			phys_addr = cpuid_eax(0x80000008) & 0xff;
1692 1693 1694 1695 1696 1697 1698 1699
			/* CPUID workaround for Intel 0F33/0F34 CPU */
			if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL &&
			    boot_cpu_data.x86 == 0xF &&
			    boot_cpu_data.x86_model == 0x3 &&
			    (boot_cpu_data.x86_mask == 0x3 ||
			     boot_cpu_data.x86_mask == 0x4))
				phys_addr = 36;

1700 1701
			size_or_mask = ~((1ULL << (phys_addr - PAGE_SHIFT)) - 1);
			size_and_mask = ~size_or_mask & 0xfffff00000ULL;
1702 1703 1704 1705 1706 1707
		} else if (boot_cpu_data.x86_vendor == X86_VENDOR_CENTAUR &&
			   boot_cpu_data.x86 == 6) {
			/* VIA C* family have Intel style MTRRs, but
			   don't support PAE */
			size_or_mask = 0xfff00000;	/* 32 bits */
			size_and_mask = 0;
1708
			phys_addr = 32;
L
Linus Torvalds 已提交
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
		}
	} else {
		switch (boot_cpu_data.x86_vendor) {
		case X86_VENDOR_AMD:
			if (cpu_has_k6_mtrr) {
				/* Pre-Athlon (K6) AMD CPU MTRRs */
				mtrr_if = mtrr_ops[X86_VENDOR_AMD];
				size_or_mask = 0xfff00000;	/* 32 bits */
				size_and_mask = 0;
			}
			break;
		case X86_VENDOR_CENTAUR:
			if (cpu_has_centaur_mcr) {
				mtrr_if = mtrr_ops[X86_VENDOR_CENTAUR];
				size_or_mask = 0xfff00000;	/* 32 bits */
				size_and_mask = 0;
			}
			break;
		case X86_VENDOR_CYRIX:
			if (cpu_has_cyrix_arr) {
				mtrr_if = mtrr_ops[X86_VENDOR_CYRIX];
				size_or_mask = 0xfff00000;	/* 32 bits */
				size_and_mask = 0;
			}
			break;
		default:
			break;
		}
	}

	if (mtrr_if) {
		set_num_var_ranges();
		init_table();
1742
		if (use_intel()) {
S
Shaohua Li 已提交
1743
			get_mtrr_state();
1744

1745 1746
			if (mtrr_cleanup(phys_addr)) {
				changed_by_mtrr_cleanup = 1;
1747
				mtrr_if->set_all();
1748
			}
1749 1750

		}
L
Linus Torvalds 已提交
1751 1752 1753
	}
}

S
Shaohua Li 已提交
1754 1755 1756 1757 1758 1759 1760
void mtrr_ap_init(void)
{
	unsigned long flags;

	if (!mtrr_if || !use_intel())
		return;
	/*
1761
	 * Ideally we should hold mtrr_mutex here to avoid mtrr entries changed,
S
Shaohua Li 已提交
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
	 * but this routine will be called in cpu boot time, holding the lock
	 * breaks it. This routine is called in two cases: 1.very earily time
	 * of software resume, when there absolutely isn't mtrr entry changes;
	 * 2.cpu hotadd time. We let mtrr_add/del_page hold cpuhotplug lock to
	 * prevent mtrr entry changes
	 */
	local_irq_save(flags);

	mtrr_if->set_all();

	local_irq_restore(flags);
}

1775 1776 1777 1778 1779
/**
 * Save current fixed-range MTRR state of the BSP
 */
void mtrr_save_state(void)
{
1780
	smp_call_function_single(0, mtrr_save_fixed_ranges, NULL, 1);
1781 1782
}

S
Shaohua Li 已提交
1783 1784 1785 1786
static int __init mtrr_init_finialize(void)
{
	if (!mtrr_if)
		return 0;
1787
	if (use_intel()) {
1788
		if (!changed_by_mtrr_cleanup)
1789 1790
			mtrr_state_warn();
	} else {
S
Simon Arlott 已提交
1791
		/* The CPUs haven't MTRR and seem to not support SMP. They have
S
Shaohua Li 已提交
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
		 * specific drivers, we use a tricky method to support
		 * suspend/resume for them.
		 * TBD: is there any system with such CPU which supports
		 * suspend/resume?  if no, we should remove the code.
		 */
		sysdev_driver_register(&cpu_sysdev_class,
			&mtrr_sysdev_driver);
	}
	return 0;
}
subsys_initcall(mtrr_init_finialize);