/* Generic MTRR (Memory Type Range Register) driver.12Copyright (C) 1997-2000 Richard Gooch3Copyright (c) 2002 Patrick Mochel45This library is free software; you can redistribute it and/or6modify it under the terms of the GNU Library General Public7License as published by the Free Software Foundation; either8version 2 of the License, or (at your option) any later version.910This library is distributed in the hope that it will be useful,11but WITHOUT ANY WARRANTY; without even the implied warranty of12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU13Library General Public License for more details.1415You should have received a copy of the GNU Library General Public16License along with this library; if not, write to the Free17Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.1819Richard Gooch may be reached by email at [email protected]20The postal address is:21Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia.2223Source: "Pentium Pro Family Developer's Manual, Volume 3:24Operating System Writer's Guide" (Intel document number 242692),25section 11.11.72627This was cleaned and made readable by Patrick Mochel <[email protected]>28on 6-7 March 2002.29Source: Intel Architecture Software Developers Manual, Volume 3:30System Programming Guide; Section 9.11. (1997 edition - PPro).31*/3233#include <linux/types.h> /* FIXME: kvm_para.h needs this */3435#include <linux/stop_machine.h>36#include <linux/kvm_para.h>37#include <linux/uaccess.h>38#include <linux/export.h>39#include <linux/mutex.h>40#include <linux/init.h>41#include <linux/sort.h>42#include <linux/cpu.h>43#include <linux/pci.h>44#include <linux/smp.h>45#include <linux/syscore_ops.h>46#include <linux/rcupdate.h>4748#include <asm/cacheinfo.h>49#include <asm/cpufeature.h>50#include <asm/e820/api.h>51#include <asm/mtrr.h>52#include <asm/msr.h>53#include <asm/memtype.h>5455#include "mtrr.h"5657static_assert(X86_MEMTYPE_UC == MTRR_TYPE_UNCACHABLE);58static_assert(X86_MEMTYPE_WC == MTRR_TYPE_WRCOMB);59static_assert(X86_MEMTYPE_WT == MTRR_TYPE_WRTHROUGH);60static_assert(X86_MEMTYPE_WP == MTRR_TYPE_WRPROT);61static_assert(X86_MEMTYPE_WB == MTRR_TYPE_WRBACK);6263/* arch_phys_wc_add returns an MTRR register index plus this offset. */64#define MTRR_TO_PHYS_WC_OFFSET 10006566u32 num_var_ranges;6768unsigned int mtrr_usage_table[MTRR_MAX_VAR_RANGES];69DEFINE_MUTEX(mtrr_mutex);7071const struct mtrr_ops *mtrr_if;7273/* Returns non-zero if we have the write-combining memory type */74static int have_wrcomb(void)75{76struct pci_dev *dev;7778dev = pci_get_class(PCI_CLASS_BRIDGE_HOST << 8, NULL);79if (dev != NULL) {80/*81* ServerWorks LE chipsets < rev 6 have problems with82* write-combining. Don't allow it and leave room for other83* chipsets to be tagged84*/85if (dev->vendor == PCI_VENDOR_ID_SERVERWORKS &&86dev->device == PCI_DEVICE_ID_SERVERWORKS_LE &&87dev->revision <= 5) {88pr_info("Serverworks LE rev < 6 detected. Write-combining disabled.\n");89pci_dev_put(dev);90return 0;91}92/*93* Intel 450NX errata # 23. Non ascending cacheline evictions to94* write combining memory may resulting in data corruption95*/96if (dev->vendor == PCI_VENDOR_ID_INTEL &&97dev->device == PCI_DEVICE_ID_INTEL_82451NX) {98pr_info("Intel 450NX MMC detected. Write-combining disabled.\n");99pci_dev_put(dev);100return 0;101}102pci_dev_put(dev);103}104return mtrr_if->have_wrcomb ? mtrr_if->have_wrcomb() : 0;105}106107static void __init init_table(void)108{109int i, max;110111max = num_var_ranges;112for (i = 0; i < max; i++)113mtrr_usage_table[i] = 1;114}115116struct set_mtrr_data {117unsigned long smp_base;118unsigned long smp_size;119unsigned int smp_reg;120mtrr_type smp_type;121};122123/**124* mtrr_rendezvous_handler - Work done in the synchronization handler. Executed125* by all the CPUs.126* @info: pointer to mtrr configuration data127*128* Returns nothing.129*/130static int mtrr_rendezvous_handler(void *info)131{132struct set_mtrr_data *data = info;133134mtrr_if->set(data->smp_reg, data->smp_base,135data->smp_size, data->smp_type);136return 0;137}138139static inline int types_compatible(mtrr_type type1, mtrr_type type2)140{141return type1 == MTRR_TYPE_UNCACHABLE ||142type2 == MTRR_TYPE_UNCACHABLE ||143(type1 == MTRR_TYPE_WRTHROUGH && type2 == MTRR_TYPE_WRBACK) ||144(type1 == MTRR_TYPE_WRBACK && type2 == MTRR_TYPE_WRTHROUGH);145}146147/**148* set_mtrr - update mtrrs on all processors149* @reg: mtrr in question150* @base: mtrr base151* @size: mtrr size152* @type: mtrr type153*154* This is kinda tricky, but fortunately, Intel spelled it out for us cleanly:155*156* 1. Queue work to do the following on all processors:157* 2. Disable Interrupts158* 3. Wait for all procs to do so159* 4. Enter no-fill cache mode160* 5. Flush caches161* 6. Clear PGE bit162* 7. Flush all TLBs163* 8. Disable all range registers164* 9. Update the MTRRs165* 10. Enable all range registers166* 11. Flush all TLBs and caches again167* 12. Enter normal cache mode and reenable caching168* 13. Set PGE169* 14. Wait for buddies to catch up170* 15. Enable interrupts.171*172* What does that mean for us? Well, stop_machine() will ensure that173* the rendezvous handler is started on each CPU. And in lockstep they174* do the state transition of disabling interrupts, updating MTRR's175* (the CPU vendors may each do it differently, so we call mtrr_if->set()176* callback and let them take care of it.) and enabling interrupts.177*178* Note that the mechanism is the same for UP systems, too; all the SMP stuff179* becomes nops.180*/181static void set_mtrr(unsigned int reg, unsigned long base, unsigned long size,182mtrr_type type)183{184struct set_mtrr_data data = { .smp_reg = reg,185.smp_base = base,186.smp_size = size,187.smp_type = type188};189190stop_machine_cpuslocked(mtrr_rendezvous_handler, &data, cpu_online_mask);191192generic_rebuild_map();193}194195/**196* mtrr_add_page - Add a memory type region197* @base: Physical base address of region in pages (in units of 4 kB!)198* @size: Physical size of region in pages (4 kB)199* @type: Type of MTRR desired200* @increment: If this is true do usage counting on the region201*202* Memory type region registers control the caching on newer Intel and203* non Intel processors. This function allows drivers to request an204* MTRR is added. The details and hardware specifics of each processor's205* implementation are hidden from the caller, but nevertheless the206* caller should expect to need to provide a power of two size on an207* equivalent power of two boundary.208*209* If the region cannot be added either because all regions are in use210* or the CPU cannot support it a negative value is returned. On success211* the register number for this entry is returned, but should be treated212* as a cookie only.213*214* On a multiprocessor machine the changes are made to all processors.215* This is required on x86 by the Intel processors.216*217* The available types are218*219* %MTRR_TYPE_UNCACHABLE - No caching220*221* %MTRR_TYPE_WRBACK - Write data back in bursts whenever222*223* %MTRR_TYPE_WRCOMB - Write data back soon but allow bursts224*225* %MTRR_TYPE_WRTHROUGH - Cache reads but not writes226*227* BUGS: Needs a quiet flag for the cases where drivers do not mind228* failures and do not wish system log messages to be sent.229*/230int mtrr_add_page(unsigned long base, unsigned long size,231unsigned int type, bool increment)232{233unsigned long lbase, lsize;234int i, replace, error;235mtrr_type ltype;236237if (!mtrr_enabled())238return -ENXIO;239240error = mtrr_if->validate_add_page(base, size, type);241if (error)242return error;243244if (type >= MTRR_NUM_TYPES) {245pr_warn("type: %u invalid\n", type);246return -EINVAL;247}248249/* If the type is WC, check that this processor supports it */250if ((type == MTRR_TYPE_WRCOMB) && !have_wrcomb()) {251pr_warn("your processor doesn't support write-combining\n");252return -ENOSYS;253}254255if (!size) {256pr_warn("zero sized request\n");257return -EINVAL;258}259260if ((base | (base + size - 1)) >>261(boot_cpu_data.x86_phys_bits - PAGE_SHIFT)) {262pr_warn("base or size exceeds the MTRR width\n");263return -EINVAL;264}265266error = -EINVAL;267replace = -1;268269/* No CPU hotplug when we change MTRR entries */270cpus_read_lock();271272/* Search for existing MTRR */273mutex_lock(&mtrr_mutex);274for (i = 0; i < num_var_ranges; ++i) {275mtrr_if->get(i, &lbase, &lsize, <ype);276if (!lsize || base > lbase + lsize - 1 ||277base + size - 1 < lbase)278continue;279/*280* At this point we know there is some kind of281* overlap/enclosure282*/283if (base < lbase || base + size - 1 > lbase + lsize - 1) {284if (base <= lbase &&285base + size - 1 >= lbase + lsize - 1) {286/* New region encloses an existing region */287if (type == ltype) {288replace = replace == -1 ? i : -2;289continue;290} else if (types_compatible(type, ltype))291continue;292}293pr_warn("0x%lx000,0x%lx000 overlaps existing 0x%lx000,0x%lx000\n", base, size, lbase,294lsize);295goto out;296}297/* New region is enclosed by an existing region */298if (ltype != type) {299if (types_compatible(type, ltype))300continue;301pr_warn("type mismatch for %lx000,%lx000 old: %s new: %s\n",302base, size, mtrr_attrib_to_str(ltype),303mtrr_attrib_to_str(type));304goto out;305}306if (increment)307++mtrr_usage_table[i];308error = i;309goto out;310}311/* Search for an empty MTRR */312i = mtrr_if->get_free_region(base, size, replace);313if (i >= 0) {314set_mtrr(i, base, size, type);315if (likely(replace < 0)) {316mtrr_usage_table[i] = 1;317} else {318mtrr_usage_table[i] = mtrr_usage_table[replace];319if (increment)320mtrr_usage_table[i]++;321if (unlikely(replace != i)) {322set_mtrr(replace, 0, 0, 0);323mtrr_usage_table[replace] = 0;324}325}326} else {327pr_info("no more MTRRs available\n");328}329error = i;330out:331mutex_unlock(&mtrr_mutex);332cpus_read_unlock();333return error;334}335336static int mtrr_check(unsigned long base, unsigned long size)337{338if ((base & (PAGE_SIZE - 1)) || (size & (PAGE_SIZE - 1))) {339pr_warn("size and base must be multiples of 4 kiB\n");340Dprintk("size: 0x%lx base: 0x%lx\n", size, base);341dump_stack();342return -1;343}344return 0;345}346347/**348* mtrr_add - Add a memory type region349* @base: Physical base address of region350* @size: Physical size of region351* @type: Type of MTRR desired352* @increment: If this is true do usage counting on the region353*354* Memory type region registers control the caching on newer Intel and355* non Intel processors. This function allows drivers to request an356* MTRR is added. The details and hardware specifics of each processor's357* implementation are hidden from the caller, but nevertheless the358* caller should expect to need to provide a power of two size on an359* equivalent power of two boundary.360*361* If the region cannot be added either because all regions are in use362* or the CPU cannot support it a negative value is returned. On success363* the register number for this entry is returned, but should be treated364* as a cookie only.365*366* On a multiprocessor machine the changes are made to all processors.367* This is required on x86 by the Intel processors.368*369* The available types are370*371* %MTRR_TYPE_UNCACHABLE - No caching372*373* %MTRR_TYPE_WRBACK - Write data back in bursts whenever374*375* %MTRR_TYPE_WRCOMB - Write data back soon but allow bursts376*377* %MTRR_TYPE_WRTHROUGH - Cache reads but not writes378*379* BUGS: Needs a quiet flag for the cases where drivers do not mind380* failures and do not wish system log messages to be sent.381*/382int mtrr_add(unsigned long base, unsigned long size, unsigned int type,383bool increment)384{385if (!mtrr_enabled())386return -ENODEV;387if (mtrr_check(base, size))388return -EINVAL;389return mtrr_add_page(base >> PAGE_SHIFT, size >> PAGE_SHIFT, type,390increment);391}392393/**394* mtrr_del_page - delete a memory type region395* @reg: Register returned by mtrr_add396* @base: Physical base address397* @size: Size of region398*399* If register is supplied then base and size are ignored. This is400* how drivers should call it.401*402* Releases an MTRR region. If the usage count drops to zero the403* register is freed and the region returns to default state.404* On success the register is returned, on failure a negative error405* code.406*/407int mtrr_del_page(int reg, unsigned long base, unsigned long size)408{409int i, max;410mtrr_type ltype;411unsigned long lbase, lsize;412int error = -EINVAL;413414if (!mtrr_enabled())415return -ENODEV;416417max = num_var_ranges;418/* No CPU hotplug when we change MTRR entries */419cpus_read_lock();420mutex_lock(&mtrr_mutex);421if (reg < 0) {422/* Search for existing MTRR */423for (i = 0; i < max; ++i) {424mtrr_if->get(i, &lbase, &lsize, <ype);425if (lbase == base && lsize == size) {426reg = i;427break;428}429}430if (reg < 0) {431Dprintk("no MTRR for %lx000,%lx000 found\n", base, size);432goto out;433}434}435if (reg >= max) {436pr_warn("register: %d too big\n", reg);437goto out;438}439mtrr_if->get(reg, &lbase, &lsize, <ype);440if (lsize < 1) {441pr_warn("MTRR %d not used\n", reg);442goto out;443}444if (mtrr_usage_table[reg] < 1) {445pr_warn("reg: %d has count=0\n", reg);446goto out;447}448if (--mtrr_usage_table[reg] < 1)449set_mtrr(reg, 0, 0, 0);450error = reg;451out:452mutex_unlock(&mtrr_mutex);453cpus_read_unlock();454return error;455}456457/**458* mtrr_del - delete a memory type region459* @reg: Register returned by mtrr_add460* @base: Physical base address461* @size: Size of region462*463* If register is supplied then base and size are ignored. This is464* how drivers should call it.465*466* Releases an MTRR region. If the usage count drops to zero the467* register is freed and the region returns to default state.468* On success the register is returned, on failure a negative error469* code.470*/471int mtrr_del(int reg, unsigned long base, unsigned long size)472{473if (!mtrr_enabled())474return -ENODEV;475if (mtrr_check(base, size))476return -EINVAL;477return mtrr_del_page(reg, base >> PAGE_SHIFT, size >> PAGE_SHIFT);478}479480/**481* arch_phys_wc_add - add a WC MTRR and handle errors if PAT is unavailable482* @base: Physical base address483* @size: Size of region484*485* If PAT is available, this does nothing. If PAT is unavailable, it486* attempts to add a WC MTRR covering size bytes starting at base and487* logs an error if this fails.488*489* The called should provide a power of two size on an equivalent490* power of two boundary.491*492* Drivers must store the return value to pass to mtrr_del_wc_if_needed,493* but drivers should not try to interpret that return value.494*/495int arch_phys_wc_add(unsigned long base, unsigned long size)496{497int ret;498499if (pat_enabled() || !mtrr_enabled())500return 0; /* Success! (We don't need to do anything.) */501502ret = mtrr_add(base, size, MTRR_TYPE_WRCOMB, true);503if (ret < 0) {504pr_warn("Failed to add WC MTRR for [%p-%p]; performance may suffer.",505(void *)base, (void *)(base + size - 1));506return ret;507}508return ret + MTRR_TO_PHYS_WC_OFFSET;509}510EXPORT_SYMBOL(arch_phys_wc_add);511512/*513* arch_phys_wc_del - undoes arch_phys_wc_add514* @handle: Return value from arch_phys_wc_add515*516* This cleans up after mtrr_add_wc_if_needed.517*518* The API guarantees that mtrr_del_wc_if_needed(error code) and519* mtrr_del_wc_if_needed(0) do nothing.520*/521void arch_phys_wc_del(int handle)522{523if (handle >= 1) {524WARN_ON(handle < MTRR_TO_PHYS_WC_OFFSET);525mtrr_del(handle - MTRR_TO_PHYS_WC_OFFSET, 0, 0);526}527}528EXPORT_SYMBOL(arch_phys_wc_del);529530/*531* arch_phys_wc_index - translates arch_phys_wc_add's return value532* @handle: Return value from arch_phys_wc_add533*534* This will turn the return value from arch_phys_wc_add into an mtrr535* index suitable for debugging.536*537* Note: There is no legitimate use for this function, except possibly538* in printk line. Alas there is an illegitimate use in some ancient539* drm ioctls.540*/541int arch_phys_wc_index(int handle)542{543if (handle < MTRR_TO_PHYS_WC_OFFSET)544return -1;545else546return handle - MTRR_TO_PHYS_WC_OFFSET;547}548EXPORT_SYMBOL_GPL(arch_phys_wc_index);549550int __initdata changed_by_mtrr_cleanup;551552/**553* mtrr_bp_init - initialize MTRRs on the boot CPU554*555* This needs to be called early; before any of the other CPUs are556* initialized (i.e. before smp_init()).557*/558void __init mtrr_bp_init(void)559{560bool generic_mtrrs = cpu_feature_enabled(X86_FEATURE_MTRR);561const char *why = "(not available)";562unsigned long config, dummy;563564phys_hi_rsvd = GENMASK(31, boot_cpu_data.x86_phys_bits - 32);565566if (!generic_mtrrs && mtrr_state.enabled) {567/*568* Software overwrite of MTRR state, only for generic case.569* Note that X86_FEATURE_MTRR has been reset in this case.570*/571init_table();572mtrr_build_map();573pr_info("MTRRs set to read-only\n");574575return;576}577578if (generic_mtrrs)579mtrr_if = &generic_mtrr_ops;580else581mtrr_set_if();582583if (mtrr_enabled()) {584/* Get the number of variable MTRR ranges. */585if (mtrr_if == &generic_mtrr_ops)586rdmsr(MSR_MTRRcap, config, dummy);587else588config = mtrr_if->var_regs;589num_var_ranges = config & MTRR_CAP_VCNT;590591init_table();592if (mtrr_if == &generic_mtrr_ops) {593/* BIOS may override */594if (get_mtrr_state()) {595memory_caching_control |= CACHE_MTRR;596changed_by_mtrr_cleanup = mtrr_cleanup();597mtrr_build_map();598} else {599mtrr_if = NULL;600why = "by BIOS";601}602}603}604605if (!mtrr_enabled())606pr_info("MTRRs disabled %s\n", why);607}608609/**610* mtrr_save_state - Save current fixed-range MTRR state of the first611* cpu in cpu_online_mask.612*/613void mtrr_save_state(void)614{615int first_cpu;616617if (!mtrr_enabled() || !mtrr_state.have_fixed)618return;619620first_cpu = cpumask_first(cpu_online_mask);621smp_call_function_single(first_cpu, mtrr_save_fixed_ranges, NULL, 1);622}623624static int __init mtrr_init_finalize(void)625{626/*627* Map might exist if guest_force_mtrr_state() has been called or if628* mtrr_enabled() returns true.629*/630mtrr_copy_map();631632if (!mtrr_enabled())633return 0;634635if (memory_caching_control & CACHE_MTRR) {636if (!changed_by_mtrr_cleanup)637mtrr_state_warn();638return 0;639}640641mtrr_register_syscore();642643return 0;644}645subsys_initcall(mtrr_init_finalize);646647648