# # Copyright (C) 2011 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # LIB_MENU:=Libraries define KernelPackage/lib-crc-ccitt SUBMENU:=$(LIB_MENU) TITLE:=CRC-CCITT support KCONFIG:=CONFIG_CRC_CCITT FILES:=$(LINUX_DIR)/lib/crc-ccitt.ko AUTOLOAD:=$(call AutoProbe,crc-ccitt) endef define KernelPackage/lib-crc-ccitt/description Kernel module for CRC-CCITT support endef $(eval $(call KernelPackage,lib-crc-ccitt)) define KernelPackage/lib-crc-itu-t SUBMENU:=$(LIB_MENU) TITLE:=CRC ITU-T V.41 support KCONFIG:=CONFIG_CRC_ITU_T FILES:=$(LINUX_DIR)/lib/crc-itu-t.ko AUTOLOAD:=$(call AutoProbe,crc-itu-t) endef define KernelPackage/lib-crc-itu-t/description Kernel module for CRC ITU-T V.41 support endef $(eval $(call KernelPackage,lib-crc-itu-t)) define KernelPackage/lib-crc7 SUBMENU:=$(LIB_MENU) TITLE:=CRC7 support KCONFIG:=CONFIG_CRC7 FILES:=$(LINUX_DIR)/lib/crc7.ko AUTOLOAD:=$(call AutoProbe,crc7) endef define KernelPackage/lib-crc7/description Kernel module for CRC7 support endef $(eval $(call KernelPackage,lib-crc7)) define KernelPackage/lib-crc8 SUBMENU:=$(LIB_MENU) TITLE:=CRC8 support KCONFIG:=CONFIG_CRC8 FILES:=$(LINUX_DIR)/lib/crc8.ko AUTOLOAD:=$(call AutoProbe,crc8) endef define KernelPackage/lib-crc8/description Kernel module for CRC8 support endef $(eval $(call KernelPackage,lib-crc8)) define KernelPackage/lib-crc16 SUBMENU:=$(LIB_MENU) TITLE:=CRC16 support KCONFIG:=CONFIG_CRC16 FILES:=$(LINUX_DIR)/lib/crc16.ko AUTOLOAD:=$(call AutoLoad,20,crc16,1) endef define KernelPackage/lib-crc16/description Kernel module for CRC16 support endef $(eval $(call KernelPackage,lib-crc16)) define KernelPackage/lib-crc32c SUBMENU:=$(LIB_MENU) TITLE:=CRC32 support KCONFIG:=CONFIG_LIBCRC32C DEPENDS:=+kmod-crypto-crc32c FILES:=$(LINUX_DIR)/lib/libcrc32c.ko AUTOLOAD:=$(call AutoProbe,libcrc32c) endef define KernelPackage/lib-crc32c/description Kernel module for CRC32 support endef $(eval $(call KernelPackage,lib-crc32c)) define KernelPackage/lib-lzo SUBMENU:=$(LIB_MENU) TITLE:=LZO support KCONFIG:= \ CONFIG_LZO_COMPRESS \ CONFIG_LZO_DECOMPRESS FILES:= \ $(LINUX_DIR)/lib/lzo/lzo_compress.ko \ $(LINUX_DIR)/lib/lzo/lzo_decompress.ko AUTOLOAD:=$(call AutoProbe,lzo_compress lzo_decompress) endef define KernelPackage/lib-lzo/description Kernel module for LZO compression/decompression support endef $(eval $(call KernelPackage,lib-lzo)) define KernelPackage/lib-lz4 SUBMENU:=$(LIB_MENU) TITLE:=LZ4 support KCONFIG:= \ CONFIG_LZ4_COMPRESS \ CONFIG_LZ4_DECOMPRESS FILES:= \ $(LINUX_DIR)/lib/lz4/lz4_compress.ko \ $(LINUX_DIR)/lib/lz4/lz4_decompress.ko AUTOLOAD:=$(call AutoProbe,lz4_compress lz4_decompress) endef define KernelPackage/lib-lz4/description Kernel module for LZ4 compression/decompression support endef $(eval $(call KernelPackage,lib-lz4)) define KernelPackage/lib-raid6 SUBMENU:=$(LIB_MENU) TITLE:=RAID6 algorithm support HIDDEN:=1 KCONFIG:=CONFIG_RAID6_PQ FILES:=$(LINUX_DIR)/lib/raid6/raid6_pq.ko AUTOLOAD:=$(call AutoProbe,raid6_pq) endef define KernelPackage/lib-raid6/description Kernel module for RAID6 algorithms endef $(eval $(call KernelPackage,lib-raid6)) define KernelPackage/lib-xor SUBMENU:=$(LIB_MENU) TITLE:=XOR blocks algorithm support HIDDEN:=1 KCONFIG:=CONFIG_XOR_BLOCKS ifneq ($(wildcard $(LINUX_DIR)/arch/arm/lib/xor-neon.ko),) FILES:= \ $(LINUX_DIR)/crypto/xor.ko \ $(LINUX_DIR)/arch/arm/lib/xor-neon.ko AUTOLOAD:=$(call AutoProbe,xor-neon xor) else FILES:=$(LINUX_DIR)/crypto/xor.ko AUTOLOAD:=$(call AutoProbe,xor) endif endef define KernelPackage/lib-xor/description Kernel module for XOR blocks algorithms endef $(eval $(call KernelPackage,lib-xor)) define KernelPackage/lib-textsearch SUBMENU:=$(LIB_MENU) TITLE:=Textsearch support KCONFIG:= \ CONFIG_TEXTSEARCH=y \ CONFIG_TEXTSEARCH_KMP \ CONFIG_TEXTSEARCH_BM \ CONFIG_TEXTSEARCH_FSM FILES:= \ $(LINUX_DIR)/lib/ts_kmp.ko \ $(LINUX_DIR)/lib/ts_bm.ko \ $(LINUX_DIR)/lib/ts_fsm.ko AUTOLOAD:=$(call AutoProbe,ts_kmp ts_bm ts_fsm) endef $(eval $(call KernelPackage,lib-textsearch)) define KernelPackage/lib-zlib SUBMENU:=$(LIB_MENU) TITLE:=Zlib support KCONFIG:= \ CONFIG_ZLIB_DEFLATE \ CONFIG_ZLIB_INFLATE FILES:= \ $(LINUX_DIR)/lib/zlib_deflate/zlib_deflate.ko \ $(LINUX_DIR)/lib/zlib_inflate/zlib_inflate.ko AUTOLOAD:=$(call AutoProbe,zlib_deflate zlib_inflate) endef $(eval $(call KernelPackage,lib-zlib)) define KernelPackage/lib-cordic SUBMENU:=$(LIB_MENU) TITLE:=Cordic function support KCONFIG:=CONFIG_CORDIC FILES:=$(LINUX_DIR)/lib/cordic.ko AUTOLOAD:=$(call AutoProbe,cordic) endef define KernelPackage/lib-cordic/description Kernel module for Cordic function support endef $(eval $(call KernelPackage,lib-cordic)) > 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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
/*
 * vmcs.c: VMCS management
 * Copyright (c) 2004, 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 <xen/config.h>
#include <xen/init.h>
#include <xen/mm.h>
#include <xen/lib.h>
#include <xen/errno.h>
#include <xen/domain_page.h>
#include <asm/current.h>
#include <asm/cpufeature.h>
#include <asm/processor.h>
#include <asm/msr.h>
#include <asm/hvm/hvm.h>
#include <asm/hvm/io.h>
#include <asm/hvm/support.h>
#include <asm/hvm/vmx/vmx.h>
#include <asm/hvm/vmx/vmcs.h>
#include <asm/flushtlb.h>
#include <xen/event.h>
#include <xen/kernel.h>
#include <asm/shadow.h>
#include <xen/keyhandler.h>

#if CONFIG_PAGING_LEVELS >= 3
#include <asm/shadow_64.h>
#endif

static int vmcs_size;
static int vmcs_order;
static u32 vmcs_revision_id;

void vmx_init_vmcs_config(void)
{
    u32 vmx_msr_low, vmx_msr_high;

    if ( vmcs_size )
        return;

    rdmsr(MSR_IA32_VMX_BASIC_MSR, vmx_msr_low, vmx_msr_high);

    vmcs_revision_id = vmx_msr_low;

    vmcs_size  = vmx_msr_high & 0x1fff;
    vmcs_order = get_order_from_bytes(vmcs_size);
}

static struct vmcs_struct *vmx_alloc_vmcs(void)
{
    struct vmcs_struct *vmcs;

    if ( (vmcs = alloc_xenheap_pages(vmcs_order)) == NULL )
    {
        DPRINTK("Failed to allocate VMCS.\n");
        return NULL;
    }

    memset(vmcs, 0, vmcs_size); /* don't remove this */
    vmcs->vmcs_revision_id = vmcs_revision_id;

    return vmcs;
}

static void vmx_free_vmcs(struct vmcs_struct *vmcs)
{
    free_xenheap_pages(vmcs, vmcs_order);
}

static void __vmx_clear_vmcs(void *info)
{
    struct vcpu *v = info;

    __vmpclear(virt_to_maddr(v->arch.hvm_vmx.vmcs));

    v->arch.hvm_vmx.active_cpu = -1;
    v->arch.hvm_vmx.launched   = 0;
}

static void vmx_clear_vmcs(struct vcpu *v)
{
    int cpu = v->arch.hvm_vmx.active_cpu;

    if ( cpu == -1 )
        return;

    if ( cpu == smp_processor_id() )
        return __vmx_clear_vmcs(v);

    on_selected_cpus(cpumask_of_cpu(cpu), __vmx_clear_vmcs, v, 1, 1);
}

static void vmx_load_vmcs(struct vcpu *v)
{
    __vmptrld(virt_to_maddr(v->arch.hvm_vmx.vmcs));
    v->arch.hvm_vmx.active_cpu = smp_processor_id();
}

void vmx_vmcs_enter(struct vcpu *v)
{
    /*
     * NB. We must *always* run an HVM VCPU on its own VMCS, except for
     * vmx_vmcs_enter/exit critical regions. This leads to some XXX TODOs XXX:
     *  1. Move construct_vmcs() much earlier, to domain creation or
     *     context initialisation.
     *  2. VMPTRLD as soon as we context-switch to a HVM VCPU.
     *  3. VMCS destruction needs to happen later (from domain_destroy()).
     * We can relax this a bit if a paused VCPU always commits its
     * architectural state to a software structure.
     */
    if ( v == current )
        return;

    vcpu_pause(v);
    spin_lock(&v->arch.hvm_vmx.vmcs_lock);

    vmx_clear_vmcs(v);
    vmx_load_vmcs(v);
}

void vmx_vmcs_exit(struct vcpu *v)
{
    if ( v == current )
        return;

    /* Don't confuse arch_vmx_do_resume (for @v or @current!) */
    vmx_clear_vmcs(v);
    if ( hvm_guest(current) )
        vmx_load_vmcs(current);

    spin_unlock(&v->arch.hvm_vmx.vmcs_lock);
    vcpu_unpause(v);
}

struct vmcs_struct *vmx_alloc_host_vmcs(void)
{
    return vmx_alloc_vmcs();
}

void vmx_free_host_vmcs(struct vmcs_struct *vmcs)
{
    vmx_free_vmcs(vmcs);
}

static inline int construct_vmcs_controls(struct arch_vmx_struct *arch_vmx)
{
    int error = 0;

    error |= __vmwrite(PIN_BASED_VM_EXEC_CONTROL,
                       MONITOR_PIN_BASED_EXEC_CONTROLS);

    error |= __vmwrite(VM_EXIT_CONTROLS, MONITOR_VM_EXIT_CONTROLS);

    error |= __vmwrite(VM_ENTRY_CONTROLS, MONITOR_VM_ENTRY_CONTROLS);

    error |= __vmwrite(IO_BITMAP_A, virt_to_maddr(arch_vmx->io_bitmap_a));
    error |= __vmwrite(IO_BITMAP_B, virt_to_maddr(arch_vmx->io_bitmap_b));

#ifdef CONFIG_X86_PAE
    /* On PAE bitmaps may in future be above 4GB. Write high words. */
    error |= __vmwrite(IO_BITMAP_A_HIGH,
                       (paddr_t)virt_to_maddr(arch_vmx->io_bitmap_a) >> 32);
    error |= __vmwrite(IO_BITMAP_B_HIGH,
                       (paddr_t)virt_to_maddr(arch_vmx->io_bitmap_b) >> 32);
#endif

    return error;
}

#define GUEST_LAUNCH_DS         0x08
#define GUEST_LAUNCH_CS         0x10
#define GUEST_SEGMENT_LIMIT     0xffffffff
#define HOST_SEGMENT_LIMIT      0xffffffff

struct host_execution_env {
    /* selectors */
    unsigned short ldtr_selector;
    unsigned short tr_selector;
    unsigned short ds_selector;
    unsigned short cs_selector;
    /* limits */
    unsigned short gdtr_limit;
    unsigned short ldtr_limit;
    unsigned short idtr_limit;
    unsigned short tr_limit;
    /* base */
    unsigned long gdtr_base;
    unsigned long ldtr_base;
    unsigned long idtr_base;
    unsigned long tr_base;
    unsigned long ds_base;
    unsigned long cs_base;
#ifdef __x86_64__
    unsigned long fs_base;
    unsigned long gs_base;
#endif
};

static void vmx_set_host_env(struct vcpu *v)
{
    unsigned int tr, cpu, error = 0;
    struct host_execution_env host_env;
    struct Xgt_desc_struct desc;

    cpu = smp_processor_id();
    __asm__ __volatile__ ("sidt  (%0) \n" :: "a"(&desc) : "memory");
    host_env.idtr_limit = desc.size;
    host_env.idtr_base = desc.address;
    error |= __vmwrite(HOST_IDTR_BASE, host_env.idtr_base);

    __asm__ __volatile__ ("sgdt  (%0) \n" :: "a"(&desc) : "memory");
    host_env.gdtr_limit = desc.size;
    host_env.gdtr_base = desc.address;
    error |= __vmwrite(HOST_GDTR_BASE, host_env.gdtr_base);

    __asm__ __volatile__ ("str  (%0) \n" :: "a"(&tr) : "memory");
    host_env.tr_selector = tr;
    host_env.tr_limit = sizeof(struct tss_struct);
    host_env.tr_base = (unsigned long) &init_tss[cpu];
    error |= __vmwrite(HOST_TR_SELECTOR, host_env.tr_selector);
    error |= __vmwrite(HOST_TR_BASE, host_env.tr_base);
    error |= __vmwrite(HOST_RSP, (unsigned long)get_stack_bottom());
}

static void vmx_do_launch(struct vcpu *v)
{
/* Update CR3, GDT, LDT, TR */
    unsigned int  error = 0;
    unsigned long cr0, cr4;

    if (v->vcpu_id == 0)
        hvm_setup_platform(v->domain);

    if ( evtchn_bind_vcpu(iopacket_port(v), v->vcpu_id) < 0 )
    {
        printk("VMX domain bind port %d to vcpu %d failed!\n",
               iopacket_port(v), v->vcpu_id);
        domain_crash_synchronous();
    }

    HVM_DBG_LOG(DBG_LEVEL_1, "eport: %x", iopacket_port(v));

    clear_bit(iopacket_port(v),
              &v->domain->shared_info->evtchn_mask[0]);

    __asm__ __volatile__ ("mov %%cr0,%0" : "=r" (cr0) : );

    error |= __vmwrite(GUEST_CR0, cr0);
    cr0 &= ~X86_CR0_PG;
    error |= __vmwrite(CR0_READ_SHADOW, cr0);
    error |= __vmwrite(CPU_BASED_VM_EXEC_CONTROL,
                       MONITOR_CPU_BASED_EXEC_CONTROLS);
    v->arch.hvm_vcpu.u.vmx.exec_control = MONITOR_CPU_BASED_EXEC_CONTROLS;

    __asm__ __volatile__ ("mov %%cr4,%0" : "=r" (cr4) : );

    error |= __vmwrite(GUEST_CR4, cr4 & ~X86_CR4_PSE);
    cr4 &= ~(X86_CR4_PGE | X86_CR4_VMXE | X86_CR4_PAE);

    error |= __vmwrite(CR4_READ_SHADOW, cr4);

    vmx_stts();

    if(hvm_apic_support(v->domain))
        vlapic_init(v);

    vmx_set_host_env(v);
    init_timer(&v->arch.hvm_vmx.hlt_timer, hlt_timer_fn, v, v->processor);

    error |= __vmwrite(GUEST_LDTR_SELECTOR, 0);
    error |= __vmwrite(GUEST_LDTR_BASE, 0);
    error |= __vmwrite(GUEST_LDTR_LIMIT, 0);

    error |= __vmwrite(GUEST_TR_BASE, 0);
    error |= __vmwrite(GUEST_TR_LIMIT, 0xff);

    __vmwrite(GUEST_CR3, pagetable_get_paddr(v->domain->arch.phys_table));
    __vmwrite(HOST_CR3, pagetable_get_paddr(v->arch.monitor_table));

    v->arch.schedule_tail = arch_vmx_do_resume;

    /* init guest tsc to start from 0 */
    set_guest_time(v, 0);
}

/*
 * Initially set the same environement as host.
 */
static inline int construct_init_vmcs_guest(cpu_user_regs_t *regs)
{
    int error = 0;
    union vmcs_arbytes arbytes;
    unsigned long dr7;
    unsigned long eflags;

    /* MSR */
    error |= __vmwrite(VM_EXIT_MSR_LOAD_ADDR, 0);
    error |= __vmwrite(VM_EXIT_MSR_STORE_ADDR, 0);

    error |= __vmwrite(VM_EXIT_MSR_STORE_COUNT, 0);
    error |= __vmwrite(VM_EXIT_MSR_LOAD_COUNT, 0);
    error |= __vmwrite(VM_ENTRY_MSR_LOAD_COUNT, 0);
    /* interrupt */
    error |= __vmwrite(VM_ENTRY_INTR_INFO_FIELD, 0);
    /* mask */
    error |= __vmwrite(CR0_GUEST_HOST_MASK, -1UL);
    error |= __vmwrite(CR4_GUEST_HOST_MASK, -1UL);

    error |= __vmwrite(PAGE_FAULT_ERROR_CODE_MASK, 0);
    error |= __vmwrite(PAGE_FAULT_ERROR_CODE_MATCH, 0);

    /* TSC */
    error |= __vmwrite(CR3_TARGET_COUNT, 0);

    /* Guest Selectors */
    error |= __vmwrite(GUEST_ES_SELECTOR, GUEST_LAUNCH_DS);
    error |= __vmwrite(GUEST_SS_SELECTOR, GUEST_LAUNCH_DS);
    error |= __vmwrite(GUEST_DS_SELECTOR, GUEST_LAUNCH_DS);
    error |= __vmwrite(GUEST_FS_SELECTOR, GUEST_LAUNCH_DS);
    error |= __vmwrite(GUEST_GS_SELECTOR, GUEST_LAUNCH_DS);
    error |= __vmwrite(GUEST_CS_SELECTOR, GUEST_LAUNCH_CS);

    /* Guest segment bases */
    error |= __vmwrite(GUEST_ES_BASE, 0);
    error |= __vmwrite(GUEST_SS_BASE, 0);
    error |= __vmwrite(GUEST_DS_BASE, 0);
    error |= __vmwrite(GUEST_FS_BASE, 0);
    error |= __vmwrite(GUEST_GS_BASE, 0);
    error |= __vmwrite(GUEST_CS_BASE, 0);

    /* Guest segment Limits */
    error |= __vmwrite(GUEST_ES_LIMIT, GUEST_SEGMENT_LIMIT);
    error |= __vmwrite(GUEST_SS_LIMIT, GUEST_SEGMENT_LIMIT);
    error |= __vmwrite(GUEST_DS_LIMIT, GUEST_SEGMENT_LIMIT);
    error |= __vmwrite(GUEST_FS_LIMIT, GUEST_SEGMENT_LIMIT);
    error |= __vmwrite(GUEST_GS_LIMIT, GUEST_SEGMENT_LIMIT);
    error |= __vmwrite(GUEST_CS_LIMIT, GUEST_SEGMENT_LIMIT);

    /* Guest segment AR bytes */
    arbytes.bytes = 0;
    arbytes.fields.seg_type = 0x3;          /* type = 3 */
    arbytes.fields.s = 1;                   /* code or data, i.e. not system */
    arbytes.fields.dpl = 0;                 /* DPL = 3 */
    arbytes.fields.p = 1;                   /* segment present */
    arbytes.fields.default_ops_size = 1;    /* 32-bit */
    arbytes.fields.g = 1;
    arbytes.fields.null_bit = 0;            /* not null */

    error |= __vmwrite(GUEST_ES_AR_BYTES, arbytes.bytes);
    error |= __vmwrite(GUEST_SS_AR_BYTES, arbytes.bytes);
    error |= __vmwrite(GUEST_DS_AR_BYTES, arbytes.bytes);
    error |= __vmwrite(GUEST_FS_AR_BYTES, arbytes.bytes);
    error |= __vmwrite(GUEST_GS_AR_BYTES, arbytes.bytes);

    arbytes.fields.seg_type = 0xb;          /* type = 0xb */
    error |= __vmwrite(GUEST_CS_AR_BYTES, arbytes.bytes);

    /* Guest GDT */
    error |= __vmwrite(GUEST_GDTR_BASE, 0);
    error |= __vmwrite(GUEST_GDTR_LIMIT, 0);

    /* Guest IDT */
    error |= __vmwrite(GUEST_IDTR_BASE, 0);
    error |= __vmwrite(GUEST_IDTR_LIMIT, 0);

    /* Guest LDT & TSS */
    arbytes.fields.s = 0;                   /* not code or data segement */
    arbytes.fields.seg_type = 0x2;          /* LTD */
    arbytes.fields.default_ops_size = 0;    /* 16-bit */
    arbytes.fields.g = 0;
    error |= __vmwrite(GUEST_LDTR_AR_BYTES, arbytes.bytes);

    arbytes.fields.seg_type = 0xb;          /* 32-bit TSS (busy) */
    error |= __vmwrite(GUEST_TR_AR_BYTES, arbytes.bytes);
    /* CR3 is set in vmx_final_setup_guest */

    error |= __vmwrite(GUEST_RSP, 0);
    error |= __vmwrite(GUEST_RIP, regs->eip);

    /* Guest EFLAGS */
    eflags = regs->eflags & ~HVM_EFLAGS_RESERVED_0; /* clear 0s */
    eflags |= HVM_EFLAGS_RESERVED_1; /* set 1s */
    error |= __vmwrite(GUEST_RFLAGS, eflags);

    error |= __vmwrite(GUEST_INTERRUPTIBILITY_INFO, 0);
    __asm__ __volatile__ ("mov %%dr7, %0\n" : "=r" (dr7));
    error |= __vmwrite(GUEST_DR7, dr7);
    error |= __vmwrite(VMCS_LINK_POINTER, ~0UL);
#if defined(__i386__)
    error |= __vmwrite(VMCS_LINK_POINTER_HIGH, ~0UL);
#endif

    return error;
}

static inline int construct_vmcs_host(void)
{
    int error = 0;
#ifdef __x86_64__
    unsigned long fs_base;
    unsigned long gs_base;
#endif
    unsigned long crn;

    /* Host Selectors */
    error |= __vmwrite(HOST_ES_SELECTOR, __HYPERVISOR_DS);
    error |= __vmwrite(HOST_SS_SELECTOR, __HYPERVISOR_DS);
    error |= __vmwrite(HOST_DS_SELECTOR, __HYPERVISOR_DS);
#if defined(__i386__)
    error |= __vmwrite(HOST_FS_SELECTOR, __HYPERVISOR_DS);
    error |= __vmwrite(HOST_GS_SELECTOR, __HYPERVISOR_DS);
    error |= __vmwrite(HOST_FS_BASE, 0);
    error |= __vmwrite(HOST_GS_BASE, 0);

#else
    rdmsrl(MSR_FS_BASE, fs_base);
    rdmsrl(MSR_GS_BASE, gs_base);
    error |= __vmwrite(HOST_FS_BASE, fs_base);
    error |= __vmwrite(HOST_GS_BASE, gs_base);

#endif
    error |= __vmwrite(HOST_CS_SELECTOR, __HYPERVISOR_CS);

    __asm__ __volatile__ ("mov %%cr0,%0" : "=r" (crn) : );
    error |= __vmwrite(HOST_CR0, crn); /* same CR0 */

    /* CR3 is set in vmx_final_setup_hostos */
    __asm__ __volatile__ ("mov %%cr4,%0" : "=r" (crn) : );
    error |= __vmwrite(HOST_CR4, crn);

    error |= __vmwrite(HOST_RIP, (unsigned long) vmx_asm_vmexit_handler);
#ifdef __x86_64__
    /* TBD: support cr8 for 64-bit guest */
    __vmwrite(VIRTUAL_APIC_PAGE_ADDR, 0);
    __vmwrite(TPR_THRESHOLD, 0);
    __vmwrite(SECONDARY_VM_EXEC_CONTROL, 0);
#endif

    return error;
}

/*
 * the working VMCS pointer has been set properly
 * just before entering this function.
 */
static int construct_vmcs(struct vcpu *v,
                          cpu_user_regs_t *regs)
{
    struct arch_vmx_struct *arch_vmx = &v->arch.hvm_vmx;
    int error;

    if ( (error = construct_vmcs_controls(arch_vmx)) ) {
        printk("construct_vmcs: construct_vmcs_controls failed.\n");
        return error;
    }

    /* host selectors */
    if ( (error = construct_vmcs_host()) ) {
        printk("construct_vmcs: construct_vmcs_host failed.\n");
        return error;
    }

    /* guest selectors */
    if ( (error = construct_init_vmcs_guest(regs)) ) {
        printk("construct_vmcs: construct_vmcs_guest failed.\n");
        return error;
    }

    if ( (error = __vmwrite(EXCEPTION_BITMAP,
                            MONITOR_DEFAULT_EXCEPTION_BITMAP)) ) {
        printk("construct_vmcs: setting exception bitmap failed.\n");
        return error;
    }

    if ( regs->eflags & EF_TF )
        error = __vm_set_bit(EXCEPTION_BITMAP, EXCEPTION_BITMAP_DB);
    else
        error = __vm_clear_bit(EXCEPTION_BITMAP, EXCEPTION_BITMAP_DB);

    return error;
}

int vmx_create_vmcs(struct vcpu *v)
{
    if ( (v->arch.hvm_vmx.vmcs = vmx_alloc_vmcs()) == NULL )
        return -ENOMEM;
    __vmx_clear_vmcs(v);
    return 0;
}

void vmx_destroy_vmcs(struct vcpu *v)
{
    struct arch_vmx_struct *arch_vmx = &v->arch.hvm_vmx;

    if ( arch_vmx->vmcs == NULL )
        return;

    vmx_clear_vmcs(v);

    free_xenheap_pages(arch_vmx->io_bitmap_a, IO_BITMAP_ORDER);
    free_xenheap_pages(arch_vmx->io_bitmap_b, IO_BITMAP_ORDER);

    arch_vmx->io_bitmap_a = NULL;
    arch_vmx->io_bitmap_b = NULL;

    vmx_free_vmcs(arch_vmx->vmcs);
    arch_vmx->vmcs = NULL;
}

void vm_launch_fail(unsigned long eflags)
{
    unsigned long error;
    __vmread(VM_INSTRUCTION_ERROR, &error);
    printk("<vm_launch_fail> error code %lx\n", error);
    __hvm_bug(guest_cpu_user_regs());
}

void vm_resume_fail(unsigned long eflags)
{
    unsigned long error;
    __vmread(VM_INSTRUCTION_ERROR, &error);
    printk("<vm_resume_fail> error code %lx\n", error);
    __hvm_bug(guest_cpu_user_regs());
}

void arch_vmx_do_resume(struct vcpu *v)
{
    if ( v->arch.hvm_vmx.active_cpu == smp_processor_id() )
    {
        vmx_load_vmcs(v);
    }
    else
    {
        vmx_clear_vmcs(v);
        vmx_load_vmcs(v);
        vmx_migrate_timers(v);
        vmx_set_host_env(v);
    }

    vmx_do_resume(v);
    reset_stack_and_jump(vmx_asm_do_vmentry);
}

void arch_vmx_do_launch(struct vcpu *v)
{
    cpu_user_regs_t *regs = &current->arch.guest_context.user_regs;

    vmx_load_vmcs(v);

    if ( construct_vmcs(v, regs) < 0 )
    {
        if ( v->vcpu_id == 0 ) {
            printk("Failed to construct VMCS for BSP.\n");
        } else {
            printk("Failed to construct VMCS for AP %d.\n", v->vcpu_id);
        }
        domain_crash_synchronous();
    }

    vmx_do_launch(v);
    reset_stack_and_jump(vmx_asm_do_vmentry);
}


/* Dump a section of VMCS */
static void print_section(char *header, uint32_t start, 
                          uint32_t end, int incr)
{
    uint32_t addr, j;
    unsigned long val;
    int code;
    char *fmt[4] = {"0x%04lx ", "0x%016lx ", "0x%08lx ", "0x%016lx "};
    char *err[4] = {"------ ", "------------------ ", 
                    "---------- ", "------------------ "};

    /* Find width of the field (encoded in bits 14:13 of address) */
    code = (start>>13)&3;

    if (header)
        printk("\t %s", header);

    for (addr=start, j=0; addr<=end; addr+=incr, j++) {

        if (!(j&3))
            printk("\n\t\t0x%08x: ", addr);

        if (!__vmread(addr, &val))
            printk(fmt[code], val);
        else
            printk("%s", err[code]);
    }

    printk("\n");
}

/* Dump current VMCS */
void vmcs_dump_vcpu(void)
{
    print_section("16-bit Guest-State Fields", 0x800, 0x80e, 2);
    print_section("16-bit Host-State Fields", 0xc00, 0xc0c, 2);
    print_section("64-bit Control Fields", 0x2000, 0x2013, 1);
    print_section("64-bit Guest-State Fields", 0x2800, 0x2803, 1);
    print_section("32-bit Control Fields", 0x4000, 0x401c, 2);
    print_section("32-bit RO Data Fields", 0x4400, 0x440e, 2);
    print_section("32-bit Guest-State Fields", 0x4800, 0x482a, 2);
    print_section("32-bit Host-State Fields", 0x4c00, 0x4c00, 2);
    print_section("Natural 64-bit Control Fields", 0x6000, 0x600e, 2);
    print_section("64-bit RO Data Fields", 0x6400, 0x640A, 2);
    print_section("Natural 64-bit Guest-State Fields", 0x6800, 0x6826, 2);
    print_section("Natural 64-bit Host-State Fields", 0x6c00, 0x6c16, 2);
}


static void vmcs_dump(unsigned char ch)
{
    struct domain *d;
    struct vcpu *v;
    
    printk("*********** VMCS Areas **************\n");
    for_each_domain(d) {
        printk("\n>>> Domain %d <<<\n", d->domain_id);
        for_each_vcpu(d, v) {

            /* 
             * Presumably, if a domain is not an HVM guest,
             * the very first CPU will not pass this test
             */
            if (!hvm_guest(v)) {
                printk("\t\tNot HVM guest\n");
                break;
            }
            printk("\tVCPU %d\n", v->vcpu_id);

            vmx_vmcs_enter(v);
            vmcs_dump_vcpu();
            vmx_vmcs_exit(v);
        }
    }

    printk("**************************************\n");
}

static int __init setup_vmcs_dump(void)
{
    register_keyhandler('v', vmcs_dump, "dump Intel's VMCS");
    return 0;
}

__initcall(setup_vmcs_dump);

/*
 * Local variables:
 * mode: C
 * c-set-style: "BSD"
 * c-basic-offset: 4
 * tab-width: 4
 * indent-tabs-mode: nil
 * End:
 */