aboutsummaryrefslogtreecommitdiffstats
path: root/testhal/STM32/STM32F3xx/USB_CDC/mcuconf.h
blob: 0bcab46c8c75d9c5db82cb4d44d96ede81cca0ec (plain)
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
39
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
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
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
/*
    ChibiOS - Copyright (C) 2006..2016 Giovanni Di Sirio

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#ifndef MCUCONF_H
#define MCUCONF_H

/*
 * STM32F3xx drivers configuration.
 * The following settings override the default settings present in
 * the various device driver implementation headers.
 * Note that the settings for each driver only have effect if the whole
 * driver is enabled in halconf.h.
 *
 * IRQ priorities:
 * 15...0       Lowest...Highest.
 *
 * DMA priorities:
 * 0...3        Lowest...Highest.
 */

#define STM32F3xx_MCUCONF

/*
 * HAL driver system settings.
 */
#define STM32_NO_INIT                       FALSE
#define STM32_PVD_ENABLE                    FALSE
#define STM32_PLS                           STM32_PLS_LEV0
#define STM32_HSI_ENABLED                   TRUE
#define STM32_LSI_ENABLED                   TRUE
#define STM32_HSE_ENABLED                   TRUE
#define STM32_LSE_ENABLED                   FALSE
#define STM32_SW                            STM32_SW_PLL
#define STM32_PLLSRC                        STM32_PLLSRC_HSE
#define STM32_PREDIV_VALUE                  1
#define STM32_PLLMUL_VALUE                  9
#define STM32_HPRE                          STM32_HPRE_DIV1
#define STM32_PPRE1                         STM32_PPRE1_DIV2
#define STM32_PPRE2                         STM32_PPRE2_DIV2
#define STM32_MCOSEL                        STM32_MCOSEL_NOCLOCK
#define STM32_ADC12PRES                     STM32_ADC12PRES_DIV1
#define STM32_ADC34PRES                     STM32_ADC34PRES_DIV1
#define STM32_USART1SW                      STM32_USART1SW_PCLK
#define STM32_USART2SW                      STM32_USART2SW_PCLK
#define STM32_USART3SW                      STM32_USART3SW_PCLK
#define STM32_UART4SW                       STM32_UART4SW_PCLK
#define STM32_UART5SW                       STM32_UART5SW_PCLK
#define STM32_I2C1SW                        STM32_I2C1SW_SYSCLK
#define STM32_I2C2SW                        STM32_I2C2SW_SYSCLK
#define STM32_TIM1SW                        STM32_TIM1SW_PCLK2
#define STM32_TIM8SW                        STM32_TIM8SW_PCLK2
#define STM32_RTCSEL                        STM32_RTCSEL_LSI
#define STM32_USB_CLOCK_REQUIRED            TRUE
#define STM32_USBPRE                        STM32_USBPRE_DIV1P5

/*
 * ADC driver system settings.
 */
#define STM32_ADC_DUAL_MODE                 FALSE
#define STM32_ADC_COMPACT_SAMPLES           FALSE
#define STM32_ADC_USE_ADC1                  FALSE
#define STM32_ADC_USE_ADC2                  FALSE
#define STM32_ADC_USE_ADC3                  FALSE
#define STM32_ADC_USE_ADC4                  FALSE
#define STM32_ADC_ADC1_DMA_STREAM           STM32_DMA_STREAM_ID(1, 1)
#define STM32_ADC_ADC2_DMA_STREAM           STM32_DMA_STREAM_ID(2, 1)
#define STM32_ADC_ADC3_DMA_STREAM           STM32_DMA_STREAM_ID(2, 5)
#define STM32_ADC_ADC4_DMA_STREAM           STM32_DMA_STREAM_ID(2, 2)
#define STM32_ADC_ADC1_DMA_PRIORITY         2
#define STM32_ADC_ADC2_DMA_PRIORITY         2
#define STM32_ADC_ADC3_DMA_PRIORITY         2
#define STM32_ADC_ADC4_DMA_PRIORITY         2
#define STM32_ADC_ADC12_IRQ_PRIORITY        5
#define STM32_ADC_ADC3_IRQ_PRIORITY         5
#define STM32_ADC_ADC4_IRQ_PRIORITY         5
#define STM32_ADC_ADC1_DMA_IRQ_PRIORITY     5
#define STM32_ADC_ADC2_DMA_IRQ_PRIORITY     5
#define STM32_ADC_ADC3_DMA_IRQ_PRIORITY     5
#define STM32_ADC_ADC4_DMA_IRQ_PRIORITY     5
#define STM32_ADC_ADC12_CLOCK_MODE          ADC_CCR_CKMODE_AHB_DIV1
#define STM32_ADC_ADC34_CLOCK_MODE          ADC_CCR_CKMODE_AHB_DIV1

/*
 * CAN driver system settings.
 */
#define STM32_CAN_USE_CAN1                  FALSE
#define STM32_CAN_CAN1_IRQ_PRIORITY         11

/*
 * DAC driver system settings.
 */
#define STM32_DAC_DUAL_MODE                 FALSE
#define STM32_DAC_USE_DAC1_CH1              TRUE
#define STM32_DAC_USE_DAC1_CH2              TRUE
#define STM32_DAC_DAC1_CH1_IRQ_PRIORITY     10
#define STM32_DAC_DAC1_CH2_IRQ_PRIORITY     10
#define STM32_DAC_DAC1_CH1_DMA_PRIORITY     2
#define STM32_DAC_DAC1_CH2_DMA_PRIORITY     2

/*
 * EXT driver system settings.
 */
#define STM32_EXT_EXTI0_IRQ_PRIORITY        6
#define STM32_EXT_EXTI1_IRQ_PRIORITY        6
#define STM32_EXT_EXTI2_IRQ_PRIORITY        6
#define STM32_EXT_EXTI3_IRQ_PRIORITY        6
#define STM32_EXT_EXTI4_IRQ_PRIORITY        6
#define STM32_EXT_EXTI5_9_IRQ_PRIORITY      6
#define STM32_EXT_EXTI10_15_IRQ_PRIORITY    6
#define STM32_EXT_EXTI16_IRQ_PRIORITY       6
#define STM32_EXT_EXTI17_IRQ_PRIORITY       6
#define STM32_EXT_EXTI18_IRQ_PRIORITY       6
#define STM32_EXT_EXTI19_IRQ_PRIORITY       6
#define STM32_EXT_EXTI20_IRQ_PRIORITY       6
#define STM32_EXT_EXTI21_22_29_IRQ_PRIORITY 6
#define STM32_EXT_EXTI30_32_IRQ_PRIORITY    6
#define STM32_EXT_EXTI33_IRQ_PRIORITY       6

/*
 * GPT driver system settings.
 */
#define STM32_GPT_USE_TIM1                  FALSE
#define STM32_GPT_USE_TIM2                  FALSE
#define STM32_GPT_USE_TIM3                  FALSE
#define STM32_GPT_USE_TIM4                  FALSE
#define STM32_GPT_USE_TIM6                  FALSE
#define STM32_GPT_USE_TIM7                  FALSE
#define STM32_GPT_USE_TIM8                  FALSE
#define STM32_GPT_TIM1_IRQ_PRIORITY         7
#define STM32_GPT_TIM2_IRQ_PRIORITY         7
#define STM32_GPT_TIM3_IRQ_PRIORITY         7
#define STM32_GPT_TIM4_IRQ_PRIORITY         7
#define STM32_GPT_TIM6_IRQ_PRIORITY         7
#define STM32_GPT_TIM7_IRQ_PRIORITY         7
#define STM32_GPT_TIM8_IRQ_PRIORITY         7

/*
 * I2C driver system settings.
 */
#define STM32_I2C_USE_I2C1                  FALSE
#define STM32_I2C_USE_I2C2                  FALSE
#define STM32_I2C_BUSY_TIMEOUT              50
#define STM32_I2C_I2C1_IRQ_PRIORITY         10
#define STM32_I2C_I2C2_IRQ_PRIORITY         10
#define STM32_I2C_USE_DMA                   TRUE
#define STM32_I2C_I2C1_DMA_PRIORITY         1
#define STM32_I2C_I2C2_DMA_PRIORITY         1
#define STM32_I2C_DMA_ERROR_HOOK(i2cp)      osalSysHalt("DMA failure")

/*
 * ICU driver system settings.
 */
#define STM32_ICU_USE_TIM1                  FALSE
#define STM32_ICU_USE_TIM2                  FALSE
#define STM32_ICU_USE_TIM3                  FALSE
#define STM32_ICU_USE_TIM4                  FALSE
#define STM32_ICU_USE_TIM8                  FALSE
#define STM32_ICU_TIM1_IRQ_PRIORITY         7
#define STM32_ICU_TIM2_IRQ_PRIORITY         7
#define STM32_ICU_TIM3_IRQ_PRIORITY         7
#define STM32_ICU_TIM4_IRQ_PRIORITY         7
#define STM32_ICU_TIM8_IRQ_PRIORITY         7

/*
 * PWM driver system settings.
 */
#define STM32_PWM_USE_ADVANCED              FALSE
#define STM32_PWM_USE_TIM1                  FALSE
#define STM32_PWM_USE_TIM2                  FALSE
#define STM32_PWM_USE_TIM3                  FALSE
#define STM32_PWM_USE_TIM4                  FALSE
#define STM32_PWM_USE_TIM8                  FALSE
#define STM32_PWM_TIM1_IRQ_PRIORITY         7
#define STM32_PWM_TIM2_IRQ_PRIORITY         7
#define STM32_PWM_TIM3_IRQ_PRIORITY         7
#define STM32_PWM_TIM4_IRQ_PRIORITY         7
#define STM32_PWM_TIM8_IRQ_PRIORITY         7

/*
 * SERIAL driver system settings.
 */
#define STM32_SERIAL_USE_USART1             FALSE
#define STM32_SERIAL_USE_USART2             FALSE
#define STM32_SERIAL_USE_USART3             FALSE
#define STM32_SERIAL_USE_UART4              FALSE
#define STM32_SERIAL_USE_UART5              FALSE
#define STM32_SERIAL_USART1_PRIORITY        12
#define STM32_SERIAL_USART2_PRIORITY        12
#define STM32_SERIAL_USART3_PRIORITY        12
#define STM32_SERIAL_UART4_PRIORITY         12
#define STM32_SERIAL_UART5_PRIORITY         12

/*
 * SPI driver system settings.
 */
#define STM32_SPI_USE_SPI1                  FALSE
#define STM32_SPI_USE_SPI2                  FALSE
#define STM32_SPI_USE_SPI3                  FALSE
#define STM32_SPI_SPI1_DMA_PRIORITY         1
#define STM32_SPI_SPI2_DMA_PRIORITY         1
#define STM32_SPI_SPI3_DMA_PRIORITY         1
#define STM32_SPI_SPI1_IRQ_PRIORITY         10
#define STM32_SPI_SPI2_IRQ_PRIORITY         10
#define STM32_SPI_SPI3_IRQ_PRIORITY         10
#define STM32_SPI_DMA_ERROR_HOOK(spip)      osalSysHalt("DMA failure")

/*
 * ST driver system settings.
 */
#define STM32_ST_IRQ_PRIORITY               8
#define STM32_ST_USE_TIMER                  2

/*
 * UART driver system settings.
 */
#define STM32_UART_USE_USART1               FALSE
#define STM32_UART_USE_USART2               FALSE
#define STM32_UART_USE_USART3               FALSE
#define STM32_UART_USART1_IRQ_PRIORITY      12
#define STM32_UART_USART2_IRQ_PRIORITY      12
#define STM32_UART_USART3_IRQ_PRIORITY      12
#define STM32_UART_USART1_DMA_PRIORITY      0
#define STM32_UART_USART2_DMA_PRIORITY      0
#define STM32_UART_USART3_DMA_PRIORITY      0
#define STM32_UART_DMA_ERROR_HOOK(uartp)    osalSysHalt("DMA failure")

/*
 * USB driver system settings.
 */
#define STM32_USB_USE_USB1                  TRUE
#define STM32_USB_LOW_POWER_ON_SUSPEND      FALSE
#define STM32_USB_USB1_HP_IRQ_PRIORITY      13
#define STM32_USB_USB1_LP_IRQ_PRIORITY      14

/*
 * WDG driver system settings.
 */
#define STM32_WDG_USE_IWDG                  FALSE

#endif /* MCUCONF_H */
ackground-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/*
 * mtrr.c: MTRR/PAT virtualization
 *
 * Copyright (c) 2007, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU General Public License,
 * version 2, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place - Suite 330, Boston, MA 02111-1307 USA.
 */

#include <public/hvm/e820.h>
#include <xen/types.h>
#include <asm/e820.h>
#include <asm/paging.h>
#include <asm/p2m.h>
#include <xen/domain_page.h>
#include <asm/mtrr.h>
#include <asm/hvm/support.h>
#include <asm/hvm/cacheattr.h>

extern struct mtrr_state mtrr_state;

static uint64_t phys_base_msr_mask;
static uint64_t phys_mask_msr_mask;
static uint32_t size_or_mask;
static uint32_t size_and_mask;

/* Get page attribute fields (PAn) from PAT MSR. */
#define pat_cr_2_paf(pat_cr,n)  ((((uint64_t)pat_cr) >> ((n)<<3)) & 0xff)

/* PAT entry to PTE flags (PAT, PCD, PWT bits). */
static uint8_t pat_entry_2_pte_flags[8] = {
    0,           _PAGE_PWT,
    _PAGE_PCD,   _PAGE_PCD | _PAGE_PWT,
    _PAGE_PAT,   _PAGE_PAT | _PAGE_PWT,
    _PAGE_PAT | _PAGE_PCD, _PAGE_PAT | _PAGE_PCD | _PAGE_PWT };

/* Effective mm type lookup table, according to MTRR and PAT. */
static uint8_t mm_type_tbl[MTRR_NUM_TYPES][PAT_TYPE_NUMS] = {
/********PAT(UC,WC,RS,RS,WT,WP,WB,UC-)*/
/* RS means reserved type(2,3), and type is hardcoded here */
 /*MTRR(UC):(UC,WC,RS,RS,UC,UC,UC,UC)*/
            {0, 1, 2, 2, 0, 0, 0, 0},
 /*MTRR(WC):(UC,WC,RS,RS,UC,UC,WC,WC)*/
            {0, 1, 2, 2, 0, 0, 1, 1},
 /*MTRR(RS):(RS,RS,RS,RS,RS,RS,RS,RS)*/
            {2, 2, 2, 2, 2, 2, 2, 2},
 /*MTRR(RS):(RS,RS,RS,RS,RS,RS,RS,RS)*/
            {2, 2, 2, 2, 2, 2, 2, 2},
 /*MTRR(WT):(UC,WC,RS,RS,WT,WP,WT,UC)*/
            {0, 1, 2, 2, 4, 5, 4, 0},
 /*MTRR(WP):(UC,WC,RS,RS,WT,WP,WP,WC)*/
            {0, 1, 2, 2, 4, 5, 5, 1},
 /*MTRR(WB):(UC,WC,RS,RS,WT,WP,WB,UC)*/
            {0, 1, 2, 2, 4, 5, 6, 0}
};

/*
 * Reverse lookup table, to find a pat type according to MTRR and effective
 * memory type. This table is dynamically generated.
 */
static uint8_t mtrr_epat_tbl[MTRR_NUM_TYPES][MEMORY_NUM_TYPES];

/* Lookup table for PAT entry of a given PAT value in host PAT. */
static uint8_t pat_entry_tbl[PAT_TYPE_NUMS];

static void get_mtrr_range(uint64_t base_msr, uint64_t mask_msr,
                           uint64_t *base, uint64_t *end)
{
    uint32_t mask_lo = (uint32_t)mask_msr;
    uint32_t mask_hi = (uint32_t)(mask_msr >> 32);
    uint32_t base_lo = (uint32_t)base_msr;
    uint32_t base_hi = (uint32_t)(base_msr >> 32);
    uint32_t size;

    if ( (mask_lo & 0x800) == 0 )
    {
        /* Invalid (i.e. free) range */
        *base = 0;
        *end = 0;
        return;
    }

    /* Work out the shifted address mask. */
    mask_lo = (size_or_mask | (mask_hi << (32 - PAGE_SHIFT)) |
               (mask_lo >> PAGE_SHIFT));

    /* This works correctly if size is a power of two (a contiguous range). */
    size = -mask_lo;
    *base = base_hi << (32 - PAGE_SHIFT) | base_lo >> PAGE_SHIFT;
    *end = *base + size - 1;
}

bool_t is_var_mtrr_overlapped(struct mtrr_state *m)
{
    int32_t seg, i;
    uint64_t phys_base, phys_mask, phys_base_pre, phys_mask_pre;
    uint64_t base_pre, end_pre, base, end;
    uint8_t num_var_ranges = (uint8_t)m->mtrr_cap;

    for ( i = 0; i < num_var_ranges; i++ )
    {
        phys_base_pre = ((uint64_t*)m->var_ranges)[i*2];
        phys_mask_pre = ((uint64_t*)m->var_ranges)[i*2 + 1];

        get_mtrr_range(phys_base_pre, phys_mask_pre,
                        &base_pre, &end_pre);

        for ( seg = i + 1; seg < num_var_ranges; seg ++ )
        {
            phys_base = ((uint64_t*)m->var_ranges)[seg*2];
            phys_mask = ((uint64_t*)m->var_ranges)[seg*2 + 1];

            get_mtrr_range(phys_base, phys_mask,
                            &base, &end);

            if ( ((base_pre != end_pre) && (base != end))
                 || ((base >= base_pre) && (base <= end_pre))
                 || ((end >= base_pre) && (end <= end_pre))
                 || ((base_pre >= base) && (base_pre <= end))
                 || ((end_pre >= base) && (end_pre <= end)) )
            {
                /* MTRR is overlapped. */
                return 1;
            }
        }
    }
    return 0;
}

#define MTRR_PHYSMASK_VALID_BIT  11
#define MTRR_PHYSMASK_SHIFT      12

#define MTRR_PHYSBASE_TYPE_MASK  0xff   /* lowest 8 bits */
#define MTRR_PHYSBASE_SHIFT      12
#define MTRR_VCNT                8

#define MTRRphysBase_MSR(reg) (0x200 + 2 * (reg))
#define MTRRphysMask_MSR(reg) (0x200 + 2 * (reg) + 1)
bool_t mtrr_var_range_msr_set(struct mtrr_state *m, uint32_t msr,
                              uint64_t msr_content);
bool_t mtrr_fix_range_msr_set(struct mtrr_state *m, uint32_t row,
                              uint64_t msr_content);

static int hvm_mtrr_pat_init(void)
{
    extern uint64_t host_pat;
    unsigned int i, j, phys_addr;

    memset(&mtrr_epat_tbl, INVALID_MEM_TYPE, sizeof(mtrr_epat_tbl));
    for ( i = 0; i < MTRR_NUM_TYPES; i++ )
    {
        for ( j = 0; j < PAT_TYPE_NUMS; j++ )
        {
            int32_t tmp = mm_type_tbl[i][j];
            if ( (tmp >= 0) && (tmp < MEMORY_NUM_TYPES) )
                mtrr_epat_tbl[i][tmp] = j;
        }
    }

    memset(&pat_entry_tbl, INVALID_MEM_TYPE,
           PAT_TYPE_NUMS * sizeof(pat_entry_tbl[0]));
    for ( i = 0; i < PAT_TYPE_NUMS; i++ )
    {
        for ( j = 0; j < PAT_TYPE_NUMS; j++ )
        {
            if ( pat_cr_2_paf(host_pat, j) == i )
            {
                pat_entry_tbl[i] = j;
                break;
            }
        }
    }

    phys_addr = 36;
    if ( cpuid_eax(0x80000000) >= 0x80000008 )
        phys_addr = (uint8_t)cpuid_eax(0x80000008);

    phys_base_msr_mask = ~((((uint64_t)1) << phys_addr) - 1) | 0xf00UL;
    phys_mask_msr_mask = ~((((uint64_t)1) << phys_addr) - 1) | 0x7ffUL;

    size_or_mask = ~((1 << (phys_addr - PAGE_SHIFT)) - 1);
    size_and_mask = ~size_or_mask & 0xfff00000;

    return 0;
}
__initcall(hvm_mtrr_pat_init);

uint8_t pat_type_2_pte_flags(uint8_t pat_type)
{
    int32_t pat_entry = pat_entry_tbl[pat_type];

    /* INVALID_MEM_TYPE, means doesn't find the pat_entry in host pat for
     * a given pat_type. If host pat covers all the pat types,
     * it can't happen.
     */
    if ( likely(pat_entry != INVALID_MEM_TYPE) )
        return pat_entry_2_pte_flags[pat_entry];

    return pat_entry_2_pte_flags[pat_entry_tbl[PAT_TYPE_UNCACHABLE]];
}

int hvm_vcpu_cacheattr_init(struct vcpu *v)
{
    struct mtrr_state *m = &v->arch.hvm_vcpu.mtrr;

    memset(m, 0, sizeof(*m));

    m->var_ranges = xmalloc_array(struct mtrr_var_range, MTRR_VCNT);
    if ( m->var_ranges == NULL )
        return -ENOMEM;
    memset(m->var_ranges, 0, MTRR_VCNT * sizeof(struct mtrr_var_range));

    m->mtrr_cap = (1u << 10) | (1u << 8) | MTRR_VCNT;

    v->arch.hvm_vcpu.pat_cr =
        ((uint64_t)PAT_TYPE_WRBACK) |               /* PAT0: WB */
        ((uint64_t)PAT_TYPE_WRTHROUGH << 8) |       /* PAT1: WT */
        ((uint64_t)PAT_TYPE_UC_MINUS << 16) |       /* PAT2: UC- */
        ((uint64_t)PAT_TYPE_UNCACHABLE << 24) |     /* PAT3: UC */
        ((uint64_t)PAT_TYPE_WRBACK << 32) |         /* PAT4: WB */
        ((uint64_t)PAT_TYPE_WRTHROUGH << 40) |      /* PAT5: WT */
        ((uint64_t)PAT_TYPE_UC_MINUS << 48) |       /* PAT6: UC- */
        ((uint64_t)PAT_TYPE_UNCACHABLE << 56);      /* PAT7: UC */

    return 0;
}

void hvm_vcpu_cacheattr_destroy(struct vcpu *v)
{
    xfree(v->arch.hvm_vcpu.mtrr.var_ranges);
}

/*
 * Get MTRR memory type for physical address pa.
 */
static uint8_t get_mtrr_type(struct mtrr_state *m, paddr_t pa)
{
   int32_t     addr, seg, index;
   uint8_t     overlap_mtrr = 0;
   uint8_t     overlap_mtrr_pos = 0;
   uint64_t    phys_base;
   uint64_t    phys_mask;
   uint8_t     num_var_ranges = m->mtrr_cap & 0xff;

   if ( unlikely(!(m->enabled & 0x2)) )
       return MTRR_TYPE_UNCACHABLE;

   if ( (pa < 0x100000) && (m->enabled & 1) )
   {
       /* Fixed range MTRR takes effective */
       addr = (uint32_t) pa;
       if ( addr < 0x80000 )
       {
           seg = (addr >> 16);
           return m->fixed_ranges[seg];
       }
       else if ( addr < 0xc0000 )
       {
           seg = (addr - 0x80000) >> 14;
           index = (seg >> 3) + 1;
           seg &= 7;            /* select 0-7 segments */
           return m->fixed_ranges[index*8 + seg];
       }
       else
       {
           /* 0xC0000 --- 0x100000 */
           seg = (addr - 0xc0000) >> 12;
           index = (seg >> 3) + 3;
           seg &= 7;            /* select 0-7 segments */
           return m->fixed_ranges[index*8 + seg];
       }
   }

   /* Match with variable MTRRs. */
   for ( seg = 0; seg < num_var_ranges; seg++ )
   {
       phys_base = ((uint64_t*)m->var_ranges)[seg*2];
       phys_mask = ((uint64_t*)m->var_ranges)[seg*2 + 1];
       if ( phys_mask & (1 << MTRR_PHYSMASK_VALID_BIT) )
       {
           if ( ((uint64_t) pa & phys_mask) >> MTRR_PHYSMASK_SHIFT ==
                (phys_base & phys_mask) >> MTRR_PHYSMASK_SHIFT )
           {
               if ( unlikely(m->overlapped) )
               {
                    overlap_mtrr |= 1 << (phys_base & MTRR_PHYSBASE_TYPE_MASK);
                    overlap_mtrr_pos = phys_base & MTRR_PHYSBASE_TYPE_MASK;
               }
               else
               {
                   /* If no overlap, return the found one */
                   return (phys_base & MTRR_PHYSBASE_TYPE_MASK);
               }
           }
       }
   }

   /* Overlapped or not found. */
   if ( unlikely(overlap_mtrr == 0) )
       return m->def_type;

   if ( likely(!(overlap_mtrr & ~( ((uint8_t)1) << overlap_mtrr_pos ))) )
       /* Covers both one variable memory range matches and
        * two or more identical match.
        */
       return overlap_mtrr_pos;

   if ( overlap_mtrr & 0x1 )
       /* Two or more match, one is UC. */
       return MTRR_TYPE_UNCACHABLE;

   if ( !(overlap_mtrr & 0xaf) )
       /* Two or more match, WT and WB. */
       return MTRR_TYPE_WRTHROUGH;

   /* Behaviour is undefined, but return the last overlapped type. */
   return overlap_mtrr_pos;
}

/*
 * return the memory type from PAT.
 * NOTE: valid only when paging is enabled.
 *       Only 4K page PTE is supported now.
 */
static uint8_t page_pat_type(uint64_t pat_cr, uint32_t pte_flags)
{
    int32_t pat_entry;

    /* PCD/PWT -> bit 1/0 of PAT entry */
    pat_entry = ( pte_flags >> 3 ) & 0x3;
    /* PAT bits as bit 2 of PAT entry */
    if ( pte_flags & _PAGE_PAT )
        pat_entry |= 4;

    return (uint8_t)pat_cr_2_paf(pat_cr, pat_entry);
}

/*
 * Effective memory type for leaf page.
 */
static uint8_t effective_mm_type(struct mtrr_state *m,
                                 uint64_t pat,
                                 paddr_t gpa,
                                 uint32_t pte_flags)
{
    uint8_t mtrr_mtype, pat_value, effective;

    mtrr_mtype = get_mtrr_type(m, gpa);

    pat_value = page_pat_type(pat, pte_flags);

    effective = mm_type_tbl[mtrr_mtype][pat_value];

    return effective;
}

uint32_t get_pat_flags(struct vcpu *v,
                       uint32_t gl1e_flags,
                       paddr_t gpaddr,
                       paddr_t spaddr)
{
    uint8_t guest_eff_mm_type;
    uint8_t shadow_mtrr_type;
    uint8_t pat_entry_value;
    uint64_t pat = v->arch.hvm_vcpu.pat_cr;
    struct mtrr_state *g = &v->arch.hvm_vcpu.mtrr;

    /* 1. Get the effective memory type of guest physical address,
     * with the pair of guest MTRR and PAT
     */
    guest_eff_mm_type = effective_mm_type(g, pat, gpaddr, gl1e_flags);
    /* 2. Get the memory type of host physical address, with MTRR */
    shadow_mtrr_type = get_mtrr_type(&mtrr_state, spaddr);

    /* 3. Find the memory type in PAT, with host MTRR memory type
     * and guest effective memory type.
     */
    pat_entry_value = mtrr_epat_tbl[shadow_mtrr_type][guest_eff_mm_type];
    /* If conflit occurs(e.g host MTRR is UC, guest memory type is
     * WB),set UC as effective memory. Here, returning PAT_TYPE_UNCACHABLE will
     * always set effective memory as UC.
     */
    if ( pat_entry_value == INVALID_MEM_TYPE )
    {
        gdprintk(XENLOG_WARNING,
                 "Conflict occurs for a given guest l1e flags:%x "
                 "at %"PRIx64" (the effective mm type:%d), "
                 "because the host mtrr type is:%d\n",
                 gl1e_flags, (uint64_t)gpaddr, guest_eff_mm_type,
                 shadow_mtrr_type);
        pat_entry_value = PAT_TYPE_UNCACHABLE;
    }
    /* 4. Get the pte flags */
    return pat_type_2_pte_flags(pat_entry_value);
}

/* Helper funtions for seting mtrr/pat */
bool_t pat_msr_set(uint64_t *pat, uint64_t msr_content)
{
    uint8_t *value = (uint8_t*)&msr_content;
    int32_t i;

    if ( *pat != msr_content )
    {
        for ( i = 0; i < 8; i++ )
            if ( unlikely(!(value[i] == 0 || value[i] == 1 ||
                            value[i] == 4 || value[i] == 5 ||
                            value[i] == 6 || value[i] == 7)) )
                return 0;

        *pat = msr_content;
    }

    return 1;
}

bool_t mtrr_def_type_msr_set(struct mtrr_state *m, uint64_t msr_content)
{
    uint8_t def_type = msr_content & 0xff;
    uint8_t enabled = (msr_content >> 10) & 0x3;

    if ( unlikely(!(def_type == 0 || def_type == 1 || def_type == 4 ||
                    def_type == 5 || def_type == 6)) )
    {
         HVM_DBG_LOG(DBG_LEVEL_MSR, "invalid MTRR def type:%x\n", def_type);
         return 0;
    }

    if ( unlikely(msr_content && (msr_content & ~0xcffUL)) )
    {
         HVM_DBG_LOG(DBG_LEVEL_MSR, "invalid msr content:%"PRIx64"\n",
                     msr_content);
         return 0;
    }

    m->enabled = enabled;
    m->def_type = def_type;

    return 1;
}

bool_t mtrr_fix_range_msr_set(struct mtrr_state *m, uint32_t row,
                              uint64_t msr_content)
{
    uint64_t *fixed_range_base = (uint64_t *)m->fixed_ranges;

    if ( fixed_range_base[row] != msr_content )
    {
        uint8_t *range = (uint8_t*)&msr_content;
        int32_t i, type;

        for ( i = 0; i < 8; i++ )
        {
            type = range[i];
            if ( unlikely(!(type == 0 || type == 1 ||
                            type == 4 || type == 5 || type == 6)) )
                return 0;
        }

        fixed_range_base[row] = msr_content;
    }

    return 1;
}

bool_t mtrr_var_range_msr_set(struct mtrr_state *m, uint32_t msr,
                              uint64_t msr_content)
{
    uint32_t index;
    uint64_t msr_mask;
    uint64_t *var_range_base = (uint64_t*)m->var_ranges;

    index = msr - MSR_IA32_MTRR_PHYSBASE0;

    if ( var_range_base[index] != msr_content )
    {
        uint32_t type = msr_content & 0xff;

        msr_mask = (index & 1) ? phys_mask_msr_mask : phys_base_msr_mask;

        if ( unlikely(!(type == 0 || type == 1 ||
                        type == 4 || type == 5 || type == 6)) )
            return 0;

        if ( unlikely(msr_content && (msr_content & msr_mask)) )
        {
            HVM_DBG_LOG(DBG_LEVEL_MSR, "invalid msr content:%"PRIx64"\n",
                        msr_content);
            return 0;
        }

        var_range_base[index] = msr_content;
    }

    m->overlapped = is_var_mtrr_overlapped(m);

    return 1;
}

bool_t mtrr_pat_not_equal(struct vcpu *vd, struct vcpu *vs)
{
    struct mtrr_state *md = &vd->arch.hvm_vcpu.mtrr;
    struct mtrr_state *ms = &vs->arch.hvm_vcpu.mtrr;
    int32_t res;
    uint8_t num_var_ranges = (uint8_t)md->mtrr_cap;

    /* Test fixed ranges. */
    res = memcmp(md->fixed_ranges, ms->fixed_ranges,
            NUM_FIXED_RANGES*sizeof(mtrr_type));
    if ( res )
        return 1;

    /* Test var ranges. */
    res = memcmp(md->var_ranges, ms->var_ranges,
            num_var_ranges*sizeof(struct mtrr_var_range));
    if ( res )
        return 1;

    /* Test default type MSR. */
    if ( (md->def_type != ms->def_type)
            && (md->enabled != ms->enabled) )
        return 1;

    /* Test PAT. */
    if ( vd->arch.hvm_vcpu.pat_cr != vs->arch.hvm_vcpu.pat_cr )
        return 1;

    return 0;
}

void hvm_init_cacheattr_region_list(
    struct domain *d)
{
    INIT_LIST_HEAD(&d->arch.hvm_domain.pinned_cacheattr_ranges);
}

void hvm_destroy_cacheattr_region_list(
    struct domain *d)
{
    struct list_head *head = &d->arch.hvm_domain.pinned_cacheattr_ranges;
    struct hvm_mem_pinned_cacheattr_range *range;

    while ( !list_empty(head) )
    {
        range = list_entry(head->next,
                           struct hvm_mem_pinned_cacheattr_range,
                           list);
        list_del(&range->list);
        xfree(range);
    }
}

int32_t hvm_get_mem_pinned_cacheattr(
    struct domain *d,
    uint64_t guest_fn,
    uint32_t *type)
{
    struct hvm_mem_pinned_cacheattr_range *range;

    *type = 0;

    if ( !is_hvm_domain(d) )
        return 0;

    list_for_each_entry_rcu ( range,
                              &d->arch.hvm_domain.pinned_cacheattr_ranges,
                              list )
    {
        if ( (guest_fn >= range->start) && (guest_fn <= range->end) )
        {
            *type = range->type;
            return 1;
        }
    }

    return 0;
}

int32_t hvm_set_mem_pinned_cacheattr(
    struct domain *d,
    uint64_t gfn_start,
    uint64_t gfn_end,
    uint32_t  type)
{
    struct hvm_mem_pinned_cacheattr_range *range;

    if ( !((type == PAT_TYPE_UNCACHABLE) ||
           (type == PAT_TYPE_WRCOMB) ||
           (type == PAT_TYPE_WRTHROUGH) ||
           (type == PAT_TYPE_WRPROT) ||
           (type == PAT_TYPE_WRBACK) ||
           (type == PAT_TYPE_UC_MINUS)) ||
         !is_hvm_domain(d) )
        return -EINVAL;

    range = xmalloc(struct hvm_mem_pinned_cacheattr_range);
    if ( range == NULL )
        return -ENOMEM;

    memset(range, 0, sizeof(*range));

    range->start = gfn_start;
    range->end = gfn_end;
    range->type = type;

    list_add_rcu(&range->list, &d->arch.hvm_domain.pinned_cacheattr_ranges);

    return 0;
}

static int hvm_save_mtrr_msr(struct domain *d, hvm_domain_context_t *h)
{
    int i;
    struct vcpu *v;
    struct hvm_hw_mtrr hw_mtrr;
    struct mtrr_state *mtrr_state;
    /* save mtrr&pat */
    for_each_vcpu(d, v)
    {
        mtrr_state = &v->arch.hvm_vcpu.mtrr;

        hw_mtrr.msr_pat_cr = v->arch.hvm_vcpu.pat_cr;

        hw_mtrr.msr_mtrr_def_type = mtrr_state->def_type
                                | (mtrr_state->enabled << 10);
        hw_mtrr.msr_mtrr_cap = mtrr_state->mtrr_cap;

        for ( i = 0; i < MTRR_VCNT; i++ )
        {
            /* save physbase */
            hw_mtrr.msr_mtrr_var[i*2] =
                ((uint64_t*)mtrr_state->var_ranges)[i*2];
            /* save physmask */
            hw_mtrr.msr_mtrr_var[i*2+1] =
                ((uint64_t*)mtrr_state->var_ranges)[i*2+1];
        }

        for ( i = 0; i < NUM_FIXED_MSR; i++ )
            hw_mtrr.msr_mtrr_fixed[i] =
                ((uint64_t*)mtrr_state->fixed_ranges)[i];

        if ( hvm_save_entry(MTRR, v->vcpu_id, h, &hw_mtrr) != 0 )
            return 1;
    }
    return 0;
}

static int hvm_load_mtrr_msr(struct domain *d, hvm_domain_context_t *h)
{
    int vcpuid, i;
    struct vcpu *v;
    struct mtrr_state *mtrr_state;
    struct hvm_hw_mtrr hw_mtrr;

    vcpuid = hvm_load_instance(h);
    if ( vcpuid > MAX_VIRT_CPUS || (v = d->vcpu[vcpuid]) == NULL )
    {
        gdprintk(XENLOG_ERR, "HVM restore: domain has no vcpu %u\n", vcpuid);
        return -EINVAL;
    }

    if ( hvm_load_entry(MTRR, h, &hw_mtrr) != 0 )
        return -EINVAL;

    mtrr_state = &v->arch.hvm_vcpu.mtrr;

    pat_msr_set(&v->arch.hvm_vcpu.pat_cr, hw_mtrr.msr_pat_cr);

    mtrr_state->mtrr_cap = hw_mtrr.msr_mtrr_cap;

    for ( i = 0; i < NUM_FIXED_MSR; i++ )
        mtrr_fix_range_msr_set(mtrr_state, i, hw_mtrr.msr_mtrr_fixed[i]);

    for ( i = 0; i < MTRR_VCNT; i++ )
    {
        mtrr_var_range_msr_set(mtrr_state,
                MTRRphysBase_MSR(i), hw_mtrr.msr_mtrr_var[i*2]);
        mtrr_var_range_msr_set(mtrr_state,
                MTRRphysMask_MSR(i), hw_mtrr.msr_mtrr_var[i*2+1]);
    }

    mtrr_def_type_msr_set(mtrr_state, hw_mtrr.msr_mtrr_def_type);

    return 0;
}

HVM_REGISTER_SAVE_RESTORE(MTRR, hvm_save_mtrr_msr, hvm_load_mtrr_msr,
                          1, HVMSR_PER_VCPU);

uint8_t epte_get_entry_emt(
    struct domain *d, unsigned long gfn, unsigned long mfn)
{
    uint8_t gmtrr_mtype, hmtrr_mtype;
    uint32_t type;
    struct vcpu *v = current;

    if ( (current->domain != d) && ((v = d->vcpu[0]) == NULL) )
        return MTRR_TYPE_WRBACK;

    if ( !v->domain->arch.hvm_domain.params[HVM_PARAM_IDENT_PT] )
        return MTRR_TYPE_WRBACK;

    if ( (v == current) && v->domain->arch.hvm_domain.is_in_uc_mode )
        return MTRR_TYPE_UNCACHABLE;

    if ( !mfn_valid(mfn) )
        return MTRR_TYPE_UNCACHABLE;

    if ( hvm_get_mem_pinned_cacheattr(d, gfn, &type) )
        return type;

    gmtrr_mtype = get_mtrr_type(&v->arch.hvm_vcpu.mtrr, (gfn << PAGE_SHIFT));
    hmtrr_mtype = get_mtrr_type(&mtrr_state, (mfn << PAGE_SHIFT));
    return ((gmtrr_mtype <= hmtrr_mtype) ? gmtrr_mtype : hmtrr_mtype);
}