[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Xen-changelog] [xen-unstable] merge with xen-unstable.hg



# HG changeset patch
# User Alex Williamson <alex.williamson@xxxxxx>
# Date 1185545716 21600
# Node ID 4492a0285bae734ee18f6acbb6b3f9c80f153be7
# Parent  37833b33ae779151a9d88edd15b93d0d3f56d0fc
# Parent  5682f899c7ae7fa945085aaded75cd1220fd8d17
merge with xen-unstable.hg
---
 xen/arch/x86/mm/hap/support.c                                     |  334 --
 xen/include/xen/shadow.h                                          |   23 
 .hgignore                                                         |    7 
 Config.mk                                                         |    8 
 buildconfigs/enable-xen-config                                    |    4 
 buildconfigs/mk.linux-2.6                                         |   14 
 buildconfigs/mk.linux-2.6-git                                     |    2 
 buildconfigs/mk.linux-2.6-mm                                      |   14 
 buildconfigs/mk.linux-2.6-rc                                      |   14 
 buildconfigs/mk.linux-2.6-tip                                     |   14 
 docs/man/xm.pod.1                                                 |  167 -
 docs/xen-api/xenapi-datamodel-graph.dot                           |    4 
 docs/xen-api/xenapi-datamodel.tex                                 | 1375 
++++++++--
 tools/examples/vtpm-common.sh                                     |   56 
 tools/firmware/hvmloader/acpi/dsdt.asl                            |   21 
 tools/firmware/hvmloader/acpi/dsdt.c                              |   25 
 tools/firmware/hvmloader/config.h                                 |    2 
 tools/firmware/hvmloader/hvmloader.c                              |   12 
 tools/firmware/rombios/rombios.c                                  |   48 
 tools/ioemu/hw/cirrus_vga.c                                       |    2 
 tools/ioemu/hw/ide.c                                              |    3 
 tools/ioemu/hw/rtl8139.c                                          |   11 
 tools/ioemu/keymaps.c                                             |   16 
 tools/ioemu/target-i386-dm/exec-dm.c                              |    6 
 tools/ioemu/target-i386-dm/helper2.c                              |   43 
 tools/ioemu/vl.c                                                  |   38 
 tools/ioemu/vl.h                                                  |    1 
 tools/ioemu/vnc.c                                                 |   92 
 tools/ioemu/xenstore.c                                            |   98 
 tools/libxc/xc_domain.c                                           |   21 
 tools/libxc/xc_linux.c                                            |    2 
 tools/libxc/xenctrl.h                                             |   14 
 tools/libxen/include/xen/api/xen_acmpolicy.h                      |  117 
 tools/libxen/include/xen/api/xen_vdi.h                            |   13 
 tools/libxen/include/xen/api/xen_vif.h                            |   14 
 tools/libxen/include/xen/api/xen_vm.h                             |   14 
 tools/libxen/include/xen/api/xen_xspolicy.h                       |  271 +
 tools/libxen/include/xen/api/xen_xspolicy_decl.h                  |   31 
 tools/libxen/src/xen_acmpolicy.c                                  |  234 +
 tools/libxen/src/xen_vdi.c                                        |   39 
 tools/libxen/src/xen_vif.c                                        |   39 
 tools/libxen/src/xen_vm.c                                         |   45 
 tools/libxen/src/xen_xspolicy.c                                   |  327 ++
 tools/python/xen/lowlevel/acm/acm.c                               |    9 
 tools/python/xen/util/acmpolicy.py                                |   98 
 tools/python/xen/util/security.py                                 |  146 -
 tools/python/xen/xend/XendAPI.py                                  |   48 
 tools/python/xen/xend/XendCheckpoint.py                           |    6 
 tools/python/xen/xend/XendConfig.py                               |   28 
 tools/python/xen/xend/XendDevices.py                              |    3 
 tools/python/xen/xend/XendDomain.py                               |   57 
 tools/python/xen/xend/XendDomainInfo.py                           |   52 
 tools/python/xen/xend/XendPIF.py                                  |   10 
 tools/python/xen/xend/XendVDI.py                                  |    1 
 tools/python/xen/xend/XendXSPolicyAdmin.py                        |   21 
 tools/python/xen/xend/balloon.py                                  |    8 
 tools/python/xen/xend/image.py                                    |   42 
 tools/python/xen/xend/server/SrvServer.py                         |    3 
 tools/python/xen/xend/server/netif.py                             |   43 
 tools/python/xen/xend/server/tpmif.py                             |    5 
 tools/python/xen/xm/activatepolicy.py                             |   86 
 tools/python/xen/xm/addlabel.py                                   |  176 +
 tools/python/xen/xm/cfgbootpolicy.py                              |   77 
 tools/python/xen/xm/create.dtd                                    |   10 
 tools/python/xen/xm/create.py                                     |   25 
 tools/python/xen/xm/getlabel.py                                   |   71 
 tools/python/xen/xm/getpolicy.py                                  |   94 
 tools/python/xen/xm/labels.py                                     |   37 
 tools/python/xen/xm/loadpolicy.py                                 |   32 
 tools/python/xen/xm/main.py                                       |  115 
 tools/python/xen/xm/makepolicy.py                                 |   14 
 tools/python/xen/xm/resources.py                                  |   33 
 tools/python/xen/xm/rmlabel.py                                    |  101 
 tools/python/xen/xm/setpolicy.py                                  |  117 
 tools/python/xen/xm/xenapi_create.py                              |   68 
 tools/security/policies/security_policy.xsd                       |    7 
 tools/vtpm_manager/util/hashtable_itr.c                           |    8 
 tools/xcutils/xc_save.c                                           |   29 
 tools/xenfb/vncfb.c                                               |  110 
 tools/xenstore/talloc.c                                           |   18 
 tools/xenstore/xenstored_core.c                                   |  144 -
 tools/xenstore/xenstored_domain.c                                 |   14 
 tools/xenstore/xenstored_watch.c                                  |    5 
 tools/xenstore/xsls.c                                             |   37 
 tools/xm-test/lib/XmTestLib/XenAPIDomain.py                       |    4 
 tools/xm-test/lib/XmTestLib/acm.py                                |   52 
 tools/xm-test/tests/security-acm/01_security-acm_basic.py         |   24 
 tools/xm-test/tests/security-acm/07_security-acm_pol_update.py    |  303 ++
 tools/xm-test/tests/security-acm/08_security-acm_xapi.py          |  354 ++
 tools/xm-test/tests/security-acm/09_security-acm_pol_update.py    |  427 +++
 tools/xm-test/tests/security-acm/Makefile.am                      |    5 
 tools/xm-test/tests/security-acm/xm-test-new-security_policy.xml  |   97 
 tools/xm-test/tests/vtpm/01_vtpm-list_pos.py                      |    8 
 tools/xm-test/tests/vtpm/02_vtpm-cat_pcrs.py                      |    9 
 tools/xm-test/tests/vtpm/03_vtpm-susp_res.py                      |   16 
 tools/xm-test/tests/vtpm/04_vtpm-loc_migr.py                      |   15 
 tools/xm-test/tests/vtpm/05_vtpm-loc_migr.py                      |   15 
 tools/xm-test/tests/vtpm/06_vtpm-susp_res_pcrs.py                 |   20 
 tools/xm-test/tests/vtpm/07_vtpm-mig_pcrs.py                      |   19 
 tools/xm-test/tests/vtpm/08_vtpm-mig_pcrs.py                      |   19 
 tools/xm-test/tests/vtpm/vtpm_utils.py                            |   14 
 unmodified_drivers/linux-2.6/compat-include/xen/platform-compat.h |    9 
 unmodified_drivers/linux-2.6/netfront/Kbuild                      |    1 
 xen/Makefile                                                      |   16 
 xen/acm/acm_chinesewall_hooks.c                                   |  190 -
 xen/acm/acm_core.c                                                |   29 
 xen/acm/acm_policy.c                                              |  309 +-
 xen/acm/acm_simple_type_enforcement_hooks.c                       |  397 +-
 xen/arch/ia64/linux-xen/perfmon.c                                 |    2 
 xen/arch/ia64/xen/oprofile/perfmon.c                              |   11 
 xen/arch/powerpc/Rules.mk                                         |    4 
 xen/arch/powerpc/exceptions.h                                     |    3 
 xen/arch/powerpc/mpic_init.c                                      |    4 
 xen/arch/powerpc/of-devtree.c                                     |    2 
 xen/arch/powerpc/of-devwalk.c                                     |    8 
 xen/arch/powerpc/of_handler/ofh.c                                 |   24 
 xen/arch/powerpc/of_handler/papr.S                                |    2 
 xen/arch/powerpc/ofd_fixup.c                                      |   13 
 xen/arch/powerpc/papr/Makefile                                    |    1 
 xen/arch/powerpc/papr/h_perfmon.c                                 |  158 +
 xen/arch/powerpc/powerpc64/domain.c                               |   46 
 xen/arch/powerpc/powerpc64/exceptions.S                           |   25 
 xen/arch/powerpc/sysctl.c                                         |    1 
 xen/arch/x86/acpi/Makefile                                        |    1 
 xen/arch/x86/acpi/boot.c                                          |   93 
 xen/arch/x86/acpi/power.c                                         |  282 ++
 xen/arch/x86/acpi/suspend.c                                       |   73 
 xen/arch/x86/acpi/wakeup_prot.S                                   |  267 +
 xen/arch/x86/apic.c                                               |    2 
 xen/arch/x86/boot/Makefile                                        |    3 
 xen/arch/x86/boot/head.S                                          |    2 
 xen/arch/x86/boot/wakeup.S                                        |  212 +
 xen/arch/x86/cpu/common.c                                         |   11 
 xen/arch/x86/cpu/intel_cacheinfo.c                                |    4 
 xen/arch/x86/crash.c                                              |    4 
 xen/arch/x86/dmi_scan.c                                           |    1 
 xen/arch/x86/domain.c                                             |   72 
 xen/arch/x86/domain_build.c                                       |    3 
 xen/arch/x86/domctl.c                                             |   40 
 xen/arch/x86/e820.c                                               |   71 
 xen/arch/x86/hvm/hvm.c                                            |    6 
 xen/arch/x86/hvm/svm/svm.c                                        |   20 
 xen/arch/x86/hvm/svm/vmcb.c                                       |   10 
 xen/arch/x86/hvm/vlapic.c                                         |    9 
 xen/arch/x86/hvm/vmx/vmcs.c                                       |  219 +
 xen/arch/x86/hvm/vmx/vmx.c                                        |  109 
 xen/arch/x86/hvm/vpt.c                                            |    8 
 xen/arch/x86/i8259.c                                              |    6 
 xen/arch/x86/io_apic.c                                            |    3 
 xen/arch/x86/irq.c                                                |   33 
 xen/arch/x86/machine_kexec.c                                      |    4 
 xen/arch/x86/mm.c                                                 |   23 
 xen/arch/x86/mm/hap/Makefile                                      |   10 
 xen/arch/x86/mm/hap/guest_walk.c                                  |  181 +
 xen/arch/x86/mm/hap/hap.c                                         |  383 +-
 xen/arch/x86/mm/hap/private.h                                     |   55 
 xen/arch/x86/mm/shadow/multi.c                                    |   46 
 xen/arch/x86/nmi.c                                                |    2 
 xen/arch/x86/oprofile/nmi_int.c                                   |   83 
 xen/arch/x86/platform_hypercall.c                                 |    5 
 xen/arch/x86/setup.c                                              |    4 
 xen/arch/x86/shutdown.c                                           |    2 
 xen/arch/x86/smp.c                                                |    2 
 xen/arch/x86/smpboot.c                                            |  340 ++
 xen/arch/x86/x86_32/traps.c                                       |    2 
 xen/arch/x86/x86_64/mm.c                                          |    3 
 xen/arch/x86/x86_64/platform_hypercall.c                          |    3 
 xen/arch/x86/x86_64/traps.c                                       |    2 
 xen/common/compat/kernel.c                                        |    1 
 xen/common/domctl.c                                               |    2 
 xen/common/grant_table.c                                          |   13 
 xen/common/kernel.c                                               |    4 
 xen/common/keyhandler.c                                           |    1 
 xen/common/memory.c                                               |    8 
 xen/common/page_alloc.c                                           |   60 
 xen/common/sysctl.c                                               |   14 
 xen/common/xenoprof.c                                             |   58 
 xen/drivers/acpi/tables.c                                         |    3 
 xen/drivers/char/ns16550.c                                        |    4 
 xen/drivers/char/serial.c                                         |    4 
 xen/include/acm/acm_core.h                                        |    7 
 xen/include/acm/acm_hooks.h                                       |   62 
 xen/include/asm-ia64/xenoprof.h                                   |    2 
 xen/include/asm-powerpc/domain.h                                  |   21 
 xen/include/asm-powerpc/numa.h                                    |    1 
 xen/include/asm-powerpc/papr.h                                    |    1 
 xen/include/asm-powerpc/processor.h                               |  138 -
 xen/include/asm-powerpc/reg_defs.h                                |   27 
 xen/include/asm-powerpc/xenoprof.h                                |   76 
 xen/include/asm-x86/acpi.h                                        |   20 
 xen/include/asm-x86/config.h                                      |   12 
 xen/include/asm-x86/desc.h                                        |    5 
 xen/include/asm-x86/domain.h                                      |   10 
 xen/include/asm-x86/hap.h                                         |    3 
 xen/include/asm-x86/hvm/hvm.h                                     |   21 
 xen/include/asm-x86/hvm/support.h                                 |    1 
 xen/include/asm-x86/hvm/vmx/vmcs.h                                |    9 
 xen/include/asm-x86/page.h                                        |   15 
 xen/include/asm-x86/processor.h                                   |   18 
 xen/include/asm-x86/smp.h                                         |   15 
 xen/include/asm-x86/system.h                                      |    2 
 xen/include/asm-x86/xenoprof.h                                    |    4 
 xen/include/public/acm.h                                          |    5 
 xen/include/public/platform.h                                     |   12 
 xen/include/public/sysctl.h                                       |   13 
 xen/include/xen/acpi.h                                            |    1 
 xen/include/xen/cpumask.h                                         |    2 
 xen/include/xen/irq.h                                             |   10 
 xen/include/xen/mm.h                                              |    5 
 xen/include/xen/paging.h                                          |   26 
 xen/include/xen/xenoprof.h                                        |    2 
 211 files changed, 9151 insertions(+), 2580 deletions(-)

diff -r 37833b33ae77 -r 4492a0285bae .hgignore
--- a/.hgignore Thu Jul 26 14:35:01 2007 -0600
+++ b/.hgignore Fri Jul 27 08:15:16 2007 -0600
@@ -62,14 +62,11 @@
 ^extras/mini-os/h/xen-public$
 ^extras/mini-os/mini-os.*$
 ^install/.*$
-^linux-[^/]*-native/.*$
-^linux-[^/]*-xen/.*$
-^linux-[^/]*-xen0/.*$
-^linux-[^/]*-xenU/.*$
 ^linux-[^/]*-paravirt/.*$
-^linux-[^/]*-mm/.*$
+^linux-2.6[^/]*/.*$
 ^linux-[^/]*-rc/.*$
 ^linux-[^/]*-tip/.*$
+^linux-[^/]*-git/.*$
 ^linux-[^/]*\.patch$
 ^mkddbxen$
 ^netbsd-[^/]*-tools/.*$
diff -r 37833b33ae77 -r 4492a0285bae Config.mk
--- a/Config.mk Thu Jul 26 14:35:01 2007 -0600
+++ b/Config.mk Fri Jul 27 08:15:16 2007 -0600
@@ -81,14 +81,6 @@ CFLAGS += $(foreach i, $(EXTRA_INCLUDES)
 #        n - Do not build the Xen ACM framework
 ACM_SECURITY ?= n
 
-# If ACM_SECURITY = y and no boot policy file is installed,
-# then the ACM defaults to the security policy set by
-# ACM_DEFAULT_SECURITY_POLICY
-# Supported models are:
-#      ACM_NULL_POLICY
-#      ACM_CHINESE_WALL_AND_SIMPLE_TYPE_ENFORCEMENT_POLICY
-ACM_DEFAULT_SECURITY_POLICY ?= ACM_NULL_POLICY
-
 # Optional components
 XENSTAT_XENTOP     ?= y
 VTPM_TOOLS         ?= n
diff -r 37833b33ae77 -r 4492a0285bae buildconfigs/enable-xen-config
--- a/buildconfigs/enable-xen-config    Thu Jul 26 14:35:01 2007 -0600
+++ b/buildconfigs/enable-xen-config    Fri Jul 27 08:15:16 2007 -0600
@@ -28,9 +28,13 @@ setopt CONFIG_PARAVIRT y
 setopt CONFIG_PARAVIRT y
 setopt CONFIG_XEN y
 setopt CONFIG_VMI y
+setopt CONFIG_KVM y
+setopt CONFIG_KVM_INTEL y
+setopt CONFIG_KVM_AMD y
 setopt CONFIG_LGUEST n
 setopt CONFIG_XEN_BLKDEV_FRONTEND y
 setopt CONFIG_XEN_NETDEV_FRONTEND y
 setopt CONFIG_HVC_XEN y
+setopt CONFIG_NUMA n
 
 exit 0
diff -r 37833b33ae77 -r 4492a0285bae buildconfigs/mk.linux-2.6
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/buildconfigs/mk.linux-2.6 Fri Jul 27 08:15:16 2007 -0600
@@ -0,0 +1,14 @@
+XEN_LINUX_SOURCE ?= tarball
+LINUX_VER ?= 2.6
+
+XEN_LINUX_TARBALL_KETCHUP := y
+
+IMAGE_TARGET ?= vmlinux bzImage
+
+XEN_LINUX_ALLOW_INTERFACE_MISMATCH := y
+
+XEN_LINUX_CONFIG_UPDATE := buildconfigs/enable-xen-config
+
+EXTRAVERSION ?=
+
+include buildconfigs/mk.linux-2.6-xen
diff -r 37833b33ae77 -r 4492a0285bae buildconfigs/mk.linux-2.6-git
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/buildconfigs/mk.linux-2.6-git     Fri Jul 27 08:15:16 2007 -0600
@@ -0,0 +1,2 @@
+LINUX_VER ?= 2.6-git
+include buildconfigs/mk.linux-2.6
diff -r 37833b33ae77 -r 4492a0285bae buildconfigs/mk.linux-2.6-mm
--- a/buildconfigs/mk.linux-2.6-mm      Thu Jul 26 14:35:01 2007 -0600
+++ b/buildconfigs/mk.linux-2.6-mm      Fri Jul 27 08:15:16 2007 -0600
@@ -1,14 +1,2 @@ XEN_LINUX_SOURCE ?= tarball
-XEN_LINUX_SOURCE ?= tarball
 LINUX_VER ?= 2.6-mm
-
-XEN_LINUX_TARBALL_KETCHUP := y
-
-IMAGE_TARGET ?= vmlinux bzImage
-
-XEN_LINUX_ALLOW_INTERFACE_MISMATCH := y
-
-XEN_LINUX_CONFIG_UPDATE := buildconfigs/enable-xen-config
-
-EXTRAVERSION ?=
-
-include buildconfigs/mk.linux-2.6-xen
+include buildconfigs/mk.linux-2.6
diff -r 37833b33ae77 -r 4492a0285bae buildconfigs/mk.linux-2.6-rc
--- a/buildconfigs/mk.linux-2.6-rc      Thu Jul 26 14:35:01 2007 -0600
+++ b/buildconfigs/mk.linux-2.6-rc      Fri Jul 27 08:15:16 2007 -0600
@@ -1,14 +1,2 @@ XEN_LINUX_SOURCE ?= tarball
-XEN_LINUX_SOURCE ?= tarball
 LINUX_VER ?= 2.6-rc
-
-XEN_LINUX_TARBALL_KETCHUP := y
-
-IMAGE_TARGET ?= vmlinux bzImage
-
-XEN_LINUX_ALLOW_INTERFACE_MISMATCH := y
-
-XEN_LINUX_CONFIG_UPDATE := buildconfigs/enable-xen-config
-
-EXTRAVERSION ?=
-
-include buildconfigs/mk.linux-2.6-xen
+include buildconfigs/mk.linux-2.6
diff -r 37833b33ae77 -r 4492a0285bae buildconfigs/mk.linux-2.6-tip
--- a/buildconfigs/mk.linux-2.6-tip     Thu Jul 26 14:35:01 2007 -0600
+++ b/buildconfigs/mk.linux-2.6-tip     Fri Jul 27 08:15:16 2007 -0600
@@ -1,14 +1,2 @@ XEN_LINUX_SOURCE ?= tarball
-XEN_LINUX_SOURCE ?= tarball
 LINUX_VER ?= 2.6-tip
-
-XEN_LINUX_TARBALL_KETCHUP := y
-
-IMAGE_TARGET ?= vmlinux bzImage
-
-XEN_LINUX_ALLOW_INTERFACE_MISMATCH := y
-
-XEN_LINUX_CONFIG_UPDATE := buildconfigs/enable-xen-config
-
-EXTRAVERSION ?=
-
-include buildconfigs/mk.linux-2.6-xen
+include buildconfigs/mk.linux-2.6
diff -r 37833b33ae77 -r 4492a0285bae docs/man/xm.pod.1
--- a/docs/man/xm.pod.1 Thu Jul 26 14:35:01 2007 -0600
+++ b/docs/man/xm.pod.1 Fri Jul 27 08:15:16 2007 -0600
@@ -822,13 +822,15 @@ described under "Configuring Security" b
 described under "Configuring Security" below. There, you will find
 also examples of each subcommand described here.
 
-=item B<makepolicy> I<policy>
-
-Compiles the XML source representation of the security I<policy>. It
-creates a mapping (.map) as well as a binary (.bin) version of the
-policy. The compiled policy can be loaded into Xen with the
-B<loadpolicy> subcommand or can be configured to be loaded at boot
-time with the B<cfgbootpolicy> subcommand.
+=item B<setpolicy> ACM I<policy> I<[--load|--boot]>
+
+Makes the given ACM policy available to xend as a I<xend-managed policy>.
+The policy is compiled and a mapping (.map) as well as a binary (.bin)
+version of the policy is created. If the option I<--load> is provided
+the policy is loaded into Xen. If the option I<--boot> is provided the
+system is configure to be loaded with the policy at boot time. If these
+options are not provided with the B<setpolicy> subcommand, the
+B<activatepolicy> subcommand provides this functionality.
 
 =over 4
 
@@ -843,18 +845,26 @@ global policy root directory.
 
 =back
 
-=item B<loadpolicy> I<policy>
-
-Loads the binary representation of the I<policy> into Xen. The binary
-representation can be created with the B<makepolicy> subcommand.
-
-=item B<cfgbootpolicy> I<policy> [I<boot title>]
-
-Configures I<policy> as the boot policy for Xen. It copies the binary
-policy representation into the /boot directory and adds a module line
-specifying the binary policy to the /boot/grub/menu.lst file. If your
-boot configuration includes multiple Xen boot titles, then use the
-I<boot title> parameter to specify a unique part of the proper title.
+=item B<activatepolicy> I<[--load|--boot]>
+
+Activates the xend-managed policy by loading it into Xen using the
+I<--load> option or configures the system to boot with the
+xend-managed policy during the next reboot as a result of the
+I<--boot> option. The latter is only supported if the system is booted
+with the grub boot loader and the default boot title is modified.
+It copies the binary policy representation into the /boot directory and
+adds a module line specifying the binary policy to the /boot/grub/menu.lst
+or /boot/grub/grub.conf file.
+
+=item B<getpolicy> [--dumpxml]
+
+Displays information about the current xend-managed policy, such as
+name and type of the policy, the uuid xend has assigned to it on the
+local system, the version of the XML representation and the status
+of the policy, such as whether it is currently loaded into Xen or
+whether the policy is automatically loaded during system boot. With
+the I<--dumpxml> option, the XML representation of the policy is
+displayed.
 
 =item B<dumppolicy>
 
@@ -869,28 +879,47 @@ is 'dom'. The labels are arranged in alp
 
 =item B<addlabel> I<label> B<dom> I<configfile> [I<policy>]
 
+=item B<addlabel> I<label> B<mgt> I<domain name> [I<policy type>:I<policy>]
+
 =item B<addlabel> I<label> B<res> I<resource> [I<policy>]
 
+=item B<addlabel> I<label> B<vif-idx> I<domain name> [I<policy type>:I<policy>]
+
+
 Adds the security label with name I<label> to a domain
-I<configfile> (dom) or to the global resource label file for the
-given I<resource> (res). Unless specified, the default I<policy> is the
-currently enforced access control policy. This subcommand also
-verifies that the I<policy> definition supports the specified I<label>
-name.
+I<configfile> (dom), a Xend-managed domain (mgt), to the global resource label
+file for the given I<resource> (res), or to a managed domain's virtual network
+interface (vif) that is specified by its index. Unless specified,
+the default I<policy> is the currently enforced access control policy.
+This subcommand also verifies that the I<policy> definition supports the
+specified I<label> name.
+
+The only I<policy type> that is currently supported is I<ACM>.
 
 =item B<rmlabel> B<dom> I<configfile>
 
+=item B<rmlabel> B<mgt> I<domain name>
+
 =item B<rmlabel> B<res> I<resource>
 
+=item B<rmlabel> B<vif-idx> I<domain name>
+
 Works the same as the B<addlabel> command (above), except that this
-command will remove the label from the domain I<configfile> (dom) or
-the global resource label file (res).
+command will remove the label from the domain I<configfile> (dom),
+a Xend-managed domain (mgt), the global resource label file (res),
+or a managed domain's network interface (vif).
 
 =item B<getlabel> B<dom> I<configfile>
 
+=item B<getlabel> B<mgt> I<domain name>
+
 =item B<getlabel> B<res> I<resource>
 
-Shows the label for the given I<configfile> or I<resource>
+=item B<getlabel> B<vif-idx> I<domain name>
+
+Shows the label for a domain's configuration in the given I<configfile>,
+a xend-managed domain (mgt), a resource, or a managed domain's network
+interface (vif).
 
 =item B<resources>
 
@@ -908,12 +937,9 @@ B<CONFIGURING SECURITY>
 
 =over 4
 
-In xen_source_dir/Config.mk set the following parameters:
+In xen_source_dir/Config.mk set the following parameter:
 
     ACM_SECURITY ?= y
-    ACM_DEFAULT_SECURITY_POLICY ?= \
-        ACM_CHINESE_WALL_AND_SIMPLE_TYPE_ENFORCEMENT_POLICY
-
 Then recompile and install xen and the security tools and then reboot:
 
     cd xen_source_dir/xen; make clean; make; cp xen.gz /boot;
@@ -922,26 +948,26 @@ Then recompile and install xen and the s
 
 =back
 
-B<COMPILING A SECURITY POLICY>
-
-=over 4
-
-This step creates client_v1.map and client_v1.bin files in
-/etc/xen/acm-security/policies/example/chwall_ste.
-
-    xm makepolicy example.chwall_ste.client_v1
-
-=back
-
-B<LOADING A SECURITY POLICY>
-
-=over 4
-
-This step activates client_v1.bin as new security policy in Xen. You
-can use the dumppolicy subcommand before and afterwards to see the
+B<SETTING A SECURITY POLICY>
+
+=over 4
+
+This step makes the policy available to xend and creates the client_v1.map and
+client_v1.bin files in /etc/xen/acm-security/policies/example/chwall_ste.
+
+    xm setpolicy ACM example.client_v1
+
+=back
+
+B<ACTIVATING THE XEND-MANAGED SECURITY POLICY>
+
+=over 4
+
+This step activates the xend-manged policy as new security policy in Xen.
+You can use the dumppolicy subcommand before and afterwards to see the
 change in the Xen policy state.
 
-    xm loadpolicy example.chwall_ste.client_v1
+    xm activatpolicy --load
 
 =back
 
@@ -949,11 +975,11 @@ B<CONFIGURING A BOOT SECURITY POLICY>
 
 =over 4
 
-This configures the boot loader to load client_v1.bin at boot
-time. During system start, the ACM configures Xen with this policy and
+This configures the boot loader to load the current xend-managed policy at
+boot time. During system start, the ACM configures Xen with this policy and
 Xen enforces this policy from then on.
 
-    xm cfgbootpolicy example.chwall_ste.client_v1
+    xm activatepolicy --boot
 
 =back
 
@@ -964,7 +990,7 @@ This subcommand shows all labels that ar
 This subcommand shows all labels that are defined and which can be
 attached to domains.
 
-    xm labels example.chwall_ste.client_v1 type=dom
+    xm labels example.client_v1 type=dom
 
 will print for our example policy:
 
@@ -1019,6 +1045,28 @@ permitted".
 
 =back
 
+B<ATTACHING A SECURITY LABEL TO A XEND-MANAGED DOMAIN>
+
+=over 4
+
+The addlabel subcommand supports labeling of domains that are managed
+by xend. This includes domains that are currently running, such as for
+example Domain-0, or those that are in a dormant state.
+Depending on the state of the system, it is possible that the new label
+is rejected. An example for a reason for the rejection of the relabeling
+of a domain would be if a domain is currently allowed to
+access its labeled resources but due to the new label would be prevented
+from accessing one or more of them.
+
+    xm addlabel dom_Fun mgt Domain-0
+
+This changes the label of Domain-0 to dom_Fun under the condition that
+this new label of Domain-0 would not prevent any other domain from
+accessing its resources that are provided through Domain-0, such as for
+example network or block device access.
+
+=back
+
 B<ATTACHING A SECURITY LABEL TO A RESOURCE>
 
 =over 4
@@ -1072,9 +1120,11 @@ B<LISTING LABELED RESOURCES>
     xm resources
 
       phy:hda6
+            type: ACM
           policy: example.chwall_ste.client_v1
           label:  res_LogicalDiskPartition1(hda1)
       file:/xen/disk_image/disk.img
+            type: ACM
           policy: example.chwall_ste.client_v1
           label:  res_LogicalDiskPartition2(hda2)
 
@@ -1094,19 +1144,19 @@ The XML version is the version that user
 The XML version is the version that users are supposed to create or
 change, either by manually editing the XML file or by using the Xen
 policy generation tool (B<xensec_gen>). After changing the XML file,
-run the B<makepolicy> subcommand to ensure that these changes are
-reflected in the other versions. Use, for example, the subcommand
-B<cfgbootpolicy> to activate the changes during the next system
+run the B<setpolicy> subcommand to ensure that the new policy is
+available to xend. Use, for example, the subcommand
+B<activatepolicy> to activate the changes during the next system
 reboot.
 
 The binary version of the policy is derived from the XML policy by
 tokenizing the specified labels and is used inside Xen only. It is
-created with the B<makepolicy> subcommand. Essentially, the binary
+created with the B<setpolicy> subcommand. Essentially, the binary
 version is much more compact than the XML version and is easier to
 evaluate during access control decisions.
 
 The mapping version of the policy is created during the XML-to-binary
-policy translation (B<makepolicy>) and is used by the Xen management
+policy translation (B<setpolicy>) and is used by xend and the management
 tools to translate between label names used as input to the tools and
 their binary identifiers (ssidrefs) used inside Xen.
 
@@ -1121,5 +1171,6 @@ B<xmdomain.cfg>(5), B<xentop>(1)
   Sean Dague <sean at dague dot net>
   Daniel Stekloff <dsteklof at us dot ibm dot com>
   Reiner Sailer <sailer at us dot ibm dot com>
+  Stefan Berger <stefanb at us dot ibm dot com>
 
 =head1 BUGS
diff -r 37833b33ae77 -r 4492a0285bae docs/xen-api/xenapi-datamodel-graph.dot
--- a/docs/xen-api/xenapi-datamodel-graph.dot   Thu Jul 26 14:35:01 2007 -0600
+++ b/docs/xen-api/xenapi-datamodel-graph.dot   Fri Jul 27 08:15:16 2007 -0600
@@ -12,7 +12,7 @@ digraph "Xen-API Class Diagram" {
 digraph "Xen-API Class Diagram" {
 fontname="Verdana";
 
-node [ shape=box ]; session VM host network VIF PIF SR VDI VBD PBD user;
+node [ shape=box ]; session VM host network VIF PIF SR VDI VBD PBD user 
XSPolicy ACMPolicy;
 node [shape=ellipse]; PIF_metrics VIF_metrics VM_metrics VBD_metrics 
PBD_metrics VM_guest_metrics host_metrics;
 node [shape=box]; host_cpu console
 session -> host [ arrowhead="none" ]
@@ -36,4 +36,6 @@ VBD -> VM [ arrowhead="none", arrowtail=
 VBD -> VM [ arrowhead="none", arrowtail="crow" ]
 VTPM -> VM [ arrowhead="none", arrowtail="crow" ]
 VBD -> VBD_metrics [ arrowhead="none" ]
+XSPolicy -> host [ arrowhead="none" ]
+XSPolicy -> ACMPolicy [ arrowhead="none" ]
 }
diff -r 37833b33ae77 -r 4492a0285bae docs/xen-api/xenapi-datamodel.tex
--- a/docs/xen-api/xenapi-datamodel.tex Thu Jul 26 14:35:01 2007 -0600
+++ b/docs/xen-api/xenapi-datamodel.tex Fri Jul 27 08:15:16 2007 -0600
@@ -46,6 +46,8 @@ Name & Description \\
 {\tt console} & A console \\
 {\tt user} & A user of the system \\
 {\tt debug} & A basic class for testing \\
+{\tt XSPolicy} & A class for handling Xen Security Policies \\
+{\tt ACMPolicy} & A class for handling ACM-type policies \\
 \hline
 \end{tabular}\end{center}
 \section{Relationships Between Classes}
@@ -225,6 +227,261 @@ The following enumeration types are used
 \end{longtable}
 
 \vspace{1cm}
+\newpage
+
+\section{Error Handling}
+When a low-level transport error occurs, or a request is malformed at the HTTP
+or XML-RPC level, the server may send an XML-RPC Fault response, or the client
+may simulate the same.  The client must be prepared to handle these errors,
+though they may be treated as fatal.  On the wire, these are transmitted in a
+form similar to this:
+
+\begin{verbatim}
+    <methodResponse>
+      <fault>
+        <value>
+          <struct>
+            <member>
+                <name>faultCode</name>
+                <value><int>-1</int></value>
+              </member>
+              <member>
+                <name>faultString</name>
+                <value><string>Malformed request</string></value>
+            </member>
+          </struct>
+        </value>
+      </fault>
+    </methodResponse>
+\end{verbatim}
+
+All other failures are reported with a more structured error response, to
+allow better automatic response to failures, proper internationalisation of
+any error message, and easier debugging.  On the wire, these are transmitted
+like this:
+
+\begin{verbatim}
+    <struct>
+      <member>
+        <name>Status</name>
+        <value>Failure</value>
+      </member>
+      <member>
+        <name>ErrorDescription</name>
+        <value>
+          <array>
+            <data>
+              <value>MAP_DUPLICATE_KEY</value>
+              <value>Customer</value>
+              <value>eSpeil Inc.</value>
+              <value>eSpeil Incorporated</value>
+            </data>
+          </array>
+        </value>
+      </member>
+    </struct>
+\end{verbatim}
+
+Note that {\tt ErrorDescription} value is an array of string values. The
+first element of the array is an error code; the remainder of the array are
+strings representing error parameters relating to that code.  In this case,
+the client has attempted to add the mapping {\tt Customer $\rightarrow$
+eSpiel Incorporated} to a Map, but it already contains the mapping
+{\tt Customer $\rightarrow$ eSpiel Inc.}, and so the request has failed.
+
+The reference below lists each possible error returned by each method.
+As well as the errors explicitly listed, any method may return low-level
+errors as described above, or any of the following generic errors:
+
+\begin{itemize}
+\item HANDLE\_INVALID
+\item INTERNAL\_ERROR
+\item MAP\_DUPLICATE\_KEY
+\item MESSAGE\_METHOD\_UNKNOWN
+\item MESSAGE\_PARAMETER\_COUNT\_MISMATCH
+\item OPERATION\_NOT\_ALLOWED
+\item PERMISSION\_DENIED
+\item SESSION\_INVALID
+\end{itemize}
+
+Each possible error code is documented in the following section.
+
+\subsection{Error Codes}
+
+\subsubsection{HANDLE\_INVALID}
+
+You gave an invalid handle.  The object may have recently been deleted. 
+The class parameter gives the type of reference given, and the handle
+parameter echoes the bad value given.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}HANDLE_INVALID(class, handle)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{INTERNAL\_ERROR}
+
+The server failed to handle your request, due to an internal error.  The
+given message may give details useful for debugging the problem.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}INTERNAL_ERROR(message)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{MAP\_DUPLICATE\_KEY}
+
+You tried to add a key-value pair to a map, but that key is already there. 
+The key, current value, and the new value that you tried to set are all
+echoed.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}MAP_DUPLICATE_KEY(key, current value, new value)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{MESSAGE\_METHOD\_UNKNOWN}
+
+You tried to call a method that does not exist.  The method name that you
+used is echoed.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}MESSAGE_METHOD_UNKNOWN(method)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{MESSAGE\_PARAMETER\_COUNT\_MISMATCH}
+
+You tried to call a method with the incorrect number of parameters.  The
+fully-qualified method name that you used, and the number of received and
+expected parameters are returned.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}MESSAGE_PARAMETER_COUNT_MISMATCH(method, expected, 
received)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{NETWORK\_ALREADY\_CONNECTED}
+
+You tried to create a PIF, but the network you tried to attach it to is
+already attached to some other PIF, and so the creation failed.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}NETWORK_ALREADY_CONNECTED(network, connected PIF)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{OPERATION\_NOT\_ALLOWED}
+
+You attempted an operation that was not allowed.
+
+\vspace{0.3cm}
+No parameters.
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{PERMISSION\_DENIED}
+
+You do not have the required permissions to perform the operation.
+
+\vspace{0.3cm}
+No parameters.
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{PIF\_IS\_PHYSICAL}
+
+You tried to destroy a PIF, but it represents an aspect of the physical
+host configuration, and so cannot be destroyed.  The parameter echoes the
+PIF handle you gave.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}PIF_IS_PHYSICAL(PIF)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{SESSION\_AUTHENTICATION\_FAILED}
+
+The credentials given by the user are incorrect, so access has been denied,
+and you have not been issued a session handle.
+
+\vspace{0.3cm}
+No parameters.
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{SESSION\_INVALID}
+
+You gave an invalid session handle.  It may have been invalidated by a
+server restart, or timed out.  You should get a new session handle, using
+one of the session.login\_ calls.  This error does not invalidate the
+current connection.  The handle parameter echoes the bad value given.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}SESSION_INVALID(handle)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{SESSION\_NOT\_REGISTERED}
+
+This session is not registered to receive events.  You must call
+event.register before event.next.  The session handle you are using is
+echoed.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}SESSION_NOT_REGISTERED(handle)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{VALUE\_NOT\_SUPPORTED}
+
+You attempted to set a value that is not supported by this implementation. 
+The fully-qualified field name and the value that you tried to set are
+returned.  Also returned is a developer-only diagnostic reason.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}VALUE_NOT_SUPPORTED(field, value, reason)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{VLAN\_TAG\_INVALID}
+
+You tried to create a VLAN, but the tag you gave was invalid -- it mmust be
+between 0 and 4095.  The parameter echoes the VLAN tag you gave.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}VLAN_TAG_INVALID(VLAN)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{VM\_BAD\_POWER\_STATE}
+
+You attempted an operation on a VM that was not in an appropriate power
+state at the time; for example, you attempted to start a VM that was
+already running.  The parameters returned are the VM's handle, and the
+expected and actual VM state at the time of the call.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}VM_BAD_POWER_STATE(vm, expected, actual)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{VM\_HVM\_REQUIRED}
+
+HVM is required for this operation
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}VM_HVM_REQUIRED(vm)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
+\subsubsection{SECURITY\_ERROR}
+
+A security error occurred. The parameter provides the xen security
+error code and a message describing the error.
+
+\vspace{0.3cm}
+{\bf Signature:}
+\begin{verbatim}SECURITY_ERROR(xserr, message)\end{verbatim}
+\begin{center}\rule{10em}{0.1pt}\end{center}
+
 
 \newpage
 \section{Class: session}
@@ -275,6 +532,11 @@ session ref
 
 
 ID of newly created session
+
+\vspace{0.3cm}
+
+\noindent{\bf Possible Error Codes:} {\tt SESSION\_AUTHENTICATION\_FAILED}
+
 \vspace{0.3cm}
 \vspace{0.3cm}
 \vspace{0.3cm}
@@ -1153,6 +1415,7 @@ Quals & Field & Type & Description \\
 $\mathit{RO}_\mathit{run}$ &  {\tt is\_control\_domain} & bool & true if this 
is a control domain (domain 0 or a driver domain) \\
 $\mathit{RO}_\mathit{run}$ &  {\tt metrics} & VM\_metrics ref & metrics 
associated with this VM \\
 $\mathit{RO}_\mathit{run}$ &  {\tt guest\_metrics} & VM\_guest\_metrics ref & 
metrics associated with the running guest \\
+$\mathit{RO}_\mathit{run}$ &  {\tt security/label} & string & the VM's 
security label \\
 \hline
 \end{longtable}
 \subsection{RPCs associated with class: VM}
@@ -4147,6 +4410,82 @@ VM\_guest\_metrics ref
 
 
 value of the field
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_security\_label}
+
+{\bf Overview:}
+Get the security label field of the given VM. Refer to the XSPolicy class
+for the format of the security label.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_security_label (session_id s, VM ref 
self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt VM ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+value of the field
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~set\_security\_label}
+
+{\bf Overview:}
+Set the security label field of the given VM. Refer to the XSPolicy class
+for the format of the security label.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} int set_security_label (session_id s, VM ref self, string
+security_label, string old_label)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt VM ref } & self & reference to the object \\ \hline
+{\tt string } & security\_label & security label for the VM \\ \hline
+{\tt string } & old\_label & Optional label value that the security label \\
+& & must currently have for the change to succeed.\\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+int
+}
+
+
+Returns the ssidref in case of an VM that is currently running or
+paused, zero in case of a dormant VM (halted, suspended).
+
+\vspace{0.3cm}
+
+\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
+
 \vspace{0.3cm}
 \vspace{0.3cm}
 \vspace{0.3cm}
@@ -7100,7 +7439,9 @@ value of the field
 \subsubsection{RPC name:~get\_flags}
 
 {\bf Overview:} 
-Get the flags field of the given host\_cpu.
+Get the flags field of the given host\_cpu.  As of this version of the
+API, the semantics of the returned string are explicitly unspecified,
+and may change in the future.
 
  \noindent {\bf Signature:} 
 \begin{verbatim} string get_flags (session_id s, host_cpu ref 
self)\end{verbatim}
@@ -7132,7 +7473,9 @@ value of the field
 \subsubsection{RPC name:~get\_features}
 
 {\bf Overview:} 
-Get the features field of the given host\_cpu.
+Get the features field of the given host\_cpu. As of this version of the
+API, the semantics of the returned string are explicitly unspecified,
+and may change in the future.
 
  \noindent {\bf Signature:} 
 \begin{verbatim} string get_features (session_id s, host_cpu ref 
self)\end{verbatim}
@@ -8634,6 +8977,79 @@ value of the field
 \vspace{0.3cm}
 \vspace{0.3cm}
 \vspace{0.3cm}
+\subsubsection{RPC name:~set\_security\_label}
+
+{\bf Overview:}
+Set the security label of the given VIF. Refer to the XSPolicy class
+for the format of the security label.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} void set_security_label (session_id s, VIF ref self, string
+security_label, string old_label)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt VIF ref } & self & reference to the object \\ \hline
+
+{\tt string } & security\_label & New value of the security label \\ \hline
+{\tt string } & old\_label & Optional label value that the security label \\
+& & must currently have for the change to succeed.\\ \hline
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+void
+}
+
+
+\vspace{0.3cm}
+
+\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
+
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_security\_label}
+
+{\bf Overview:}
+Get the security label of the given VIF.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_security_label (session_id s, VIF ref 
self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt VIF ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+value of the given field
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
 \subsubsection{RPC name:~create}
 
 {\bf Overview:} 
@@ -10382,6 +10798,7 @@ Quals & Field & Type & Description \\
 $\mathit{RW}$ &  {\tt sharable} & bool & true if this disk may be shared \\
 $\mathit{RW}$ &  {\tt read\_only} & bool & true if this disk may ONLY be 
mounted read-only \\
 $\mathit{RW}$ &  {\tt other\_config} & (string $\rightarrow$ string) Map & 
additional configuration \\
+$\mathit{RO}_\mathit{run}$ &  {\tt security/label} & string & the VM's 
security label \\
 \hline
 \end{longtable}
 \subsection{RPCs associated with class: VDI}
@@ -11062,6 +11479,79 @@ void
 
 
 
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~set\_security\_label}
+
+{\bf Overview:}
+Set the security label of the given VDI. Refer to the XSPolicy class
+for the format of the security label.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} void set_security_label (session_id s, VDI ref self, string
+security_label, string old_label)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt VDI ref } & self & reference to the object \\ \hline
+
+{\tt string } & security\_label & New value of the security label \\ \hline
+{\tt string } & old\_label & Optional label value that the security label \\
+& & must currently have for the change to succeed.\\ \hline
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+void
+}
+
+
+\vspace{0.3cm}
+
+\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
+
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_security\_label}
+
+{\bf Overview:}
+Get the security label of the given VDI.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_security_label (session_id s, VDI ref 
self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt VDI ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+value of the given field
 \vspace{0.3cm}
 \vspace{0.3cm}
 \vspace{0.3cm}
@@ -13172,6 +13662,38 @@ value of the field
 \vspace{0.3cm}
 \vspace{0.3cm}
 \vspace{0.3cm}
+\subsubsection{RPC name:~get\_runtime\_properties}
+
+{\bf Overview:}
+Get the runtime\_properties field of the given VTPM.
+
+\noindent {\bf Signature:}
+\begin{verbatim} ((string -> string) Map) get_runtime_properties (session_id 
s, VTPM ref self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt VTPM ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+(string $\rightarrow$ string) Map
+}
+
+
+value of the field
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
 \subsubsection{RPC name:~create}
 
 {\bf Overview:} 
@@ -14016,6 +14538,634 @@ all fields from the object
 \vspace{0.3cm}
 
 \vspace{1cm}
+\newpage
+\section{Class: XSPolicy}
+\subsection{Fields for class: XSPolicy}
+\begin{longtable}{|lllp{0.38\textwidth}|}
+\hline
+\multicolumn{1}{|l}{Name} & \multicolumn{3}{l|}{\bf XSPolicy} \\
+\multicolumn{1}{|l}{Description} & \multicolumn{3}{l|}{\parbox{11cm}{\em A Xen 
Security Policy}} \\
+\hline
+Quals & Field & Type & Description \\
+\hline
+$\mathit{RO}_\mathit{run}$ &  {\tt uuid} & string  & unique identifier / 
object reference \\
+$\mathit{RW}$              &  {\tt repr} & string  & representation of policy, 
i.e., XML \\
+$\mathit{RO}_\mathit{run}$ &  {\tt type} & xs\_type & type of the policy \\
+$\mathit{RO}_\mathit{run}$ & {\tt flags} & xs\_instantiationflags & policy
+status flags \\
+\hline
+\end{longtable}
+\subsection{Semantics of the class: XSPolicy}
+
+The XSPolicy class is used for administering Xen Security policies. Through
+this class a new policy can be uploaded to the system, loaded into the
+Xen hypervisor for enforcement and be set as the policy that the
+system is automatically loading when the machine is started.
+
+This class returns information about the currently administered policy,
+including a reference to the policy. This reference can then be used with
+policy-specific classes, i.e., the ACMPolicy class, to allow retrieval of
+information or changes to be made to a particular policy.
+
+\subsection{Structure and datatypes of class: XSPolicy}
+
+Format of the security label:
+
+A security label consist of the three different parts {\it policy type},
+{\it policy name} and {\it label} separated with colons. To specify
+the virtual machine label for an ACM-type policy {\it xm-test}, the
+security label string would be {\it ACM:xm-test:blue}, where blue
+denotes the virtual machine's label. The format of resource labels is
+the same.\\[0.5cm]
+The following flags are used by this class:
+
+\begin{longtable}{|l|l|l|}
+\hline
+{\tt xs\_type} & value & meaning \\
+\hline
+\hspace{0.5cm}{\tt XS\_POLICY\_ACM} & (1 $<<$ 0) & ACM-type policy \\
+\hline
+\end{longtable}
+
+\begin{longtable}{|l|l|l|}
+\hline
+{\tt xs\_instantiationflags} & value & meaning \\
+\hline
+\hspace{0.5cm}{\tt XS\_INST\_NONE} & 0 & do nothing \\
+\hspace{0.5cm}{\tt XS\_INST\_BOOT} & (1 $<<$ 0) & make system boot with this 
policy \\
+\hspace{0.5cm}{\tt XS\_INST\_LOAD} & (1 $<<$ 1) & load policy immediately \\
+\hline
+\end{longtable}
+
+\begin{longtable}{|l|l|l|}
+\hline
+{\tt xs\_policystate} & type & meaning \\
+\hline
+\hspace{0.5cm}{\tt xserr} & int & Error code from operation (if applicable) \\
+\hspace{0.5cm}{\tt xs\_ref}  & XSPolicy ref & reference to the XS policy as 
returned by the API \\
+\hspace{0.5cm}{\tt repr} & string & representation of the policy, i.e., XML \\
+\hspace{0.5cm}{\tt type} & xs\_type & the type of the policy \\
+\hspace{0.5cm}{\tt flags } & xs\_instantiationflags  & instantiation flags of 
the policy \\
+\hspace{0.5cm}{\tt version} & string & version of the policy \\
+\hspace{0.5cm}{\tt errors} & string & Base64-encoded sequence of integer 
tuples consisting \\
+& & of (error code, detail); will be returned as part  \\
+& & of the xs\_setpolicy function. \\
+\hline
+\end{longtable}
+
+\subsection{Additional RPCs associated with class: XSPolicy}
+\subsubsection{RPC name:~get\_xstype}
+
+{\bf Overview:}
+Return the Xen Security Policy types supported by this system
+
+ \noindent {\bf Signature:}
+\begin{verbatim} xs_type get_xstype (session_id s)\end{verbatim}
+
+ \noindent {\bf Return Type:}
+{\tt
+xs\_type
+}
+
+flags representing the supported Xen security policy types
+ \vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~set\_xspolicy}
+
+{\bf Overview:}
+Set the current XSPolicy. This function can also be be used for updating of
+an existing policy whose name must be equivalent to the one of the
+currently running policy.
+
+\noindent {\bf Signature:}
+\begin{verbatim} xs_policystate set_xspolicy (session_id s, xs_type type, 
string repr,
+xs_instantiationflags flags, bool overwrite)\end{verbatim}
+
+\noindent{\bf Arguments:}
+
+\vspace{0.3cm}
+
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt xs\_type } & type & the type of policy \\ \hline
+{\tt string} & repr & representation of the policy, i.e., XML \\ \hline
+{\tt xs\_instantiationflags}    & flags & flags for the setting of the policy 
\\ \hline
+{\tt bool}   & overwrite & whether to overwrite an existing policy \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+
+ \noindent {\bf Return Type:}
+{\tt
+xs\_policystate
+}
+
+
+State information about the policy. In case an error occurred, the 'xs\_err'
+field contains the error code. The 'errors' may contain further information
+about the error.
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_xspolicy}
+
+{\bf Overview:}
+Get information regarding the currently set Xen Security Policy
+
+ \noindent {\bf Signature:}
+\begin{verbatim} xs_policystate get_xspolicy (session_id s)\end{verbatim}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+xs\_policystate
+}
+
+
+Policy state information.
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~rm\_xsbootpolicy}
+
+{\bf Overview:}
+Remove any policy from the default boot configuration.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} void rm_xsbootpolicy (session_id s)\end{verbatim}
+
+\vspace{0.3cm}
+
+\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
+
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_labeled\_resources}
+
+{\bf Overview:}
+Get a list of resources that have been labeled.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} ((string -> string) Map) get_labeled_resources (session_id 
s)\end{verbatim}
+
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+(string $\rightarrow$ string) Map
+}
+
+
+A map of resources with their labels.
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~set\_resource\_label}
+
+{\bf Overview:}
+Label the given resource with the given label. An empty label removes any label
+from the resource.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} void set_resource_label (session_id s, string resource, string
+label, string old_label)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt string } & resource & resource to label \\ \hline
+{\tt string } & label & label for the resource \\ \hline
+{\tt string } & old\_label & Optional label value that the security label \\
+& & must currently have for the change to succeed. \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
+
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_resource\_label}
+
+{\bf Overview:}
+Get the label of the given resource.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_resource_label (session_id s, string 
resource)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt string } & resource & resource to label \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+The label of the given resource.
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~activate\_xspolicy}
+
+{\bf Overview:}
+Load the referenced policy into the hypervisor.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} xs_instantiationflags activate_xspolicy (session_id s, xs_ref 
xspolicy,
+xs_instantiationflags flags)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt xs ref } & self & reference to the object \\ \hline
+{\tt xs\_instantiationflags } & flags & flags to activate on a policy; flags
+  can only be set \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+
+ \noindent {\bf Return Type:}
+{\tt
+xs\_instantiationflags
+}
+
+
+Currently active instantiation flags.
+\vspace{0.3cm}
+
+\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
+
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_all}
+
+{\bf Overview:}
+Return a list of all the XSPolicies known to the system.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} ((XSPolicy ref) Set) get_all (session_id s)\end{verbatim}
+
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+(XSPolicy ref) Set
+}
+
+
+A list of all the IDs of all the XSPolicies
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_uuid}
+
+{\bf Overview:}
+Get the uuid field of the given XSPolicy.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_uuid (session_id s, XSPolicy ref 
self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt XSPolicy ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+value of the field
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_record}
+
+{\bf Overview:}
+Get a record of the referenced XSPolicy.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} (XSPolicy record) get_record (session_id s, xs_ref 
xspolicy)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt xs ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+XSPolicy record
+}
+
+
+all fields from the object
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\newpage
+\section{Class: ACMPolicy}
+\subsection{Fields for class: ACMPolicy}
+\begin{longtable}{|lllp{0.38\textwidth}|}
+\hline
+\multicolumn{1}{|l}{Name} & \multicolumn{3}{l|}{\bf ACMPolicy} \\
+\multicolumn{1}{|l}{Description} & \multicolumn{3}{l|}{\parbox{11cm}{\em An 
ACM Security Policy}} \\
+\hline
+Quals & Field & Type & Description \\
+\hline
+$\mathit{RO}_\mathit{run}$ &  {\tt uuid} & string & unique identifier / object 
reference \\
+$\mathit{RW}$              &  {\tt repr} & string & representation of policy, 
in XML \\
+$\mathit{RO}_\mathit{run}$ &  {\tt type} & xs\_type & type of the policy \\
+$\mathit{RO}_\mathit{run}$ & {\tt flags} & xs\_instantiationflags & policy
+status flags \\
+\hline
+\end{longtable}
+
+\subsection{Structure and datatypes of class: ACMPolicy}
+
+\vspace{0.5cm}
+The following data structures are used:
+
+\begin{longtable}{|l|l|l|}
+\hline
+{\tt RIP acm\_policyheader} & type & meaning \\
+\hline
+\hspace{0.5cm}{\tt policyname}   & string & name of the policy \\
+\hspace{0.5cm}{\tt policyurl }   & string & URL of the policy \\
+\hspace{0.5cm}{\tt date}         & string & data of the policy \\
+\hspace{0.5cm}{\tt reference}    & string & reference of the policy \\
+\hspace{0.5cm}{\tt namespaceurl} & string & namespaceurl of the policy \\
+\hspace{0.5cm}{\tt version}      & string & version of the policy \\
+\hline
+\end{longtable}
+
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_header}
+
+{\bf Overview:}
+Get the referenced policy's header information.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} acm_policyheader get_header (session_id s, xs ref 
self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt xs ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+acm\_policyheader
+}
+
+
+The policy's header information.
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_xml}
+
+{\bf Overview:}
+Get the XML representation of the given policy.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_XML (session_id s, xs ref self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt xs ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+XML representation of the referenced policy
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_map}
+
+{\bf Overview:}
+Get the mapping information of the given policy.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_map (session_id s, xs ref self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt xs ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+Mapping information of the referenced policy.
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_binary}
+
+{\bf Overview:}
+Get the binary policy representation of the referenced policy.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_map (session_id s, xs ref self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt xs ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+Base64-encoded representation of the binary policy.
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_all}
+
+{\bf Overview:}
+Return a list of all the ACMPolicies known to the system.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} ((ACMPolicy ref) Set) get_all (session_id s)\end{verbatim}
+
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+(ACMPolicy ref) Set
+}
+
+
+A list of all the IDs of all the ACMPolicies
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_uuid}
+
+{\bf Overview:}
+Get the uuid field of the given ACMPolicy.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} string get_uuid (session_id s, ACMPolicy ref 
self)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt ACMPolicy ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+string
+}
+
+
+value of the field
+\vspace{0.3cm}
+\vspace{0.3cm}
+\vspace{0.3cm}
+\subsubsection{RPC name:~get\_record}
+
+{\bf Overview:}
+Get a record of the referenced ACMPolicy.
+
+ \noindent {\bf Signature:}
+\begin{verbatim} (XSPolicy record) get_record (session_id s, xs_ref 
xspolicy)\end{verbatim}
+
+
+\noindent{\bf Arguments:}
+
+
+\vspace{0.3cm}
+\begin{tabular}{|c|c|p{7cm}|}
+ \hline
+{\bf type} & {\bf name} & {\bf description} \\ \hline
+{\tt xs ref } & self & reference to the object \\ \hline
+
+\end{tabular}
+
+\vspace{0.3cm}
+
+ \noindent {\bf Return Type:}
+{\tt
+XSPolicy record
+}
+
+
+all fields from the object
+
 \newpage
 \section{Class: debug}
 \subsection{Fields for class: debug}
@@ -14192,224 +15342,3 @@ all fields from the object
 \vspace{0.3cm}
 \vspace{0.3cm}
 
-\vspace{1cm}
-\newpage
-\section{Error Handling}
-When a low-level transport error occurs, or a request is malformed at the HTTP
-or XML-RPC level, the server may send an XML-RPC Fault response, or the client
-may simulate the same.  The client must be prepared to handle these errors,
-though they may be treated as fatal.  On the wire, these are transmitted in a
-form similar to this:
-
-\begin{verbatim}
-    <methodResponse>
-      <fault>
-        <value>
-          <struct>
-            <member>
-                <name>faultCode</name>
-                <value><int>-1</int></value>
-              </member>
-              <member>
-                <name>faultString</name>
-                <value><string>Malformed request</string></value>
-            </member>
-          </struct>
-        </value>
-      </fault>
-    </methodResponse>
-\end{verbatim}
-
-All other failures are reported with a more structured error response, to
-allow better automatic response to failures, proper internationalisation of
-any error message, and easier debugging.  On the wire, these are transmitted
-like this:
-
-\begin{verbatim}
-    <struct>
-      <member>
-        <name>Status</name>
-        <value>Failure</value>
-      </member>
-      <member>
-        <name>ErrorDescription</name>
-        <value>
-          <array>
-            <data>
-              <value>MAP_DUPLICATE_KEY</value>
-              <value>Customer</value>
-              <value>eSpeil Inc.</value>
-              <value>eSpeil Incorporated</value>
-            </data>
-          </array>
-        </value>
-      </member>
-    </struct>
-\end{verbatim}
-
-Note that {\tt ErrorDescription} value is an array of string values. The
-first element of the array is an error code; the remainder of the array are
-strings representing error parameters relating to that code.  In this case,
-the client has attempted to add the mapping {\tt Customer $\rightarrow$
-eSpiel Incorporated} to a Map, but it already contains the mapping
-{\tt Customer $\rightarrow$ eSpiel Inc.}, and so the request has failed.
-
-Each possible error code is documented in the following section.
-
-\subsection{Error Codes}
-
-\subsubsection{HANDLE\_INVALID}
-
-You gave an invalid handle.  The object may have recently been deleted. 
-The class parameter gives the type of reference given, and the handle
-parameter echoes the bad value given.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}HANDLE_INVALID(class, handle)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{INTERNAL\_ERROR}
-
-The server failed to handle your request, due to an internal error.  The
-given message may give details useful for debugging the problem.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}INTERNAL_ERROR(message)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{MAP\_DUPLICATE\_KEY}
-
-You tried to add a key-value pair to a map, but that key is already there. 
-The key, current value, and the new value that you tried to set are all
-echoed.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}MAP_DUPLICATE_KEY(key, current value, new value)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{MESSAGE\_METHOD\_UNKNOWN}
-
-You tried to call a method that does not exist.  The method name that you
-used is echoed.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}MESSAGE_METHOD_UNKNOWN(method)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{MESSAGE\_PARAMETER\_COUNT\_MISMATCH}
-
-You tried to call a method with the incorrect number of parameters.  The
-fully-qualified method name that you used, and the number of received and
-expected parameters are returned.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}MESSAGE_PARAMETER_COUNT_MISMATCH(method, expected, 
received)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{NETWORK\_ALREADY\_CONNECTED}
-
-You tried to create a PIF, but the network you tried to attach it to is
-already attached to some other PIF, and so the creation failed.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}NETWORK_ALREADY_CONNECTED(network, connected PIF)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{OPERATION\_NOT\_ALLOWED}
-
-You attempted an operation that was not allowed.
-
-\vspace{0.3cm}
-No parameters.
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{PIF\_IS\_PHYSICAL}
-
-You tried to destroy a PIF, but it represents an aspect of the physical
-host configuration, and so cannot be destroyed.  The parameter echoes the
-PIF handle you gave.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}PIF_IS_PHYSICAL(PIF)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{SESSION\_AUTHENTICATION\_FAILED}
-
-The credentials given by the user are incorrect, so access has been denied,
-and you have not been issued a session handle.
-
-\vspace{0.3cm}
-No parameters.
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{SESSION\_INVALID}
-
-You gave an invalid session handle.  It may have been invalidated by a
-server restart, or timed out.  You should get a new session handle, using
-one of the session.login\_ calls.  This error does not invalidate the
-current connection.  The handle parameter echoes the bad value given.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}SESSION_INVALID(handle)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{SESSION\_NOT\_REGISTERED}
-
-This session is not registered to receive events.  You must call
-event.register before event.next.  The session handle you are using is
-echoed.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}SESSION_NOT_REGISTERED(handle)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{VALUE\_NOT\_SUPPORTED}
-
-You attempted to set a value that is not supported by this implementation. 
-The fully-qualified field name and the value that you tried to set are
-returned.  Also returned is a developer-only diagnostic reason.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}VALUE_NOT_SUPPORTED(field, value, reason)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{VLAN\_TAG\_INVALID}
-
-You tried to create a VLAN, but the tag you gave was invalid -- it mmust be
-between 0 and 4095.  The parameter echoes the VLAN tag you gave.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}VLAN_TAG_INVALID(VLAN)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{VM\_BAD\_POWER\_STATE}
-
-You attempted an operation on a VM that was not in an appropriate power
-state at the time; for example, you attempted to start a VM that was
-already running.  The parameters returned are the VM's handle, and the
-expected and actual VM state at the time of the call.
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}VM_BAD_POWER_STATE(vm, expected, actual)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
-
-\subsubsection{VM\_HVM\_REQUIRED}
-
-HVM is required for this operation
-
-\vspace{0.3cm}
-{\bf Signature:}
-\begin{verbatim}VM_HVM_REQUIRED(vm)\end{verbatim}
-\begin{center}\rule{10em}{0.1pt}\end{center}
diff -r 37833b33ae77 -r 4492a0285bae tools/examples/vtpm-common.sh
--- a/tools/examples/vtpm-common.sh     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/examples/vtpm-common.sh     Fri Jul 27 08:15:16 2007 -0600
@@ -20,7 +20,7 @@ dir=$(dirname "$0")
 . "$dir/logging.sh"
 . "$dir/locking.sh"
 
-VTPMDB="/etc/xen/vtpm.db"
+VTPMDB="/var/vtpm/vtpm.db"
 
 #In the vtpm-impl file some commands should be defined:
 #      vtpm_create, vtpm_setup, vtpm_start, etc. (see below)
@@ -241,12 +241,21 @@ function vtpm_get_create_reason () {
 # If no entry in the TPM database is found, the instance is
 # created and an entry added to the database.
 function vtpm_create_instance () {
-       local res instance domname reason
-       domname=$(xenstore_read "$XENBUS_PATH"/domain)
+       local res instance domname reason uuid
+       uuid=$(xenstore_read "$XENBUS_PATH"/uuid)
        reason=$(vtpm_get_create_reason)
 
        claim_lock vtpmdb
-       instance=$(vtpmdb_find_instance $domname)
+
+       instance="0"
+
+       if [ "$uuid" != "" ]; then
+               instance=$(vtpmdb_find_instance $uuid)
+       fi
+       if [ "$instance" == "0" ]; then
+               domname=$(xenstore_read "$XENBUS_PATH"/domain)
+               instance=$(vtpmdb_find_instance $domname)
+       fi
 
        if [ "$instance" == "0" -a "$reason" != "create" ]; then
                release_lock vtpmdb
@@ -268,7 +277,11 @@ function vtpm_create_instance () {
                vtpm_create $instance
 
                if [ $vtpm_fatal_error -eq 0 ]; then
-                       vtpmdb_add_instance $domname $instance
+                       if [ "$uuid" != "" ]; then
+                               vtpmdb_add_instance $uuid $instance
+                       else
+                               vtpmdb_add_instance $domname $instance
+                       fi
                fi
        else
                if [ "$reason" == "resume" ]; then
@@ -288,22 +301,29 @@ function vtpm_create_instance () {
 #Since it is assumed that the VM will appear again, the
 #entry is kept in the VTPMDB file.
 function vtpm_remove_instance () {
-       local instance reason domname
+       local instance reason domname uuid
        #Stop script execution quietly if path does not exist (anymore)
        xenstore-exists "$XENBUS_PATH"/domain
-       domname=$(xenstore_read "$XENBUS_PATH"/domain)
-
-       if [ "$domname" != "" ]; then
-               claim_lock vtpmdb
-
+       uuid=$(xenstore_read "$XENBUS_PATH"/uuid)
+
+       claim_lock vtpmdb
+
+       instance="0"
+
+       if [ "$uuid != "" ]; then
+               instance=$(vtpmdb_find_instance $uuid)
+       fi
+
+       if [ "$instance == "0" ]; then
+               domname=$(xenstore_read "$XENBUS_PATH"/domain)
                instance=$(vtpmdb_find_instance $domname)
-
-               if [ "$instance" != "0" ]; then
-                       vtpm_suspend $instance
-               fi
-
-               release_lock vtpmdb
-       fi
+       fi
+
+       if [ "$instance" != "0" ]; then
+               vtpm_suspend $instance
+       fi
+
+       release_lock vtpmdb
 }
 
 
diff -r 37833b33ae77 -r 4492a0285bae tools/firmware/hvmloader/acpi/dsdt.asl
--- a/tools/firmware/hvmloader/acpi/dsdt.asl    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/firmware/hvmloader/acpi/dsdt.asl    Fri Jul 27 08:15:16 2007 -0600
@@ -123,11 +123,12 @@ DefinitionBlock ("DSDT.aml", "DSDT", 2, 
             }
 
             Name(BUFA, ResourceTemplate() {
-                IRQ(Level, ActiveLow, Shared) { 5, 7, 10, 11 }
+                IRQ(Level, ActiveLow, Shared) { 5, 10, 11 }
             })
 
             Name(BUFB, Buffer() {
-                0x23, 0x00, 0x00, 0x18, 0x79, 0
+                0x23, 0x00, 0x00, 0x18, /* IRQ descriptor */
+                0x79, 0                 /* End tag, null checksum */
             })
 
             CreateWordField(BUFB, 0x01, IRQV)
@@ -643,6 +644,22 @@ DefinitionBlock ("DSDT.aml", "DSDT", 2, 
                         IRQNoFlags () {4}
                     })
                 }
+
+                Device (LTP1)
+                {
+                    Name (_HID, EisaId ("PNP0400"))
+                    Name (_UID, 0x02)
+                    Method (_STA, 0, NotSerialized)
+                    {
+                        Return (0x0F)
+                    }
+
+                    Name (_CRS, ResourceTemplate()
+                    {
+                        IO (Decode16, 0x0378, 0x0378, 0x08, 0x08)
+                        IRQNoFlags () {7}
+                    })
+                } 
             }
         }
     }
diff -r 37833b33ae77 -r 4492a0285bae tools/firmware/hvmloader/acpi/dsdt.c
--- a/tools/firmware/hvmloader/acpi/dsdt.c      Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/firmware/hvmloader/acpi/dsdt.c      Fri Jul 27 08:15:16 2007 -0600
@@ -1,19 +1,19 @@
 /*
  * 
  * Intel ACPI Component Architecture
- * ASL Optimizing Compiler version 20060707 [Dec 30 2006]
+ * ASL Optimizing Compiler version 20060707 [Feb 16 2007]
  * Copyright (C) 2000 - 2006 Intel Corporation
  * Supports ACPI Specification Revision 3.0a
  * 
- * Compilation of "dsdt.asl" - Sat May 12 16:13:55 2007
+ * Compilation of "dsdt.asl" - Wed Jul 11 13:34:30 2007
  * 
  * C source code output
  *
  */
 unsigned char AmlCode[] =
 {
-    0x44,0x53,0x44,0x54,0x67,0x0D,0x00,0x00,  /* 00000000    "DSDTg..." */
-    0x02,0xE0,0x58,0x65,0x6E,0x00,0x00,0x00,  /* 00000008    "..Xen..." */
+    0x44,0x53,0x44,0x54,0x9F,0x0D,0x00,0x00,  /* 00000000    "DSDT...." */
+    0x02,0x2E,0x58,0x65,0x6E,0x00,0x00,0x00,  /* 00000008    "..Xen..." */
     0x48,0x56,0x4D,0x00,0x00,0x00,0x00,0x00,  /* 00000010    "HVM....." */
     0x00,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C,  /* 00000018    "....INTL" */
     0x07,0x07,0x06,0x20,0x08,0x50,0x4D,0x42,  /* 00000020    "... .PMB" */
@@ -27,7 +27,7 @@ unsigned char AmlCode[] =
     0x04,0x0A,0x07,0x0A,0x07,0x00,0x00,0x08,  /* 00000060    "........" */
     0x50,0x49,0x43,0x44,0x00,0x14,0x0C,0x5F,  /* 00000068    "PICD..._" */
     0x50,0x49,0x43,0x01,0x70,0x68,0x50,0x49,  /* 00000070    "PIC.phPI" */
-    0x43,0x44,0x10,0x4C,0xCE,0x5F,0x53,0x42,  /* 00000078    "CD.L._SB" */
+    0x43,0x44,0x10,0x44,0xD2,0x5F,0x53,0x42,  /* 00000078    "CD.D._SB" */
     0x5F,0x5B,0x82,0x49,0x04,0x4D,0x45,0x4D,  /* 00000080    "_[.I.MEM" */
     0x30,0x08,0x5F,0x48,0x49,0x44,0x0C,0x41,  /* 00000088    "0._HID.A" */
     0xD0,0x0C,0x02,0x08,0x5F,0x43,0x52,0x53,  /* 00000090    "...._CRS" */
@@ -37,7 +37,7 @@ unsigned char AmlCode[] =
     0x00,0x00,0xFF,0xFF,0x09,0x00,0x00,0x00,  /* 000000B0    "........" */
     0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 000000B8    "........" */
     0x00,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,  /* 000000C0    "........" */
-    0x00,0x00,0x79,0x00,0x5B,0x82,0x49,0xC9,  /* 000000C8    "..y.[.I." */
+    0x00,0x00,0x79,0x00,0x5B,0x82,0x41,0xCD,  /* 000000C8    "..y.[.A." */
     0x50,0x43,0x49,0x30,0x08,0x5F,0x48,0x49,  /* 000000D0    "PCI0._HI" */
     0x44,0x0C,0x41,0xD0,0x0A,0x03,0x08,0x5F,  /* 000000D8    "D.A...._" */
     0x55,0x49,0x44,0x00,0x08,0x5F,0x41,0x44,  /* 000000E0    "UID.._AD" */
@@ -59,7 +59,7 @@ unsigned char AmlCode[] =
     0x00,0xF0,0xFF,0xFF,0xFF,0xF4,0x00,0x00,  /* 00000160    "........" */
     0x00,0x00,0x00,0x00,0x00,0x05,0x79,0x00,  /* 00000168    "......y." */
     0xA4,0x50,0x52,0x54,0x30,0x08,0x42,0x55,  /* 00000170    ".PRT0.BU" */
-    0x46,0x41,0x11,0x09,0x0A,0x06,0x23,0xA0,  /* 00000178    "FA....#." */
+    0x46,0x41,0x11,0x09,0x0A,0x06,0x23,0x20,  /* 00000178    "FA....# " */
     0x0C,0x18,0x79,0x00,0x08,0x42,0x55,0x46,  /* 00000180    "..y..BUF" */
     0x42,0x11,0x09,0x0A,0x06,0x23,0x00,0x00,  /* 00000188    "B....#.." */
     0x18,0x79,0x00,0x8B,0x42,0x55,0x46,0x42,  /* 00000190    ".y..BUFB" */
@@ -348,7 +348,7 @@ unsigned char AmlCode[] =
     0x0C,0x04,0x0C,0xFF,0xFF,0x0F,0x00,0x0A,  /* 00000A68    "........" */
     0x02,0x00,0x0A,0x2F,0x12,0x0C,0x04,0x0C,  /* 00000A70    ".../...." */
     0xFF,0xFF,0x0F,0x00,0x0A,0x03,0x00,0x0A,  /* 00000A78    "........" */
-    0x10,0x5B,0x82,0x44,0x2E,0x49,0x53,0x41,  /* 00000A80    ".[.D.ISA" */
+    0x10,0x5B,0x82,0x4C,0x31,0x49,0x53,0x41,  /* 00000A80    ".[.L1ISA" */
     0x5F,0x08,0x5F,0x41,0x44,0x52,0x0C,0x00,  /* 00000A88    "_._ADR.." */
     0x00,0x01,0x00,0x5B,0x80,0x50,0x49,0x52,  /* 00000A90    "...[.PIR" */
     0x51,0x02,0x0A,0x60,0x0A,0x04,0x10,0x2E,  /* 00000A98    "Q..`...." */
@@ -440,6 +440,13 @@ unsigned char AmlCode[] =
     0x09,0x5F,0x53,0x54,0x41,0x00,0xA4,0x0A,  /* 00000D48    "._STA..." */
     0x0F,0x08,0x5F,0x43,0x52,0x53,0x11,0x10,  /* 00000D50    ".._CRS.." */
     0x0A,0x0D,0x47,0x01,0xF8,0x03,0xF8,0x03,  /* 00000D58    "..G....." */
-    0x01,0x08,0x22,0x10,0x00,0x79,0x00,
+    0x01,0x08,0x22,0x10,0x00,0x79,0x00,0x5B,  /* 00000D60    ".."..y.[" */
+    0x82,0x36,0x4C,0x54,0x50,0x31,0x08,0x5F,  /* 00000D68    ".6LTP1._" */
+    0x48,0x49,0x44,0x0C,0x41,0xD0,0x04,0x00,  /* 00000D70    "HID.A..." */
+    0x08,0x5F,0x55,0x49,0x44,0x0A,0x02,0x14,  /* 00000D78    "._UID..." */
+    0x09,0x5F,0x53,0x54,0x41,0x00,0xA4,0x0A,  /* 00000D80    "._STA..." */
+    0x0F,0x08,0x5F,0x43,0x52,0x53,0x11,0x10,  /* 00000D88    ".._CRS.." */
+    0x0A,0x0D,0x47,0x01,0x78,0x03,0x78,0x03,  /* 00000D90    "..G.x.x." */
+    0x08,0x08,0x22,0x80,0x00,0x79,0x00,
 };
 int DsdtLen=sizeof(AmlCode);
diff -r 37833b33ae77 -r 4492a0285bae tools/firmware/hvmloader/config.h
--- a/tools/firmware/hvmloader/config.h Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/firmware/hvmloader/config.h Fri Jul 27 08:15:16 2007 -0600
@@ -9,7 +9,7 @@
 #define LAPIC_ID(vcpu_id)   ((vcpu_id) * 2)
 
 #define PCI_ISA_DEVFN       0x08    /* dev 1, fn 0 */
-#define PCI_ISA_IRQ_MASK    0x0ca0U /* ISA IRQs 5,7,10,11 are PCI connected */
+#define PCI_ISA_IRQ_MASK    0x0c20U /* ISA IRQs 5,10,11 are PCI connected */
 
 #define ROMBIOS_SEG            0xF000
 #define ROMBIOS_BEGIN          0x000F0000
diff -r 37833b33ae77 -r 4492a0285bae tools/firmware/hvmloader/hvmloader.c
--- a/tools/firmware/hvmloader/hvmloader.c      Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/firmware/hvmloader/hvmloader.c      Fri Jul 27 08:15:16 2007 -0600
@@ -180,15 +180,13 @@ static void pci_setup(void)
     unsigned int bar, pin, link, isa_irq;
 
     /* Program PCI-ISA bridge with appropriate link routes. */
-    link = 0;
-    for ( isa_irq = 0; isa_irq < 15; isa_irq++ )
-    {
-        if ( !(PCI_ISA_IRQ_MASK & (1U << isa_irq)) )
-            continue;
+    isa_irq = 0;
+    for ( link = 0; link < 4; link++ )
+    {
+        do { isa_irq = (isa_irq + 1) & 15;
+        } while ( !(PCI_ISA_IRQ_MASK & (1U << isa_irq)) );
         pci_writeb(PCI_ISA_DEVFN, 0x60 + link, isa_irq);
         printf("PCI-ISA link %u routed to IRQ%u\n", link, isa_irq);
-        if ( link++ == 4 )
-            break;
     }
 
     /* Program ELCR to match PCI-wired IRQs. */
diff -r 37833b33ae77 -r 4492a0285bae tools/firmware/rombios/rombios.c
--- a/tools/firmware/rombios/rombios.c  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/firmware/rombios/rombios.c  Fri Jul 27 08:15:16 2007 -0600
@@ -9146,78 +9146,78 @@ pci_routing_table_structure:
   db 0 ;; pci bus number
   db 0x08 ;; pci device number (bit 7-3)
   db 0x61 ;; link value INTA#: pointer into PCI2ISA config space
-  dw 0x0ca0 ;; IRQ bitmap INTA# 
+  dw 0x0c20 ;; IRQ bitmap INTA# 
   db 0x62 ;; link value INTB#
-  dw 0x0ca0 ;; IRQ bitmap INTB# 
+  dw 0x0c20 ;; IRQ bitmap INTB# 
   db 0x63 ;; link value INTC#
-  dw 0x0ca0 ;; IRQ bitmap INTC# 
+  dw 0x0c20 ;; IRQ bitmap INTC# 
   db 0x60 ;; link value INTD#
-  dw 0x0ca0 ;; IRQ bitmap INTD#
+  dw 0x0c20 ;; IRQ bitmap INTD#
   db 0 ;; physical slot (0 = embedded)
   db 0 ;; reserved
   ;; second slot entry: 1st PCI slot
   db 0 ;; pci bus number
   db 0x10 ;; pci device number (bit 7-3)
   db 0x62 ;; link value INTA#
-  dw 0x0ca0 ;; IRQ bitmap INTA# 
+  dw 0x0c20 ;; IRQ bitmap INTA# 
   db 0x63 ;; link value INTB#
-  dw 0x0ca0 ;; IRQ bitmap INTB# 
+  dw 0x0c20 ;; IRQ bitmap INTB# 
   db 0x60 ;; link value INTC#
-  dw 0x0ca0 ;; IRQ bitmap INTC# 
+  dw 0x0c20 ;; IRQ bitmap INTC# 
   db 0x61 ;; link value INTD#
-  dw 0x0ca0 ;; IRQ bitmap INTD#
+  dw 0x0c20 ;; IRQ bitmap INTD#
   db 1 ;; physical slot (0 = embedded)
   db 0 ;; reserved
   ;; third slot entry: 2nd PCI slot
   db 0 ;; pci bus number
   db 0x18 ;; pci device number (bit 7-3)
   db 0x63 ;; link value INTA#
-  dw 0x0ca0 ;; IRQ bitmap INTA# 
+  dw 0x0c20 ;; IRQ bitmap INTA# 
   db 0x60 ;; link value INTB#
-  dw 0x0ca0 ;; IRQ bitmap INTB# 
+  dw 0x0c20 ;; IRQ bitmap INTB# 
   db 0x61 ;; link value INTC#
-  dw 0x0ca0 ;; IRQ bitmap INTC# 
+  dw 0x0c20 ;; IRQ bitmap INTC# 
   db 0x62 ;; link value INTD#
-  dw 0x0ca0 ;; IRQ bitmap INTD#
+  dw 0x0c20 ;; IRQ bitmap INTD#
   db 2 ;; physical slot (0 = embedded)
   db 0 ;; reserved
   ;; 4th slot entry: 3rd PCI slot
   db 0 ;; pci bus number
   db 0x20 ;; pci device number (bit 7-3)
   db 0x60 ;; link value INTA#
-  dw 0x0ca0 ;; IRQ bitmap INTA# 
+  dw 0x0c20 ;; IRQ bitmap INTA# 
   db 0x61 ;; link value INTB#
-  dw 0x0ca0 ;; IRQ bitmap INTB# 
+  dw 0x0c20 ;; IRQ bitmap INTB# 
   db 0x62 ;; link value INTC#
-  dw 0x0ca0 ;; IRQ bitmap INTC# 
+  dw 0x0c20 ;; IRQ bitmap INTC# 
   db 0x63 ;; link value INTD#
-  dw 0x0ca0 ;; IRQ bitmap INTD#
+  dw 0x0c20 ;; IRQ bitmap INTD#
   db 3 ;; physical slot (0 = embedded)
   db 0 ;; reserved
   ;; 5th slot entry: 4rd PCI slot
   db 0 ;; pci bus number
   db 0x28 ;; pci device number (bit 7-3)
   db 0x61 ;; link value INTA#
-  dw 0x0ca0 ;; IRQ bitmap INTA# 
+  dw 0x0c20 ;; IRQ bitmap INTA# 
   db 0x62 ;; link value INTB#
-  dw 0x0ca0 ;; IRQ bitmap INTB# 
+  dw 0x0c20 ;; IRQ bitmap INTB# 
   db 0x63 ;; link value INTC#
-  dw 0x0ca0 ;; IRQ bitmap INTC# 
+  dw 0x0c20 ;; IRQ bitmap INTC# 
   db 0x60 ;; link value INTD#
-  dw 0x0ca0 ;; IRQ bitmap INTD#
+  dw 0x0c20 ;; IRQ bitmap INTD#
   db 4 ;; physical slot (0 = embedded)
   db 0 ;; reserved
   ;; 6th slot entry: 5rd PCI slot
   db 0 ;; pci bus number
   db 0x30 ;; pci device number (bit 7-3)
   db 0x62 ;; link value INTA#
-  dw 0x0ca0 ;; IRQ bitmap INTA# 
+  dw 0x0c20 ;; IRQ bitmap INTA# 
   db 0x63 ;; link value INTB#
-  dw 0x0ca0 ;; IRQ bitmap INTB# 
+  dw 0x0c20 ;; IRQ bitmap INTB# 
   db 0x60 ;; link value INTC#
-  dw 0x0ca0 ;; IRQ bitmap INTC# 
+  dw 0x0c20 ;; IRQ bitmap INTC# 
   db 0x61 ;; link value INTD#
-  dw 0x0ca0 ;; IRQ bitmap INTD#
+  dw 0x0c20 ;; IRQ bitmap INTD#
   db 5 ;; physical slot (0 = embedded)
   db 0 ;; reserved
 #endif // BX_PCIBIOS
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/hw/cirrus_vga.c
--- a/tools/ioemu/hw/cirrus_vga.c       Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/hw/cirrus_vga.c       Fri Jul 27 08:15:16 2007 -0600
@@ -3096,8 +3096,6 @@ static void cirrus_vga_save(QEMUFile *f,
     qemu_put_be64s(f, (uint64_t*)&s->cirrus_lfb_addr);
     qemu_put_be64s(f, (uint64_t*)&s->cirrus_lfb_end);
     qemu_put_buffer(f, s->vram_ptr, VGA_RAM_SIZE); 
-    if (vga_acc)
-        cirrus_stop_acc(s);
 }
 
 static int cirrus_vga_load(QEMUFile *f, void *opaque, int version_id)
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/hw/ide.c
--- a/tools/ioemu/hw/ide.c      Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/hw/ide.c      Fri Jul 27 08:15:16 2007 -0600
@@ -596,7 +596,8 @@ static void ide_identify(IDEState *s)
     /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
     put_le16(p + 83, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
     put_le16(p + 84, (1 << 14));
-    put_le16(p + 85, (1 << 14));
+    /* 14=nop 5=write_cache */
+    put_le16(p + 85, (1 << 14) | (1 << 5));
     /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
     put_le16(p + 86, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
     put_le16(p + 87, (1 << 14));
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/hw/rtl8139.c
--- a/tools/ioemu/hw/rtl8139.c  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/hw/rtl8139.c  Fri Jul 27 08:15:16 2007 -0600
@@ -53,9 +53,8 @@
 /* debug RTL8139 card C+ mode only */
 //#define DEBUG_RTL8139CP 1
 
-/* RTL8139 provides frame CRC with received packet, this feature seems to be
-   ignored by most drivers, disabled by default */
-//#define RTL8139_CALCULATE_RXCRC 1
+/* Calculate CRCs propoerly on Rx packets */
+#define RTL8139_CALCULATE_RXCRC 1
 
 /* Uncomment to enable on-board timer interrupts */
 //#define RTL8139_ONBOARD_TIMER 1
@@ -754,7 +753,7 @@ static void rtl8139_write_buffer(RTL8139
         int wrapped = MOD2(s->RxBufAddr + size, s->RxBufferSize);
 
         /* write packet data */
-        if (wrapped && s->RxBufferSize < 65536 && !rtl8139_RxWrap(s))
+        if (wrapped && !(s->RxBufferSize < 65536 && rtl8139_RxWrap(s)))
         {
             DEBUG_PRINT((">>> RTL8139: rx packet wrapped in buffer at %d\n", 
size-wrapped));
 
@@ -1030,7 +1029,7 @@ static void rtl8139_do_receive(void *opa
 
         /* write checksum */
 #if defined (RTL8139_CALCULATE_RXCRC)
-        val = cpu_to_le32(crc32(~0, buf, size));
+        val = cpu_to_le32(crc32(0, buf, size));
 #else
         val = 0;
 #endif
@@ -1136,7 +1135,7 @@ static void rtl8139_do_receive(void *opa
 
         /* write checksum */
 #if defined (RTL8139_CALCULATE_RXCRC)
-        val = cpu_to_le32(crc32(~0, buf, size));
+        val = cpu_to_le32(crc32(0, buf, size));
 #else
         val = 0;
 #endif
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/keymaps.c
--- a/tools/ioemu/keymaps.c     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/keymaps.c     Fri Jul 27 08:15:16 2007 -0600
@@ -49,6 +49,7 @@ typedef struct {
     int extra_count;
     struct key_range *keypad_range;
     struct key_range *numlock_range;
+    struct key_range *shift_range;
 } kbd_layout_t;
 
 static void add_to_key_range(struct key_range **krp, int code) {
@@ -127,6 +128,10 @@ static kbd_layout_t *parse_keyboard_layo
                        add_to_key_range(&k->numlock_range, keysym);
                        fprintf(stderr, "keypad keysym %04x keycode %d\n", 
keysym, keycode);
                    }
+                   if (rest && strstr(rest, "shift")) {
+                       add_to_key_range(&k->shift_range, keysym);
+                       fprintf(stderr, "shift keysym %04x keycode %d\n", 
keysym, keycode);
+                   }
 
                    /* if(keycode&0x80)
                       keycode=(keycode<<8)^0x80e0; */
@@ -205,3 +210,14 @@ static int keysymIsNumlock(void *kbd_lay
            return 1;
     return 0;
 }
+
+static int keysymIsShift(void *kbd_layout, int keysym)
+{
+    kbd_layout_t *k = kbd_layout;
+    struct key_range *kr;
+
+    for (kr = k->shift_range; kr; kr = kr->next)
+       if (keysym >= kr->start && keysym <= kr->end)
+           return 1;
+    return 0;
+}
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/target-i386-dm/exec-dm.c
--- a/tools/ioemu/target-i386-dm/exec-dm.c      Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/target-i386-dm/exec-dm.c      Fri Jul 27 08:15:16 2007 -0600
@@ -446,18 +446,16 @@ extern unsigned long logdirty_bitmap_siz
 #if defined(__x86_64__) || defined(__i386__)
 static void memcpy_words(void *dst, void *src, size_t n)
 {
-    asm (
+    asm volatile (
         "   movl %%edx,%%ecx \n"
 #ifdef __x86_64__
         "   shrl $3,%%ecx    \n"
-        "   andl $7,%%edx    \n"
         "   rep  movsq       \n"
         "   test $4,%%edx    \n"
         "   jz   1f          \n"
         "   movsl            \n"
 #else /* __i386__ */
         "   shrl $2,%%ecx    \n"
-        "   andl $3,%%edx    \n"
         "   rep  movsl       \n"
 #endif
         "1: test $2,%%edx    \n"
@@ -467,7 +465,7 @@ static void memcpy_words(void *dst, void
         "   jz   1f          \n"
         "   movsb            \n"
         "1:                  \n"
-        : : "S" (src), "D" (dst), "d" (n) : "ecx" );
+        : "+S" (src), "+D" (dst) : "d" (n) : "ecx", "memory" );
 }
 #else
 static void memcpy_words(void *dst, void *src, size_t n)
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/target-i386-dm/helper2.c
--- a/tools/ioemu/target-i386-dm/helper2.c      Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/target-i386-dm/helper2.c      Fri Jul 27 08:15:16 2007 -0600
@@ -618,6 +618,7 @@ int main_loop(void)
     CPUState *env = cpu_single_env;
     int evtchn_fd = xc_evtchn_fd(xce_handle);
     char qemu_file[PATH_MAX];
+    fd_set fds;
 
     buffered_io_timer = qemu_new_timer(rt_clock, handle_buffered_io,
                                       cpu_single_env);
@@ -625,19 +626,35 @@ int main_loop(void)
 
     qemu_set_fd_handler(evtchn_fd, cpu_handle_ioreq, NULL, env);
 
-    while (!(vm_running && suspend_requested))
-        /* Wait up to 10 msec. */
-        main_loop_wait(10);
-
-    fprintf(logfile, "device model received suspend signal!\n");
-
-    /* Pull all outstanding ioreqs through the system */
-    handle_buffered_io(env);
-    main_loop_wait(1); /* For the select() on events */
-
-    /* Save the device state */
-    snprintf(qemu_file, sizeof(qemu_file), "/var/lib/xen/qemu-save.%d", domid);
-    do_savevm(qemu_file);
+    xenstore_record_dm_state("running");
+    while (1) {
+        while (!(vm_running && suspend_requested))
+            /* Wait up to 10 msec. */
+            main_loop_wait(10);
+
+        fprintf(logfile, "device model saving state\n");
+
+        /* Pull all outstanding ioreqs through the system */
+        handle_buffered_io(env);
+        main_loop_wait(1); /* For the select() on events */
+
+        /* Save the device state */
+        snprintf(qemu_file, sizeof(qemu_file), 
+                 "/var/lib/xen/qemu-save.%d", domid);
+        do_savevm(qemu_file);
+
+        xenstore_record_dm_state("paused");
+
+        /* Wait to be allowed to continue */
+        while (suspend_requested) {
+            FD_ZERO(&fds);
+            FD_SET(xenstore_fd(), &fds);
+            if (select(xenstore_fd() + 1, &fds, NULL, NULL, NULL) > 0)
+                xenstore_process_event(NULL);
+        }
+
+        xenstore_record_dm_state("running");
+    }
 
     return 0;
 }
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/vl.c
--- a/tools/ioemu/vl.c  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/vl.c  Fri Jul 27 08:15:16 2007 -0600
@@ -6856,15 +6856,6 @@ int set_mm_mapping(int xc_handle, uint32
     return 0;
 }
 
-void suspend(int sig)
-{
-    fprintf(logfile, "suspend sig handler called with requested=%d!\n",
-            suspend_requested);
-    if (sig != SIGUSR1)
-        fprintf(logfile, "suspend signal dismatch, get sig=%d!\n", sig);
-    suspend_requested = 1;
-}
-
 #if defined(MAPCACHE)
 
 #if defined(__i386__) 
@@ -7057,6 +7048,7 @@ int main(int argc, char **argv)
     xen_pfn_t *page_array;
     extern void *buffered_pio_page;
 #endif
+    sigset_t set;
 
     char qemu_dm_logfilename[128];
     
@@ -7141,13 +7133,8 @@ int main(int argc, char **argv)
         serial_devices[i][0] = '\0';
     serial_device_index = 0;
 
-#ifndef CONFIG_DM
     pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
-#else
-    /* Xen steals IRQ7 for PCI. Disable LPT1 by default. */
-    for(i = 0; i < MAX_PARALLEL_PORTS; i++)
-#endif
         parallel_devices[i][0] = '\0';
     parallel_device_index = 0;
     
@@ -7987,24 +7974,11 @@ int main(int argc, char **argv)
        close(fd);
     }
 
-    /* register signal for the suspend request when save */
-    {
-        struct sigaction act;
-        sigset_t set;
-        act.sa_handler = suspend;
-        act.sa_flags = SA_RESTART;
-        sigemptyset(&act.sa_mask);
-
-        sigaction(SIGUSR1, &act, NULL);
-
-        /* control panel mask some signals when spawn qemu, need unmask here*/
-        sigemptyset(&set);
-        sigaddset(&set, SIGUSR1);
-        sigaddset(&set, SIGTERM);
-        if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
-            fprintf(stderr, "unblock signal fail, possible issue for HVM 
save!\n");
-
-    }
+    /* Unblock SIGTERM, which may have been blocked by the caller */
+    sigemptyset(&set);
+    sigaddset(&set, SIGTERM);
+    if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
+        fprintf(stderr, "Failed to unblock SIGTERM\n");
 
     main_loop();
     quit_timers();
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/vl.h
--- a/tools/ioemu/vl.h  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/vl.h  Fri Jul 27 08:15:16 2007 -0600
@@ -1456,6 +1456,7 @@ void xenstore_parse_domain_config(int do
 void xenstore_parse_domain_config(int domid);
 int xenstore_fd(void);
 void xenstore_process_event(void *opaque);
+void xenstore_record_dm_state(char *state);
 void xenstore_check_new_media_present(int timeout);
 void xenstore_write_vncport(int vnc_display);
 int xenstore_read_vncpasswd(int domid);
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/vnc.c
--- a/tools/ioemu/vnc.c Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/vnc.c Fri Jul 27 08:15:16 2007 -0600
@@ -915,12 +915,69 @@ static void press_key(VncState *vs, int 
     kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) | 0x80);
 }
 
+static void press_key_shift_down(VncState *vs, int down, int keycode)
+{
+    if (down)
+        kbd_put_keycode(0x2a & 0x7f);
+
+    if (keycode & 0x80)
+        kbd_put_keycode(0xe0);
+    if (down)
+        kbd_put_keycode(keycode & 0x7f);
+    else
+        kbd_put_keycode(keycode | 0x80);
+
+    if (!down)
+        kbd_put_keycode(0x2a | 0x80);
+}
+
+static void press_key_shift_up(VncState *vs, int down, int keycode)
+{
+    if (down) {
+        if (vs->modifiers_state[0x2a])
+            kbd_put_keycode(0x2a | 0x80);
+        if (vs->modifiers_state[0x36]) 
+            kbd_put_keycode(0x36 | 0x80);
+    }
+
+    if (keycode & 0x80)
+        kbd_put_keycode(0xe0);
+    if (down)
+        kbd_put_keycode(keycode & 0x7f);
+    else
+        kbd_put_keycode(keycode | 0x80);
+
+    if (!down) {
+        if (vs->modifiers_state[0x2a])
+            kbd_put_keycode(0x2a & 0x7f);
+        if (vs->modifiers_state[0x36]) 
+            kbd_put_keycode(0x36 & 0x7f);
+    }
+}
+
 static void do_key_event(VncState *vs, int down, uint32_t sym)
 {
     int keycode;
+    int shift_keys = 0;
+    int shift = 0;
+
+    if (is_graphic_console()) {
+        if (sym >= 'A' && sym <= 'Z') {
+            sym = sym - 'A' + 'a';
+            shift = 1;
+        }
+        else {
+            shift = keysymIsShift(vs->kbd_layout, sym & 0xFFFF);
+        }
+    }
+    shift_keys = vs->modifiers_state[0x2a] | vs->modifiers_state[0x36];
 
     keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
-    
+    if (keycode == 0) {
+        fprintf(stderr, "Key lost : keysym=0x%x(%d)\n", sym, sym);
+        return;
+    }
+
     /* QEMU console switch */
     switch(keycode) {
     case 0x2a:                          /* Left Shift */
@@ -929,11 +986,15 @@ static void do_key_event(VncState *vs, i
     case 0x9d:                          /* Right CTRL */
     case 0x38:                          /* Left ALT */
     case 0xb8:                          /* Right ALT */
-        if (down)
+        if (down) {
             vs->modifiers_state[keycode] = 1;
-        else
+            kbd_put_keycode(keycode & 0x7f);
+        }
+        else {
             vs->modifiers_state[keycode] = 0;
-        break;
+            kbd_put_keycode(keycode | 0x80);
+        }
+        return;
     case 0x02 ... 0x0a: /* '1' to '9' keys */ 
         if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
             /* Reset the modifiers sent to the current console */
@@ -943,9 +1004,14 @@ static void do_key_event(VncState *vs, i
         }
         break;
     case 0x45:                 /* NumLock */
-       if (!down)
+       if (down) {
+            kbd_put_keycode(keycode & 0x7f);
+        }
+        else { 
            vs->modifiers_state[keycode] ^= 1;
-       break;
+            kbd_put_keycode(keycode | 0x80);
+        }
+       return;
     }
 
     if (keycodeIsKeypad(vs->kbd_layout, keycode)) {
@@ -967,6 +1033,18 @@ static void do_key_event(VncState *vs, i
     }
 
     if (is_graphic_console()) {
+        /*  If the shift state needs to change then simulate an additional
+            keypress before sending this one.
+        */
+        if (shift && !shift_keys) {
+            press_key_shift_down(vs, down, keycode);
+            return;
+        }
+        else if (!shift && shift_keys) {
+            press_key_shift_up(vs, down, keycode);
+            return;
+        }
+
         if (keycode & 0x80)
             kbd_put_keycode(0xe0);
         if (down)
@@ -1021,8 +1099,6 @@ static void do_key_event(VncState *vs, i
 
 static void key_event(VncState *vs, int down, uint32_t sym)
 {
-    if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
-       sym = sym - 'A' + 'a';
     do_key_event(vs, down, sym);
 }
 
diff -r 37833b33ae77 -r 4492a0285bae tools/ioemu/xenstore.c
--- a/tools/ioemu/xenstore.c    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/ioemu/xenstore.c    Fri Jul 27 08:15:16 2007 -0600
@@ -181,11 +181,18 @@ void xenstore_parse_domain_config(int do
     }
 
     /* Set a watch for log-dirty requests from the migration tools */
-    if (pasprintf(&buf, "%s/logdirty/next-active", path) != -1) {
+    if (pasprintf(&buf, "/local/domain/0/device-model/%u/logdirty/next-active",
+                  domid) != -1) {
         xs_watch(xsh, buf, "logdirty");
         fprintf(logfile, "Watching %s\n", buf);
     }
 
+    /* Set a watch for suspend requests from the migration tools */
+    if (pasprintf(&buf, 
+                  "/local/domain/0/device-model/%u/command", domid) != -1) {
+        xs_watch(xsh, buf, "dm-command");
+        fprintf(logfile, "Watching %s\n", buf);
+    }
 
  out:
     free(type);
@@ -218,33 +225,26 @@ void xenstore_process_logdirty_event(voi
     unsigned int len;
     int i;
 
-    fprintf(logfile, "Triggered log-dirty buffer switch\n");
-
     if (!seg) {
-        char *path, *p, *key_ascii, key_terminated[17] = {0,};
+        char *path = NULL, *key_ascii, key_terminated[17] = {0,};
         key_t key;
         int shmid;
 
         /* Find and map the shared memory segment for log-dirty bitmaps */
-        if (!(path = xs_get_domain_path(xsh, domid))) {            
-            fprintf(logfile, "Log-dirty: can't get domain path in store\n");
-            exit(1);
-        }
-        if (!(path = realloc(path, strlen(path) 
-                             + strlen("/logdirty/next-active") + 1))) {
+        if (pasprintf(&path, 
+                      "/local/domain/0/device-model/%u/logdirty/key", 
+                      domid) == -1) {
             fprintf(logfile, "Log-dirty: out of memory\n");
             exit(1);
         }
-        strcat(path, "/logdirty/");
-        p = path + strlen(path);
-        strcpy(p, "key");
         
         key_ascii = xs_read(xsh, XBT_NULL, path, &len);
-        if (!key_ascii) {
+        free(path);
+
+        if (!key_ascii) 
             /* No key yet: wait for the next watch */
-            free(path);
             return;
-        }
+
         strncpy(key_terminated, key_ascii, 16);
         free(key_ascii);
         key = (key_t) strtoull(key_terminated, NULL, 16);
@@ -276,18 +276,21 @@ void xenstore_process_logdirty_event(voi
         }
 
         /* Remember the paths for the next-active and active entries */
-        strcpy(p, "active");
-        if (!(active_path = strdup(path))) {
+        if (pasprintf(&active_path, 
+                      "/local/domain/0/device-model/%u/logdirty/active",
+                      domid) == -1) {
             fprintf(logfile, "Log-dirty: out of memory\n");
             exit(1);
         }
-        strcpy(p, "next-active");
-        if (!(next_active_path = strdup(path))) {
+        if (pasprintf(&next_active_path, 
+                      "/local/domain/0/device-model/%u/logdirty/next-active",
+                      domid) == -1) {
             fprintf(logfile, "Log-dirty: out of memory\n");
             exit(1);
         }
-        free(path);
-    }
+    }
+
+    fprintf(logfile, "Triggered log-dirty buffer switch\n");
     
     /* Read the required active buffer from the store */
     act = xs_read(xsh, XBT_NULL, next_active_path, &len);
@@ -310,6 +313,52 @@ void xenstore_process_logdirty_event(voi
 }
 
 
+/* Accept state change commands from the control tools */
+static void xenstore_process_dm_command_event(void)
+{
+    char *path = NULL, *command = NULL;
+    unsigned int len;
+    extern int suspend_requested;
+
+    if (pasprintf(&path, 
+                  "/local/domain/0/device-model/%u/command", domid) == -1) {
+        fprintf(logfile, "out of memory reading dm command\n");
+        goto out;
+    }
+    command = xs_read(xsh, XBT_NULL, path, &len);
+    if (!command)
+        goto out;
+    
+    if (!strncmp(command, "save", len)) {
+        fprintf(logfile, "dm-command: pause and save state\n");
+        suspend_requested = 1;
+    } else if (!strncmp(command, "continue", len)) {
+        fprintf(logfile, "dm-command: continue after state save\n");
+        suspend_requested = 0;
+    } else {
+        fprintf(logfile, "dm-command: unknown command\"%*s\"\n", len, command);
+    }
+
+ out:
+    free(path);
+    free(command);
+}
+
+void xenstore_record_dm_state(char *state)
+{
+    char *path = NULL;
+
+    if (pasprintf(&path, 
+                  "/local/domain/0/device-model/%u/state", domid) == -1) {
+        fprintf(logfile, "out of memory recording dm state\n");
+        goto out;
+    }
+    if (!xs_write(xsh, XBT_NULL, path, state, strlen(state)))
+        fprintf(logfile, "error recording dm state\n");
+
+ out:
+    free(path);
+}
 
 void xenstore_process_event(void *opaque)
 {
@@ -322,6 +371,11 @@ void xenstore_process_event(void *opaque
 
     if (!strcmp(vec[XS_WATCH_TOKEN], "logdirty")) {
         xenstore_process_logdirty_event();
+        goto out;
+    }
+
+    if (!strcmp(vec[XS_WATCH_TOKEN], "dm-command")) {
+        xenstore_process_dm_command_event();
         goto out;
     }
 
diff -r 37833b33ae77 -r 4492a0285bae tools/libxc/xc_domain.c
--- a/tools/libxc/xc_domain.c   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxc/xc_domain.c   Fri Jul 27 08:15:16 2007 -0600
@@ -586,6 +586,27 @@ int xc_domain_ioport_permission(int xc_h
     domctl.u.ioport_permission.allow_access = allow_access;
 
     return do_domctl(xc_handle, &domctl);
+}
+
+int xc_availheap(int xc_handle,
+                 int min_width,
+                 int max_width,
+                 int node,
+                 uint64_t *bytes)
+{
+    DECLARE_SYSCTL;
+    int rc;
+
+    sysctl.cmd = XEN_SYSCTL_availheap;
+    sysctl.u.availheap.min_bitwidth = min_width;
+    sysctl.u.availheap.max_bitwidth = max_width;
+    sysctl.u.availheap.node = node;
+
+    rc = xc_sysctl(xc_handle, &sysctl);
+
+    *bytes = sysctl.u.availheap.avail_bytes;
+
+    return rc;
 }
 
 int xc_vcpu_setcontext(int xc_handle,
diff -r 37833b33ae77 -r 4492a0285bae tools/libxc/xc_linux.c
--- a/tools/libxc/xc_linux.c    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxc/xc_linux.c    Fri Jul 27 08:15:16 2007 -0600
@@ -456,7 +456,7 @@ void *xc_gnttab_map_grant_refs(int xcg_h
 
     map->count = count;
     
-    if ( ioctl(xcg_handle, IOCTL_GNTDEV_MAP_GRANT_REF, &map) )
+    if ( ioctl(xcg_handle, IOCTL_GNTDEV_MAP_GRANT_REF, map) )
         goto out;
 
     addr = mmap(NULL, PAGE_SIZE * count, prot, MAP_SHARED, xcg_handle,
diff -r 37833b33ae77 -r 4492a0285bae tools/libxc/xenctrl.h
--- a/tools/libxc/xenctrl.h     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxc/xenctrl.h     Fri Jul 27 08:15:16 2007 -0600
@@ -628,6 +628,20 @@ int xc_get_pfn_type_batch(int xc_handle,
 /* Get current total pages allocated to a domain. */
 long xc_get_tot_pages(int xc_handle, uint32_t domid);
 
+/**
+ * This function retrieves the the number of bytes available
+ * in the heap in a specific range of address-widths and nodes.
+ * 
+ * @parm xc_handle a handle to an open hypervisor interface
+ * @parm domid the domain to query
+ * @parm min_width the smallest address width to query (0 if don't care)
+ * @parm max_width the largest address width to query (0 if don't care)
+ * @parm node the node to query (-1 for all)
+ * @parm *bytes caller variable to put total bytes counted
+ * @return 0 on success, <0 on failure.
+ */
+int xc_availheap(int xc_handle, int min_width, int max_width, int node,
+                 uint64_t *bytes);
 
 /*
  * Trace Buffer Operations
diff -r 37833b33ae77 -r 4492a0285bae 
tools/libxen/include/xen/api/xen_acmpolicy.h
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/libxen/include/xen/api/xen_acmpolicy.h      Fri Jul 27 08:15:16 
2007 -0600
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2007, IBM Corp.
+ * Copyright (c) 2007, XenSource Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
+ */
+
+#ifndef XEN_ACMPOLICY_H
+#define XEN_ACMPOLICY_H
+
+#include "xen_common.h"
+#include "xen_string_string_map.h"
+#include "xen_xspolicy_decl.h"
+#include "xen_vm_decl.h"
+
+/*
+ * Data structures.
+ */
+
+typedef struct xen_acmpolicy_record
+{
+    xen_xspolicy handle;
+    char *uuid;
+    char *repr;
+    xs_instantiationflags flags;
+    xs_type type;
+} xen_acmpolicy_record;
+
+/**
+ * Allocate a xen_acmpolicy_record.
+ */
+extern xen_acmpolicy_record *
+xen_acmpolicy_record_alloc(void);
+
+/**
+ * Free the given xen_xspolicy_record, and all referenced values.  The
+ * given record must have been allocated by this library.
+ */
+extern void
+xen_acmpolicy_record_free(xen_acmpolicy_record *record);
+
+
+/**
+ * Data structures for the policy's header
+ */
+typedef struct xen_acm_header
+{
+    char *policyname;
+    char *policyurl;
+    char *date;
+    char *reference;
+    char *namespaceurl;
+    char *version;
+} xen_acm_header;
+
+extern xen_acm_header *
+xen_acm_header_alloc(void);
+
+extern void
+xen_acm_header_free(xen_acm_header *hdr);
+
+/**
+ * Get the referenced policy's record.
+ */
+bool
+xen_acmpolicy_get_record(xen_session *session, xen_acmpolicy_record **result,
+                         xen_xspolicy xspolicy);
+
+/**
+ * Get the header of a  policy.
+ */
+extern bool
+xen_acmpolicy_get_header(xen_session *session, xen_acm_header **hdr,
+                         xen_xspolicy xspolicy);
+
+
+/**
+ * Get the XML representation of the policy.
+ */
+extern bool
+xen_acmpolicy_get_xml(xen_session *session, char **xml,
+                      xen_xspolicy xspolicy);
+
+/**
+ * Get the mapping file of the policy.
+ */
+extern bool
+xen_acmpolicy_get_map(xen_session *session, char **map,
+                      xen_xspolicy xspolicy);
+
+/**
+ * Get the binary representation (base64-encoded) of the policy.
+ */
+extern bool
+xen_acmpolicy_get_binary(xen_session *session, char **binary,
+                         xen_xspolicy xspolicy);
+
+/**
+ * Get the UUID filed of the given policy.
+ */
+bool
+xen_acmpolicy_get_uuid(xen_session *session, char **result,
+                       xen_xspolicy xspolicy);
+
+#endif
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/include/xen/api/xen_vdi.h
--- a/tools/libxen/include/xen/api/xen_vdi.h    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxen/include/xen/api/xen_vdi.h    Fri Jul 27 08:15:16 2007 -0600
@@ -344,4 +344,17 @@ xen_vdi_get_all(xen_session *session, st
 xen_vdi_get_all(xen_session *session, struct xen_vdi_set **result);
 
 
+/**
+ * Set the security label of a VDI.
+ */
+extern bool
+xen_vdi_set_security_label(xen_session *session, int64_t *result, xen_vdi vdi,
+                           char *label, char *oldlabel);
+
+/**
+ * Get the security label of a VDI.
+ */
+extern bool
+xen_vdi_get_security_label(xen_session *session, char **result, xen_vdi vdi);
+
 #endif
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/include/xen/api/xen_vif.h
--- a/tools/libxen/include/xen/api/xen_vif.h    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxen/include/xen/api/xen_vif.h    Fri Jul 27 08:15:16 2007 -0600
@@ -362,4 +362,18 @@ xen_vif_get_all(xen_session *session, st
 xen_vif_get_all(xen_session *session, struct xen_vif_set **result);
 
 
+/**
+ * Set the security label of a VIF.
+ */
+extern bool
+xen_vif_set_security_label(xen_session *session, int64_t *result, xen_vif vif,
+                           char *label, char *oldlabel);
+
+
+/**
+ * Get the security label of a VIF.
+ */
+extern bool
+xen_vif_get_security_label(xen_session *session, char **result, xen_vif vif);
+
 #endif
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/include/xen/api/xen_vm.h
--- a/tools/libxen/include/xen/api/xen_vm.h     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxen/include/xen/api/xen_vm.h     Fri Jul 27 08:15:16 2007 -0600
@@ -112,6 +112,7 @@ typedef struct xen_vm_record
     bool is_control_domain;
     struct xen_vm_metrics_record_opt *metrics;
     struct xen_vm_guest_metrics_record_opt *guest_metrics;
+    char *security_label;
 } xen_vm_record;
 
 /**
@@ -891,4 +892,17 @@ xen_vm_get_all(xen_session *session, str
 xen_vm_get_all(xen_session *session, struct xen_vm_set **result);
 
 
+/**
+ * Set the security label of a domain.
+ */
+extern bool
+xen_vm_set_security_label(xen_session *session, int64_t *result, xen_vm vm,
+                          char *label, char *oldlabel);
+
+/**
+ * Get the security label of a domain.
+ */
+extern bool
+xen_vm_get_security_label(xen_session *session, char **result, xen_vm vm);
+
 #endif
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/include/xen/api/xen_xspolicy.h
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/libxen/include/xen/api/xen_xspolicy.h       Fri Jul 27 08:15:16 
2007 -0600
@@ -0,0 +1,271 @@
+/*
+ * Copyright (c) 2007, IBM Corp.
+ * Copyright (c) 2007, XenSource Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
+ */
+
+#ifndef XEN_XSPOLICY_H
+#define XEN_XSPOLICY_H
+
+#include "xen_common.h"
+#include "xen_xspolicy_decl.h"
+#include "xen_string_string_map.h"
+
+
+/*
+ * The XSPolicy and associated data structures.
+ *
+ */
+typedef int64_t xs_type;
+typedef int64_t xs_instantiationflags;
+
+enum xs_type {
+    XS_POLICY_ACM = (1 << 0),
+};
+
+enum xs_instantiationflags {
+    XS_INST_NONE = 0,
+    XS_INST_BOOT = (1 << 0),
+    XS_INST_LOAD = (1 << 1),
+};
+
+
+/* Error codes returned by xend following XSPolicy operations */
+#define XSERR_BASE                       0x1000
+
+#define XSERR_SUCCESS                    0
+#define XSERR_GENERAL_FAILURE            1 + XSERR_BASE
+#define XSERR_BAD_XML                    2 + XSERR_BASE
+#define XSERR_XML_PROCESSING             3 + XSERR_BASE
+#define XSERR_POLICY_INCONSISTENT        4 + XSERR_BASE
+#define XSERR_FILE_ERROR                 5 + XSERR_BASE
+#define XSERR_BAD_RESOURCE_FORMAT        6 + XSERR_BASE
+#define XSERR_BAD_LABEL_FORMAT           7 + XSERR_BASE
+#define XSERR_RESOURCE_NOT_LABELED       8 + XSERR_BASE
+#define XSERR_RESOURCE_ALREADY_LABELED   9 + XSERR_BASE
+#define XSERR_WRONG_POLICY_TYPE         10 + XSERR_BASE
+#define XSERR_BOOTPOLICY_INSTALLED      11 + XSERR_BASE
+#define XSERR_NO_DEFAULT_BOOT_TITLE     12 + XSERR_BASE
+#define XSERR_POLICY_LOAD_FAILED        13 + XSERR_BASE
+#define XSERR_POLICY_LOADED             14 + XSERR_BASE
+#define XSERR_POLICY_TYPE_UNSUPPORTED   15 + XSERR_BASE
+#define XSERR_BAD_CONFLICTSET           20 + XSERR_BASE
+#define XSERR_RESOURCE_IN_USE           21 + XSERR_BASE
+#define XSERR_BAD_POLICY_NAME           22 + XSERR_BASE
+#define XSERR_RESOURCE_ACCESS           23 + XSERR_BASE
+#define XSERR_HV_OP_FAILED              24 + XSERR_BASE
+#define XSERR_BOOTPOLICY_INSTALL_ERROR  25 + XSERR_BASE
+
+
+/**
+ * Free the given xen_xspolicy.  The given handle must have been allocated
+ * by this library.
+ */
+extern void
+xen_xspolicy_free(xen_xspolicy xspolicy);
+
+
+typedef struct xen_xspolicy_set
+{
+    size_t size;
+    xen_xspolicy *contents[];
+} xen_xspolicy_set;
+
+/**
+ * Allocate a xen_xspolicy_set of the given size.
+ */
+extern xen_xspolicy_set *
+xen_xspolicy_set_alloc(size_t size);
+
+/**
+ * Free the given xen_xspolicy_set.  The given set must have been allocated
+ * by this library.
+ */
+extern void
+xen_xspolicy_set_free(xen_xspolicy_set *set);
+
+
+typedef struct xen_xspolicy_record
+{
+    xen_xspolicy handle;
+    char *uuid;
+    char *repr;
+    xs_instantiationflags flags;
+    xs_type type;
+} xen_xspolicy_record;
+
+/**
+ * Allocate a xen_xspolicy_record.
+ */
+extern xen_xspolicy_record *
+xen_xspolicy_record_alloc(void);
+
+/**
+ * Free the given xen_xspolicy_record, and all referenced values.  The
+ * given record must have been allocated by this library.
+ */
+extern void
+xen_xspolicy_record_free(xen_xspolicy_record *record);
+
+
+typedef struct xen_xspolicy_record_opt
+{
+    bool is_record;
+    union
+    {
+        xen_xspolicy handle;
+        xen_xspolicy_record *record;
+    } u;
+} xen_xspolicy_record_opt;
+
+/**
+ * Allocate a xen_xspolicy_record_opt.
+ */
+extern xen_xspolicy_record_opt *
+xen_xspolicy_record_opt_alloc(void);
+
+/**
+ * Free the given xen_xspolicy_record_opt, and all referenced values.  The
+ * given record_opt must have been allocated by this library.
+ */
+extern void
+xen_xspolicy_record_opt_free(xen_xspolicy_record_opt *record_opt);
+
+
+typedef struct xen_xspolicy_record_set
+{
+    size_t size;
+    xen_xspolicy_record *contents[];
+} xen_xspolicy_record_set;
+
+/**
+ * Allocate a xen_xspolicy_record_set of the given size.
+ */
+extern xen_xspolicy_record_set *
+xen_xspolicy_record_set_alloc(size_t size);
+
+/**
+ * Free the given xen_xspolicy_record_set, and all referenced values.  The
+ * given set must have been allocated by this library.
+ */
+extern void
+xen_xspolicy_record_set_free(xen_xspolicy_record_set *set);
+
+/**
+ * Data structures and function declarations for an XS Policy's state
+ * information.
+ */
+typedef struct xen_xs_policystate
+{
+    xen_xspolicy_record_opt *xs_ref;
+    int64_t xserr;
+    char *repr;
+    xs_type type;
+    xs_instantiationflags flags;
+    char *version;
+    char *errors;
+} xen_xs_policystate;
+
+void
+xen_xs_policystate_free(xen_xs_policystate *state);
+
+
+/**
+ * Get the referenced policy's record.
+ */
+bool
+xen_xspolicy_get_record(xen_session *session, xen_xspolicy_record **result,
+                        xen_xspolicy xspolicy);
+
+/**
+ * Get the UUID field of the given policy.
+ */
+bool
+xen_xspolicy_get_uuid(xen_session *session, char **result,
+                      xen_xspolicy xspolicy);
+
+/**
+ * Get a policy given it's UUID
+ */
+bool
+xen_xspolicy_get_by_uuid(xen_session *session, xen_xspolicy *result,
+                         char *uuid);
+
+
+/**
+ * Get the types of policies supported by the system.
+ */
+bool
+xen_xspolicy_get_xstype(xen_session *session, xs_type *result);
+
+
+/**
+ * Get information about the currently managed policy.
+ * (The API allows only one policy to be on the system.)
+ */
+bool
+xen_xspolicy_get_xspolicy(xen_session *session, xen_xs_policystate **result);
+
+/**
+ * Activate the referenced policy by loading it into the hypervisor.
+ */
+bool
+xen_xspolicy_activate_xspolicy(xen_session *session, int64_t *result,
+                               xen_xspolicy xspolicy,
+                               xs_instantiationflags flags);
+
+
+/**
+ * Set the system's policy to the given information comprising
+ * type of policy, the xml representation of the policy, some flags
+ * on whether to load the policy immediately and whether to overwrite
+ * an existing policy on the system.
+ */
+bool
+xen_xspolicy_set_xspolicy(xen_session *session, xen_xs_policystate **result,
+                          xs_type type, char *repr, int64_t flags,
+                          bool overwrite);
+
+
+/**
+ * Remove any policy from having the system booted with.
+ */
+extern bool
+xen_xspolicy_rm_xsbootpolicy(xen_session *session);
+
+/**
+ * Retrieve all labeled resources.
+ */
+extern bool
+xen_xspolicy_get_labeled_resources(xen_session *session,
+                                   xen_string_string_map **resources);
+
+/**
+ * Label a resource such as for example a hard drive partition or file
+ */
+extern bool
+xen_xspolicy_set_resource_label(xen_session *session,
+                                char *resource, char *label,
+                                char *oldlabel);
+
+/**
+ * Get the label of a resource.
+ */
+extern bool
+xen_xspolicy_get_resource_label(xen_session *session, char **label,
+                                char *resource);
+
+#endif
diff -r 37833b33ae77 -r 4492a0285bae 
tools/libxen/include/xen/api/xen_xspolicy_decl.h
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/libxen/include/xen/api/xen_xspolicy_decl.h  Fri Jul 27 08:15:16 
2007 -0600
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007, IBM Corp.
+ * Copyright (c) 2007, XenSource Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
+ */
+
+#ifndef XEN_XSPOLICY_DECL_H
+#define XEN_XSPOLICY_DECL_H
+
+typedef void *xen_xspolicy;
+
+struct xen_xspolicy_set;
+struct xen_xspolicy_record;
+struct xen_xspolicy_record_set;
+struct xen_xspolicy_record_opt;
+struct xen_xspolicy_record_opt_set;
+
+#endif
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/src/xen_acmpolicy.c
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/libxen/src/xen_acmpolicy.c  Fri Jul 27 08:15:16 2007 -0600
@@ -0,0 +1,234 @@
+/*
+ * Copyright (c) 2007, IBM Corp.
+ * Copyright (c) 2007, XenSource Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
+ */
+
+
+#include <stddef.h>
+#include <stdlib.h>
+
+#include "xen_internal.h"
+#include "xen/api/xen_common.h"
+#include "xen/api/xen_xspolicy.h"
+#include "xen/api/xen_acmpolicy.h"
+
+
+static const struct_member xen_acmpolicy_record_struct_members[] =
+    {
+        { .key = "uuid",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_acmpolicy_record, uuid) },
+        { .key = "flags",
+          .type = &abstract_type_int,
+          .offset = offsetof(xen_acmpolicy_record, flags) },
+        { .key = "repr",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_acmpolicy_record, repr) },
+        { .key = "type",
+          .type = &abstract_type_int,
+          .offset = offsetof(xen_acmpolicy_record, type) },
+    };
+
+const abstract_type xen_acmpolicy_record_abstract_type_ =
+    {
+       .typename = STRUCT,
+       .struct_size = sizeof(xen_acmpolicy_record),
+       .member_count =
+          sizeof(xen_acmpolicy_record_struct_members) / sizeof(struct_member),
+       .members = xen_acmpolicy_record_struct_members
+    };
+
+
+static const struct_member xen_acm_header_struct_members[] =
+    {
+        { .key = "policyname",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_acm_header, policyname) },
+        { .key = "policyurl",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_acm_header, policyurl) },
+        { .key = "date",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_acm_header, date) },
+        { .key = "reference",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_acm_header, reference) },
+        { .key = "namespaceurl",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_acm_header, namespaceurl) },
+        { .key = "version",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_acm_header, version) },
+    };
+
+const abstract_type xen_acm_header_abstract_type_ =
+    {
+        .typename = STRUCT,
+        .struct_size = sizeof(xen_acm_header),
+        .member_count =
+            sizeof(xen_acm_header_struct_members) /
+            sizeof(struct_member),
+        .members = xen_acm_header_struct_members,
+    };
+
+void
+xen_acm_header_free(xen_acm_header *shdr)
+{
+    if (shdr == NULL)
+    {
+        return;
+    }
+    free(shdr->policyname);
+    free(shdr->policyurl);
+    free(shdr->date);
+    free(shdr->reference);
+    free(shdr->namespaceurl);
+    free(shdr->version);
+    free(shdr);
+}
+
+
+void
+xen_acmpolicy_record_free(xen_acmpolicy_record *record)
+{
+    if (record == NULL)
+    {
+        return;
+    }
+    free(record->handle);
+    free(record->uuid);
+    free(record->repr);
+    free(record);
+}
+
+
+
+bool
+xen_acmpolicy_get_record(xen_session *session, xen_acmpolicy_record **result,
+                         xen_xspolicy xspolicy)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy }
+        };
+
+    abstract_type result_type = xen_acmpolicy_record_abstract_type_;
+
+    *result = NULL;
+    XEN_CALL_("ACMPolicy.get_record");
+
+    if (session->ok)
+    {
+       (*result)->handle = xen_strdup_((*result)->uuid);
+    }
+
+    return session->ok;
+}
+
+
+bool
+xen_acmpolicy_get_header(xen_session *session,
+                         xen_acm_header **result,
+                         xen_xspolicy xspolicy)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy },
+        };
+
+    abstract_type result_type = xen_acm_header_abstract_type_;
+
+    *result = NULL;
+    XEN_CALL_("ACMPolicy.get_header");
+    return session->ok;
+}
+
+
+bool
+xen_acmpolicy_get_xml(xen_session *session,
+                      char **result,
+                      xen_xspolicy xspolicy)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy },
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("ACMPolicy.get_xml");
+    return session->ok;
+}
+
+
+bool
+xen_acmpolicy_get_map(xen_session *session,
+                      char **result,
+                      xen_xspolicy xspolicy)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy },
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("ACMPolicy.get_map");
+    return session->ok;
+}
+
+
+bool
+xen_acmpolicy_get_binary(xen_session *session, char **result,
+                         xen_xspolicy xspolicy)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy },
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("ACMPolicy.get_binary");
+    return session->ok;
+}
+
+
+bool
+xen_acmpolicy_get_uuid(xen_session *session, char **result,
+                       xen_xspolicy xspolicy)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy }
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("ACMPolicy.get_uuid");
+    return session->ok;
+}
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/src/xen_vdi.c
--- a/tools/libxen/src/xen_vdi.c        Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxen/src/xen_vdi.c        Fri Jul 27 08:15:16 2007 -0600
@@ -534,3 +534,42 @@ xen_vdi_get_uuid(xen_session *session, c
     XEN_CALL_("VDI.get_uuid");
     return session->ok;
 }
+
+
+bool
+xen_vdi_set_security_label(xen_session *session, int64_t *result, xen_vdi vdi,
+                           char *label, char *oldlabel)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = vdi },
+            { .type = &abstract_type_string,
+              .u.string_val = label },
+            { .type = &abstract_type_string,
+              .u.string_val = oldlabel },
+        };
+
+    abstract_type result_type = abstract_type_int;
+
+    *result = 0;
+    XEN_CALL_("VDI.set_security_label");
+    return session->ok;
+}
+
+
+bool
+xen_vdi_get_security_label(xen_session *session, char **result, xen_vdi vdi)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = vdi },
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("VDI.get_security_label");
+    return session->ok;
+}
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/src/xen_vif.c
--- a/tools/libxen/src/xen_vif.c        Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxen/src/xen_vif.c        Fri Jul 27 08:15:16 2007 -0600
@@ -575,3 +575,42 @@ xen_vif_get_uuid(xen_session *session, c
     XEN_CALL_("VIF.get_uuid");
     return session->ok;
 }
+
+
+bool
+xen_vif_set_security_label(xen_session *session, int64_t *result, xen_vif vif,
+                           char *label, char *oldlabel)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = vif },
+            { .type = &abstract_type_string,
+              .u.string_val = label },
+            { .type = &abstract_type_string,
+              .u.string_val = oldlabel },
+        };
+
+    abstract_type result_type = abstract_type_int;
+
+    *result = 0;
+    XEN_CALL_("VIF.set_security_label");
+    return session->ok;
+}
+
+
+bool
+xen_vif_get_security_label(xen_session *session, char **result, xen_vif vif)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = vif },
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("VIF.get_security_label");
+    return session->ok;
+}
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/src/xen_vm.c
--- a/tools/libxen/src/xen_vm.c Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/libxen/src/xen_vm.c Fri Jul 27 08:15:16 2007 -0600
@@ -162,7 +162,10 @@ static const struct_member xen_vm_record
           .offset = offsetof(xen_vm_record, metrics) },
         { .key = "guest_metrics",
           .type = &abstract_type_ref,
-          .offset = offsetof(xen_vm_record, guest_metrics) }
+          .offset = offsetof(xen_vm_record, guest_metrics) },
+        { .key = "security_label",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_vm_record, security_label) }
     };
 
 const abstract_type xen_vm_record_abstract_type_ =
@@ -206,6 +209,7 @@ xen_vm_record_free(xen_vm_record *record
     xen_string_string_map_free(record->other_config);
     xen_vm_metrics_record_opt_free(record->metrics);
     xen_vm_guest_metrics_record_opt_free(record->guest_metrics);
+    free(record->security_label);
     free(record);
 }
 
@@ -1738,3 +1742,42 @@ xen_vm_get_uuid(xen_session *session, ch
     XEN_CALL_("VM.get_uuid");
     return session->ok;
 }
+
+
+bool
+xen_vm_set_security_label(xen_session *session, int64_t *result, xen_vm vm,
+                          char *label, char *oldlabel)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = vm },
+            { .type = &abstract_type_string,
+              .u.string_val = label },
+            { .type = &abstract_type_string,
+              .u.string_val = oldlabel },
+        };
+
+    abstract_type result_type = abstract_type_int;
+
+    *result = 0;
+    XEN_CALL_("VM.set_security_label");
+    return session->ok;
+}
+
+
+bool
+xen_vm_get_security_label(xen_session *session, char **result, xen_vm vm)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = vm },
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("VM.get_security_label");
+    return session->ok;
+}
diff -r 37833b33ae77 -r 4492a0285bae tools/libxen/src/xen_xspolicy.c
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/libxen/src/xen_xspolicy.c   Fri Jul 27 08:15:16 2007 -0600
@@ -0,0 +1,327 @@
+/*
+ * Copyright (c) 2007, IBM Corp.
+ * Copyright (c) 2007, XenSource Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
+ */
+
+
+#include <stddef.h>
+#include <stdlib.h>
+
+#include "xen/api/xen_common.h"
+#include "xen/api/xen_internal.h"
+#include "xen/api/xen_xspolicy.h"
+
+
+XEN_FREE(xen_xspolicy)
+XEN_SET_ALLOC_FREE(xen_xspolicy)
+XEN_RECORD_OPT_FREE(xen_xspolicy)
+
+static const struct_member xen_xspolicy_record_struct_members[] =
+    {
+        { .key = "uuid",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_xspolicy_record, uuid) },
+        { .key = "flags",
+          .type = &abstract_type_int,
+          .offset = offsetof(xen_xspolicy_record, flags) },
+        { .key = "repr",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_xspolicy_record, repr) },
+        { .key = "type",
+          .type = &abstract_type_int,
+          .offset = offsetof(xen_xspolicy_record, type) },
+    };
+
+const abstract_type xen_xspolicy_record_abstract_type_ =
+    {
+       .typename = STRUCT,
+       .struct_size = sizeof(xen_xspolicy_record),
+       .member_count =
+           sizeof(xen_xspolicy_record_struct_members) / sizeof(struct_member),
+       .members = xen_xspolicy_record_struct_members
+    };
+
+
+static const struct_member xen_xs_policystate_struct_members[] =
+    {
+        { .key = "xs_ref",
+          .type = &abstract_type_ref,
+          .offset = offsetof(xen_xs_policystate, xs_ref) },
+        { .key = "xserr",
+          .type = &abstract_type_int,
+          .offset = offsetof(xen_xs_policystate, xserr) },
+        { .key = "repr",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_xs_policystate, repr) },
+        { .key = "type",
+          .type = &abstract_type_int,
+          .offset = offsetof(xen_xs_policystate, type) },
+        { .key = "flags",
+          .type = &abstract_type_int,
+          .offset = offsetof(xen_xs_policystate, flags) },
+        { .key = "version",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_xs_policystate, version) },
+        { .key = "errors",
+          .type = &abstract_type_string,
+          .offset = offsetof(xen_xs_policystate, errors) },
+    };
+
+const abstract_type xen_xs_policystate_abstract_type_ =
+    {
+        .typename = STRUCT,
+        .struct_size = sizeof(xen_xs_policystate),
+        .member_count =
+            sizeof(xen_xs_policystate_struct_members) /
+            sizeof(struct_member),
+        .members = xen_xs_policystate_struct_members,
+    };
+
+
+
+
+void
+xen_xs_policystate_free(xen_xs_policystate *state)
+{
+    if (state == NULL)
+    {
+        return;
+    }
+    xen_xspolicy_record_opt_free(state->xs_ref);
+    free(state->repr);
+    free(state->errors);
+    free(state->version);
+    free(state);
+}
+
+
+void
+xen_xspolicy_record_free(xen_xspolicy_record *record)
+{
+    if (record == NULL)
+    {
+        return;
+    }
+    free(record->handle);
+    free(record->uuid);
+    free(record->repr);
+    free(record);
+}
+
+
+bool
+xen_xspolicy_get_record(xen_session *session, xen_xspolicy_record **result,
+                        xen_xspolicy xspolicy)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy }
+        };
+
+    abstract_type result_type = xen_xspolicy_record_abstract_type_;
+
+    *result = NULL;
+    XEN_CALL_("XSPolicy.get_record");
+
+    if (session->ok)
+    {
+       (*result)->handle = xen_strdup_((*result)->uuid);
+    }
+
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_get_uuid(xen_session *session, char **result,
+                      xen_xspolicy xspolicy)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy }
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("XSPolicy.get_uuid");
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_get_by_uuid(xen_session *session, xen_xspolicy *result,
+                         char *uuid)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = uuid }
+        };
+
+    abstract_type result_type = abstract_type_string;
+
+    *result = NULL;
+    XEN_CALL_("XSPolicy.get_by_uuid");
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_get_xstype(xen_session *session, xs_type *result)
+{
+    abstract_value param_values[] =
+        {
+        };
+
+    abstract_type result_type = abstract_type_int;
+
+    *result = 0;
+    XEN_CALL_("XSPolicy.get_xstype");
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_set_xspolicy(xen_session *session, xen_xs_policystate **result,
+                          xs_type type, char *repr,
+                          xs_instantiationflags flags,
+                          bool overwrite)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_int,
+              .u.int_val = type },
+            { .type = &abstract_type_string,
+              .u.string_val = repr },
+            { .type = &abstract_type_int,
+              .u.int_val = flags },
+            { .type = &abstract_type_bool,
+              .u.bool_val = overwrite }
+        };
+
+    abstract_type result_type = xen_xs_policystate_abstract_type_;
+
+    *result = NULL;
+    XEN_CALL_("XSPolicy.set_xspolicy");
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_get_xspolicy(xen_session *session, xen_xs_policystate **result)
+{
+    abstract_value param_values[] =
+        {
+        };
+
+    abstract_type result_type = xen_xs_policystate_abstract_type_;
+
+    *result = NULL;
+    XEN_CALL_("XSPolicy.get_xspolicy");
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_get_labeled_resources(xen_session *session,
+                                   xen_string_string_map **result)
+{
+    abstract_value param_values[] =
+        {
+        };
+
+    abstract_type result_type = abstract_type_string_string_map;
+
+    *result = NULL;
+    XEN_CALL_("XSPolicy.get_labeled_resources");
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_set_resource_label(xen_session *session,
+                                char *resource, char *label,
+                                char *oldlabel)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = resource },
+            { .type = &abstract_type_string,
+              .u.string_val = label },
+            { .type = &abstract_type_string,
+              .u.string_val = oldlabel },
+        };
+
+    xen_call_(session, "XSPolicy.set_resource_label", param_values, 3,
+                       NULL, NULL);
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_get_resource_label(xen_session *session, char **result,
+                                char *resource)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = resource },
+        };
+
+    abstract_type result_type = abstract_type_string;
+    XEN_CALL_("XSPolicy.get_resource_label");
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_rm_xsbootpolicy(xen_session *session)
+{
+    abstract_value param_values[] =
+        {
+        };
+
+    xen_call_(session, "XSPolicy.rm_xsbootpolicy", param_values, 0,
+                       NULL, NULL);
+    return session->ok;
+}
+
+
+bool
+xen_xspolicy_activate_xspolicy(xen_session *session,
+                               xs_instantiationflags *result,
+                               xen_xspolicy xspolicy,
+                               xs_instantiationflags flags)
+{
+    abstract_value param_values[] =
+        {
+            { .type = &abstract_type_string,
+              .u.string_val = xspolicy },
+            { .type = &abstract_type_int,
+              .u.int_val = flags },
+        };
+
+    abstract_type result_type = abstract_type_int;
+
+    *result = 0;
+    XEN_CALL_("XSPolicy.activate_xspolicy");
+    return session->ok;
+}
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/lowlevel/acm/acm.c
--- a/tools/python/xen/lowlevel/acm/acm.c       Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/lowlevel/acm/acm.c       Fri Jul 27 08:15:16 2007 -0600
@@ -148,9 +148,10 @@ static PyObject *getdecision(PyObject * 
     char *arg1_name, *arg1, *arg2_name, *arg2, *decision = NULL;
     struct acm_getdecision getdecision;
     int xc_handle, rc;
-
-    if (!PyArg_ParseTuple(args, "ssss", &arg1_name,
-                          &arg1, &arg2_name, &arg2)) {
+    uint32_t hooktype;
+
+    if (!PyArg_ParseTuple(args, "ssssi", &arg1_name,
+                          &arg1, &arg2_name, &arg2, &hooktype)) {
         return NULL;
     }
 
@@ -163,7 +164,7 @@ static PyObject *getdecision(PyObject * 
     (strcmp(arg2_name, "domid") && strcmp(arg2_name, "ssidref")))
         return NULL;
 
-    getdecision.hook = ACMHOOK_sharing;
+    getdecision.hook = hooktype;
     if (!strcmp(arg1_name, "domid")) {
         getdecision.get_decision_by1 = ACM_GETBY_domainid;
         getdecision.id1.domainid = atoi(arg1);
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/util/acmpolicy.py
--- a/tools/python/xen/util/acmpolicy.py        Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/util/acmpolicy.py        Fri Jul 27 08:15:16 2007 -0600
@@ -57,12 +57,20 @@ class ACMPolicy(XSPolicy):
     def __init__(self, name=None, dom=None, ref=None, xml=None):
         if name:
             self.name = name
-            self.dom = minidom.parse(self.path_from_policy_name(name))
+            try:
+                self.dom = minidom.parse(self.path_from_policy_name(name))
+            except Exception, e:
+                raise SecurityError(-xsconstants.XSERR_XML_PROCESSING,
+                                    str(e))
         elif dom:
             self.dom = dom
             self.name = self.get_name()
         elif xml:
-            self.dom = minidom.parseString(xml)
+            try:
+                self.dom = minidom.parseString(xml)
+            except Exception, e:
+                raise SecurityError(-xsconstants.XSERR_XML_PROCESSING,
+                                    str(e))
             self.name = self.get_name()
         rc = self.validate()
         if rc != xsconstants.XSERR_SUCCESS:
@@ -114,7 +122,8 @@ class ACMPolicy(XSPolicy):
             rc = -xsconstants.XSERR_GENERAL_FAILURE
         if rc != xsconstants.XSERR_SUCCESS:
             log.warn("XML did not validate against schema")
-        rc = self.__validate_name_and_labels()
+        if rc == xsconstants.XSERR_SUCCESS:
+            rc = self.__validate_name_and_labels()
         return rc
 
     def __validate_name_and_labels(self):
@@ -481,7 +490,8 @@ class ACMPolicy(XSPolicy):
         strings = []
         i = 0
         while i < len(node.childNodes):
-            if node.childNodes[i].nodeName == "Type":
+            if node.childNodes[i].nodeName == "Type" and \
+               len(node.childNodes[i].childNodes) > 0:
                 strings.append(node.childNodes[i].childNodes[0].nodeValue)
             i += 1
         return strings
@@ -564,7 +574,8 @@ class ACMPolicy(XSPolicy):
             while i < len(node.childNodes):
                 if node.childNodes[i].nodeName == "VirtualMachineLabel":
                     name = self.policy_dom_get(node.childNodes[i], "Name")
-                    strings.append(name.childNodes[0].nodeValue)
+                    if len(name.childNodes) > 0:
+                        strings.append(name.childNodes[0].nodeValue)
                 i += 1
         return strings
 
@@ -592,43 +603,46 @@ class ACMPolicy(XSPolicy):
             i = 0
             while i < len(node.childNodes):
                 if node.childNodes[i].nodeName == "VirtualMachineLabel":
-                    _res = {}
-                    _res['type'] = xsconstants.ACM_LABEL_VM
                     name = self.policy_dom_get(node.childNodes[i], "Name")
-                    _res['name'] = name.childNodes[0].nodeValue
-                    stes = self.policy_dom_get(node.childNodes[i],
-                                               "SimpleTypeEnforcementTypes")
-                    if stes:
-                        _res['stes'] = self.policy_get_types(stes)
-                    else:
-                        _res['stes'] = []
-                    chws = self.policy_dom_get(node.childNodes[i],
-                                               "ChineseWallTypes")
-                    if chws:
-                        _res['chws'] = self.policy_get_types(chws)
-                    else:
-                        _res['chws'] = []
-                    res.append(_res)
+                    if len(name.childNodes) > 0:
+                        _res = {}
+                        _res['type'] = xsconstants.ACM_LABEL_VM
+                        _res['name'] = name.childNodes[0].nodeValue
+                        stes = self.policy_dom_get(node.childNodes[i],
+                                                 "SimpleTypeEnforcementTypes")
+                        if stes:
+                           _res['stes'] = self.policy_get_types(stes)
+                        else:
+                            _res['stes'] = []
+                        chws = self.policy_dom_get(node.childNodes[i],
+                                                   "ChineseWallTypes")
+                        if chws:
+                            _res['chws'] = self.policy_get_types(chws)
+                        else:
+                            _res['chws'] = []
+                        res.append(_res)
                 i += 1
         return res
 
     def policy_get_stes_of_vmlabel(self, vmlabel):
         """ Get a list of all STEs of a given VMlabel """
         return self.__policy_get_stes_of_labeltype(vmlabel,
-                                                   "VirtualMachineLabel")
+                                        "/SubjectLabels", 
"VirtualMachineLabel")
 
     def policy_get_stes_of_resource(self, reslabel):
         """ Get a list of all resources of a given VMlabel """
-        return self.__policy_get_stes_of_labeltype(reslabel, "ResourceLabel")
-
-    def __policy_get_stes_of_labeltype(self, label, labeltype):
-        node = self.dom_get_node("SecurityLabelTemplate/SubjectLabels")
+        return self.__policy_get_stes_of_labeltype(reslabel,
+                                        "/ObjectLabels", "ResourceLabel")
+
+    def __policy_get_stes_of_labeltype(self, label, path, labeltype):
+        node = self.dom_get_node("SecurityLabelTemplate" + path)
         if node:
             i = 0
             while i < len(node.childNodes):
                 if node.childNodes[i].nodeName == labeltype:
                     name = self.policy_dom_get(node.childNodes[i], "Name")
-                    if name.childNodes[0].nodeValue == label:
+                    if len(name.childNodes) > 0 and \
+                       name.childNodes[0].nodeValue == label:
                         stes = self.policy_dom_get(node.childNodes[i],
                                             "SimpleTypeEnforcementTypes")
                         if not stes:
@@ -649,7 +663,8 @@ class ACMPolicy(XSPolicy):
             return False
         for res in resources:
             res_stes = self.policy_get_stes_of_resource(res)
-            if len( set(res_stes).union( set(vm_stes) ) ) == 0:
+            if len(res_stes) == 0 or \
+               len( set(res_stes).intersection( set(vm_stes) ) ) == 0:
                 return False
         return True
 
@@ -662,7 +677,7 @@ class ACMPolicy(XSPolicy):
                 if node.childNodes[i].nodeName == labeltype:
                     name = self.policy_dom_get(node.childNodes[i], "Name")
                     from_name = name.getAttribute("from")
-                    if from_name:
+                    if from_name and len(name.childNodes) > 0:
                         res.update({from_name : name.childNodes[0].nodeValue})
                 i += 1
         return res
@@ -700,7 +715,7 @@ class ACMPolicy(XSPolicy):
                     name = self.policy_dom_get(node.childNodes[i], "Name")
                     stes = self.policy_dom_get(node.childNodes[i],
                                           "SimpleTypeEnforcementTypes")
-                    if stes:
+                    if stes and len(name.childNodes) > 0:
                         strings.append(name.childNodes[0].nodeValue)
                 i += 1
         return strings
@@ -715,18 +730,19 @@ class ACMPolicy(XSPolicy):
             i = 0
             while i < len(node.childNodes):
                 if node.childNodes[i].nodeName == "ResourceLabel":
-                    _res = {}
-                    _res['type'] = xsconstants.ACM_LABEL_RES
                     name = self.policy_dom_get(node.childNodes[i], "Name")
-                    _res['name'] = name.childNodes[0].nodeValue
-                    stes = self.policy_dom_get(node.childNodes[i],
-                                               "SimpleTypeEnforcementTypes")
-                    if stes:
-                        _res['stes'] = self.policy_get_types(stes)
-                    else:
-                        _res['stes'] = []
-                    _res['chws'] = []
-                    res.append(_res)
+                    if len(name.childNodes) > 0:
+                        _res = {}
+                        _res['type'] = xsconstants.ACM_LABEL_RES
+                        _res['name'] = name.childNodes[0].nodeValue
+                        stes = self.policy_dom_get(node.childNodes[i],
+                                                   
"SimpleTypeEnforcementTypes")
+                        if stes:
+                            _res['stes'] = self.policy_get_types(stes)
+                        else:
+                            _res['stes'] = []
+                        _res['chws'] = []
+                        res.append(_res)
                 i += 1
         return res
 
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/util/security.py
--- a/tools/python/xen/util/security.py Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/util/security.py Fri Jul 27 08:15:16 2007 -0600
@@ -61,6 +61,10 @@ empty_line_re = re.compile("^\s*$")
 empty_line_re = re.compile("^\s*$")
 binary_name_re = re.compile(".*[chwall|ste|chwall_ste].*\.bin", re.IGNORECASE)
 policy_name_re = re.compile(".*[chwall|ste|chwall_ste].*", re.IGNORECASE)
+
+#decision hooks known to the hypervisor
+ACMHOOK_sharing = 1
+ACMHOOK_authorization = 2
 
 #other global variables
 NULL_SSIDREF = 0
@@ -155,75 +159,6 @@ def calc_dom_ssidref_from_info(info):
     raise VmError("security.calc_dom_ssidref_from_info: info of type '%s'"
                   "not supported." % type(info))
 
-# Assumes a 'security' info  [security access_control ...] [ssidref ...]
-def get_security_info(info, field):
-    """retrieves security field from self.info['security'])
-    allowed search fields: ssidref, label, policy
-    """
-    if isinstance(info, dict):
-        security = info['security']
-    elif isinstance(info, list):
-        security = sxp.child_value(info, 'security')
-    if not security:
-        if field == 'ssidref':
-            #return default ssid
-            return 0
-        else:
-            err("Security information not found in info struct.")
-
-    if field == 'ssidref':
-        search = 'ssidref'
-    elif field in ['policy', 'label']:
-            search = 'access_control'
-    else:
-        err("Illegal field in get_security_info.")
-
-    for idx in range(0, len(security)):
-        if search != security[idx][0]:
-            continue
-        if search == 'ssidref':
-            return int(security[idx][1])
-        else:
-            for aidx in range(0, len(security[idx])):
-                if security[idx][aidx][0] == field:
-                    return str(security[idx][aidx][1])
-
-    if search == 'ssidref':
-        return 0
-    else:
-        return None
-
-
-def get_security_printlabel(info):
-    """retrieves printable security label from self.info['security']),
-    preferably the label name and otherwise (if label is not specified
-    in config and cannot be found in mapping file) a hex string of the
-    ssidref or none if both not available
-    """
-    try:
-        if not on():
-            return "INACTIVE"
-        if active_policy in ["DEFAULT"]:
-            return "DEFAULT"
-
-        printlabel = get_security_info(info, 'label')
-        if printlabel:
-            return printlabel
-        ssidref = get_security_info(info, 'ssidref')
-        if not ssidref:
-            return None
-        #try to translate ssidref to a label
-        result = ssidref2label(ssidref)
-        if not result:
-            printlabel = "0x%08x" % ssidref
-        else:
-            printlabel = result
-        return printlabel
-    except ACMError:
-        #don't throw an exception in xm list
-        return "ERROR"
-
-
 
 def getmapfile(policyname):
     """
@@ -522,7 +457,8 @@ def get_decision(arg1, arg2):
         err("Invalid id or ssidref type, string or int required")
 
     try:
-        decision = acm.getdecision(arg1[0], arg1[1], arg2[0], arg2[1])
+        decision = acm.getdecision(arg1[0], arg1[1], arg2[0], arg2[1],
+                                   ACMHOOK_sharing)
     except:
         err("Cannot determine decision.")
 
@@ -530,6 +466,21 @@ def get_decision(arg1, arg2):
         return decision
     else:
         err("Cannot determine decision (Invalid parameter).")
+
+
+def has_authorization(ssidref):
+    """ Check if the domain with the given ssidref has authorization to
+        run on this system. To have authoriztion dom0's STE types must
+        be a superset of that of the domain's given through its ssidref.
+    """
+    rc = True
+    dom0_ssidref = int(acm.getssid(0)['ssidref'])
+    decision = acm.getdecision('ssidref', str(dom0_ssidref),
+                               'ssidref', str(ssidref),
+                               ACMHOOK_authorization)
+    if decision == "DENIED":
+        rc = False
+    return rc
 
 
 def hv_chg_policy(bin_pol, del_array, chg_array):
@@ -868,9 +819,10 @@ def is_resource_in_use(resource):
             lst.append(dominfo)
     return lst
 
-def devices_equal(res1, res2):
+def devices_equal(res1, res2, mustexist=True):
     """ Determine whether two devices are equal """
-    return (unify_resname(res1) == unify_resname(res2))
+    return (unify_resname(res1, mustexist) ==
+            unify_resname(res2, mustexist))
 
 def is_resource_in_use_by_dom(dominfo, resource):
     """ Determine whether a resources is in use by a given domain
@@ -886,7 +838,7 @@ def is_resource_in_use_by_dom(dominfo, r
         dev = devs[uuid]
         if len(dev) >= 2 and dev[1].has_key('uname'):
             # dev[0] is type, i.e. 'vbd'
-            if devices_equal(dev[1]['uname'], resource):
+            if devices_equal(dev[1]['uname'], resource, mustexist=False):
                 log.info("RESOURCE IN USE: Domain %d uses %s." %
                          (dominfo.domid, resource))
                 return True
@@ -899,7 +851,7 @@ def get_domain_resources(dominfo):
         Entries are strored in the following formats:
           tap:qcow:/path/xyz.qcow
     """
-    resources = { 'vbd' : [], 'tap' : []}
+    resources = { 'vbd' : [], 'tap' : [], 'vif' : []}
     devs = dominfo.info['devices']
     uuids = devs.keys()
     for uuid in uuids:
@@ -907,6 +859,15 @@ def get_domain_resources(dominfo):
         typ = dev[0]
         if typ in [ 'vbd', 'tap' ]:
             resources[typ].append(dev[1]['uname'])
+        if typ in [ 'vif' ]:
+            sec_lab = dev[1].get('security_label')
+            if sec_lab:
+                resources[typ].append(sec_lab)
+            else:
+                resources[typ].append("%s:%s:%s" %
+                                      (xsconstants.ACM_POLICY_ID,
+                                       active_policy,
+                                       "unlabeled"))
 
     return resources
 
@@ -942,23 +903,36 @@ def __resources_compatible_with_vmlabel(
         dictionary of the resource name to resource label mappings
         under which the evaluation should be done.
     """
+    def collect_labels(reslabels, s_label, polname):
+        if len(s_label) != 3 or polname != s_label[1]:
+            return False
+        label = s_label[2]
+        if not label in reslabels:
+            reslabels.append(label)
+        return True
+
     resources = get_domain_resources(dominfo)
     reslabels = []  # all resource labels
+
     polname = xspol.get_name()
-    for key in resources.keys():
-        for res in resources[key]:
-            try:
-                tmp = access_control[res]
-                if len(tmp) != 3:
+    for key, value in resources.items():
+        if key in [ 'vbd', 'tap' ]:
+            for res in resources[key]:
+                try:
+                    label = access_control[res]
+                    if not collect_labels(reslabels, label, polname):
+                        return False
+                except:
                     return False
-
-                if polname != tmp[1]:
+        elif key in [ 'vif' ]:
+            for xapi_label in value:
+                label = xapi_label.split(":")
+                if not collect_labels(reslabels, label, polname):
                     return False
-                label = tmp[2]
-                if not label in reslabels:
-                    reslabels.append(label)
-            except:
-                return False
+        else:
+            log.error("Unhandled device type: %s" % key)
+            return False
+
     # Check that all resource labes have a common STE type with the
     # vmlabel
     rc = xspol.policy_check_vmlabel_against_reslabels(vmlabel, reslabels)
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendAPI.py
--- a/tools/python/xen/xend/XendAPI.py  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/XendAPI.py  Fri Jul 27 08:15:16 2007 -0600
@@ -1410,22 +1410,22 @@ class XendAPI(object):
     def VM_set_memory_dynamic_max(self, session, vm_ref, mem):
         dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
         dom.set_memory_dynamic_max(int(mem))
-        return xen_api_success_void()
+        return self._VM_save(dom)
 
     def VM_set_memory_dynamic_min(self, session, vm_ref, mem):
         dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
         dom.set_memory_dynamic_min(int(mem))
-        return xen_api_success_void()
+        return self._VM_save(dom)
 
     def VM_set_memory_static_max(self, session, vm_ref, mem):
         dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
         dom.set_memory_static_max(int(mem))
-        return xen_api_success_void()
+        return self._VM_save(dom)
     
     def VM_set_memory_static_min(self, session, vm_ref, mem):
         dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
         dom.set_memory_static_min(int(mem))
-        return xen_api_success_void()
+        return self._VM_save(dom)
 
     def VM_set_memory_dynamic_max_live(self, session, vm_ref, mem):
         dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
@@ -1620,7 +1620,8 @@ class XendAPI(object):
         (rc, errors, oldlabel, new_ssidref) = \
                                  dom.set_security_label(sec_label, old_label)
         if rc != xsconstants.XSERR_SUCCESS:
-            return xen_api_error(['SECURITY_ERROR', rc])
+            return xen_api_error(['SECURITY_ERROR', rc,
+                                 xsconstants.xserr2string(-rc)])
         if rc == 0:
             rc = new_ssidref
         return xen_api_success(rc)
@@ -2083,6 +2084,25 @@ class XendAPI(object):
     def VIF_get_security_label(self, session, vif_ref):
         return self._VIF_get(vif_ref, 'security_label')
 
+    def _VIF_set(self, ref, prop, val, old_val):
+        return XendDomain.instance().set_dev_property_by_uuid(
+                       'vif', ref, prop, val, old_val)
+
+    def VIF_set_security_label(self, session, vif_ref, sec_lab, old_lab):
+        xendom = XendDomain.instance()
+        dom = xendom.get_vm_with_dev_uuid('vif', vif_ref)
+        if not dom:
+            return xen_api_error(['HANDLE_INVALID', 'VIF', vif_ref])
+
+        if dom._stateGet() == XEN_API_VM_POWER_STATE_RUNNING:
+            raise SecurityError(-xsconstants.XSERR_RESOURCE_IN_USE)
+
+        rc = self._VIF_set(vif_ref, 'security_label', sec_lab, old_lab)
+        if rc == False:
+            raise SecurityError(-xsconstants.XSERR_BAD_LABEL)
+        return xen_api_success(xsconstants.XSERR_SUCCESS)
+
+
     # Xen API: Class VIF_metrics
     # ----------------------------------------------------------------
 
@@ -2239,7 +2259,8 @@ class XendAPI(object):
         vdi = XendNode.instance().get_vdi_by_uuid(vdi_ref)
         rc = vdi.set_security_label(sec_lab, old_lab)
         if rc < 0:
-            return xen_api_error(['SECURITY_ERROR', rc])
+            return xen_api_error(['SECURITY_ERROR', rc,
+                                 xsconstants.xserr2string(-rc)])
         return xen_api_success(rc)
 
     def VDI_get_security_label(self, session, vdi_ref):
@@ -2357,11 +2378,13 @@ class XendAPI(object):
         return xen_api_success(cons)
 
     def console_get_location(self, session, console_ref):
+        xendom = XendDomain.instance()
         return xen_api_success(xendom.get_dev_property_by_uuid('console',
                                                                console_ref,
                                                                'location'))
 
     def console_get_protocol(self, session, console_ref):
+        xendom = XendDomain.instance()
         return xen_api_success(xendom.get_dev_property_by_uuid('console',
                                                                console_ref,
                                                                'protocol'))
@@ -2370,6 +2393,12 @@ class XendAPI(object):
         xendom = XendDomain.instance()        
         vm = xendom.get_vm_with_dev_uuid('console', console_ref)
         return xen_api_success(vm.get_uuid())
+    
+    def console_get_other_config(self, session, console_ref):
+        xendom = XendDomain.instance()        
+        return xen_api_success(xendom.get_dev_property_by_uuid('console',
+                                                               console_ref,
+                                                               'other_config'))
     
     # object methods
     def console_get_record(self, session, console_ref):
@@ -2409,6 +2438,13 @@ class XendAPI(object):
         except XendError, exn:
             return xen_api_error(['INTERNAL_ERROR', str(exn)])
 
+    def console_set_other_config(self, session, console_ref, other_config):
+        xd = XendDomain.instance()
+        vm = xd.get_vm_with_dev_uuid('console', console_ref)
+        vm.set_console_other_config(console_ref, other_config)
+        xd.managed_config_save(vm)
+        return xen_api_success_void()
+
     # Xen API: Class SR
     # ----------------------------------------------------------------
     SR_attr_ro = ['VDIs',
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendCheckpoint.py
--- a/tools/python/xen/xend/XendCheckpoint.py   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/XendCheckpoint.py   Fri Jul 27 08:15:16 2007 -0600
@@ -98,10 +98,6 @@ def save(fd, dominfo, network, live, dst
                 log.info("Domain %d suspended.", dominfo.getDomid())
                 dominfo.migrateDevices(network, dst, DEV_MIGRATE_STEP3,
                                        domain_name)
-                #send signal to device model for save
-                if hvm:
-                    log.info("release_devices for hvm domain")
-                    dominfo._releaseDevices(True)
                 tochild.write("done\n")
                 tochild.flush()
                 log.debug('Written done')
@@ -139,7 +135,7 @@ def save(fd, dominfo, network, live, dst
     except Exception, exn:
         log.exception("Save failed on domain %s (%s).", domain_name,
                       dominfo.getDomid())
-
+        
         dominfo.resumeDomain()
         log.debug("XendCheckpoint.save: resumeDomain")
 
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendConfig.py
--- a/tools/python/xen/xend/XendConfig.py       Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/XendConfig.py       Fri Jul 27 08:15:16 2007 -0600
@@ -128,6 +128,11 @@ XENAPI_PLATFORM_CFG = [ 'acpi', 'apic', 
                         'soundhw','stdvga', 'usb', 'usbdevice', 'vnc',
                         'vncconsole', 'vncdisplay', 'vnclisten',
                         'vncpasswd', 'vncunused', 'xauthority']
+
+# Xen API console 'other_config' keys.
+XENAPI_CONSOLE_OTHER_CFG = ['vncunused', 'vncdisplay', 'vnclisten',
+                            'vncpasswd', 'type', 'display', 'xauthority',
+                            'keymap']
 
 # List of XendConfig configuration keys that have no direct equivalent
 # in the old world.
@@ -636,6 +641,8 @@ class XendConfig(dict):
                 except ValueError, e:
                     raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e))
 
+        if not 'security' in cfg and sxp.child_value(sxp_cfg, 'security'):
+            cfg['security'] = sxp.child_value(sxp_cfg, 'security')
         if 'security' in cfg and not cfg.get('security_label'):
             secinfo = cfg['security']
             if isinstance(secinfo, list):
@@ -1083,6 +1090,12 @@ class XendConfig(dict):
 
             self.device_duplicate_check(dev_type, dev_info, target)
 
+            if dev_type == 'vif':
+                if dev_info.get('policy') and dev_info.get('label'):
+                    dev_info['security_label'] = "%s:%s:%s" % \
+                        (xsconstants.ACM_POLICY_ID,
+                         dev_info['policy'],dev_info['label'])
+
             # create uuid if it doesn't exist
             dev_uuid = dev_info.get('uuid', None)
             if not dev_uuid:
@@ -1113,9 +1126,7 @@ class XendConfig(dict):
                 # with vfb
 
                 other_config = {}
-                for key in ['vncunused', 'vncdisplay', 'vnclisten',
-                            'vncpasswd', 'type', 'display', 'xauthority',
-                            'keymap']:
+                for key in XENAPI_CONSOLE_OTHER_CFG:
                     if key in dev_info:
                         other_config[key] = dev_info[key]
                 target['devices'][dev_uuid][1]['other_config'] =  other_config
@@ -1157,6 +1168,10 @@ class XendConfig(dict):
                     network = XendAPIStore.get(
                         cfg_xenapi.get('network'), 'network')
                     dev_info['bridge'] = network.get_name_label()
+
+                if cfg_xenapi.get('security_label'):
+                    dev_info['security_label'] = \
+                         cfg_xenapi.get('security_label')
                 
                 dev_uuid = cfg_xenapi.get('uuid', None)
                 if not dev_uuid:
@@ -1299,6 +1314,13 @@ class XendConfig(dict):
         for dev_uuid, (dev_type, dev_info) in self['devices'].items():
             if dev_uuid == console_uuid:
                 dev_info[key] = value
+                # collapse other_config into dev_info for things
+                # such as vncpasswd, vncunused, etc.
+                if key == 'other_config':
+                    for k in XENAPI_CONSOLE_OTHER_CFG:
+                        if k in dev_info and k not in value:
+                            del dev_info[k]
+                    dev_info.update(value)
                 break
 
     def console_get_all(self, protocol):
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendDevices.py
--- a/tools/python/xen/xend/XendDevices.py      Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/XendDevices.py      Fri Jul 27 08:15:16 2007 -0600
@@ -78,6 +78,7 @@ class XendDevices:
         @param domain: domain this controller is handling devices for.
         @type domain: XendDomainInfo
         """
-        tpmif.destroy_vtpmstate(domain.getName())
+        from xen.xend.XendLogging import log
+        tpmif.destroy_vtpmstate(domain.info.get('vtpm_refs'))
 
     destroy_device_state = classmethod(destroy_device_state)
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendDomain.py
--- a/tools/python/xen/xend/XendDomain.py       Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/XendDomain.py       Fri Jul 27 08:15:16 2007 -0600
@@ -51,6 +51,7 @@ from xen.xend.xenstore.xswatch import xs
 from xen.xend.xenstore.xswatch import xswatch
 from xen.util import mkdir
 from xen.xend import uuid
+from xen.xend import sxp
 
 xc = xen.lowlevel.xc.xc()
 xoptions = XendOptions.instance() 
@@ -688,6 +689,29 @@ class XendDomain:
         
         return value
 
+    def set_dev_property_by_uuid(self, klass, dev_uuid, field, value,
+                                 old_val = None):
+        rc = True
+        self.domains_lock.acquire()
+
+        try:
+            try:
+                dom = self.get_vm_with_dev_uuid(klass, dev_uuid)
+                if dom:
+                    o_val = dom.get_dev_property(klass, dev_uuid, field)
+                    log.info("o_val=%s, old_val=%s" % (o_val, old_val))
+                    if old_val and old_val != o_val:
+                        return False
+
+                    dom.set_dev_property(klass, dev_uuid, field, value)
+                    self.managed_config_save(dom)
+            except ValueError, e:
+                pass
+        finally:
+            self.domains_lock.release()
+
+        return rc
+
     def is_valid_vm(self, vm_ref):
         return (self.get_vm_by_uuid(vm_ref) != None)
 
@@ -945,6 +969,31 @@ class XendDomain:
         try:
             try:
                 domconfig = XendConfig.XendConfig(sxp_obj = config)
+                
+                domains = self.list('all')
+                domains = map(lambda dom: dom.sxpr(), domains)
+                for dom in domains:
+                    if sxp.child_value(config, 'uuid', None):
+                        if domconfig['uuid'] == sxp.child_value(dom, 'uuid'):
+                            if domconfig['name_label'] != sxp.child_value(dom, 
'name'):
+                                raise XendError("Domain UUID '%s' is already 
used." % \
+                                                domconfig['uuid'])
+                            else:
+                                # Update the config for that existing domain
+                                # because it is same name and same UUID.
+                                break
+                        else:
+                            if domconfig['name_label'] == sxp.child_value(dom, 
'name'):
+                                raise XendError("Domain name '%s' is already 
used." % \
+                                                domconfig['name_label'])
+                    else:
+                        if domconfig['name_label'] == sxp.child_value(dom, 
'name'):
+                            # Overwrite the auto-generated UUID by the UUID
+                            # of the existing domain. And update the config
+                            # for that existing domain.
+                            domconfig['uuid'] = sxp.child_value(dom, 'uuid')
+                            break
+                
                 dominfo = XendDomainInfo.createDormant(domconfig)
                 log.debug("Creating new managed domain: %s" %
                           dominfo.getName())
@@ -1164,6 +1213,10 @@ class XendDomain:
 
         if dominfo.getDomid() == DOM0_ID:
             raise XendError("Cannot dump core for privileged domain %s" % 
domid)
+        if dominfo._stateGet() not in (DOM_STATE_PAUSED, DOM_STATE_RUNNING):
+            raise VMBadState("Domain '%s' is not started" % domid,
+                             POWER_STATE_NAMES[DOM_STATE_PAUSED],
+                             POWER_STATE_NAMES[dominfo._stateGet()])
 
         try:
             log.info("Domain core dump requested for domain %s (%d) "
@@ -1537,6 +1590,10 @@ class XendDomain:
         dominfo = self.domain_lookup_nr(domid)
         if not dominfo:
             raise XendInvalidDomain(str(domid))
+        if dominfo._stateGet() not in (DOM_STATE_RUNNING, DOM_STATE_PAUSED):
+            raise VMBadState("Domain '%s' is not started" % domid,
+                             POWER_STATE_NAMES[DOM_STATE_RUNNING],
+                             POWER_STATE_NAMES[dominfo._stateGet()])
         if trigger_name.lower() in TRIGGER_TYPE: 
             trigger = TRIGGER_TYPE[trigger_name.lower()]
         else:
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendDomainInfo.py
--- a/tools/python/xen/xend/XendDomainInfo.py   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/XendDomainInfo.py   Fri Jul 27 08:15:16 2007 -0600
@@ -632,16 +632,27 @@ class XendDomainInfo:
                     ['vcpu_count', self.info['VCPUs_max']]]
 
             for i in range(0, self.info['VCPUs_max']):
-                info = xc.vcpu_getinfo(self.domid, i)
-
-                sxpr.append(['vcpu',
-                             ['number',   i],
-                             ['online',   info['online']],
-                             ['blocked',  info['blocked']],
-                             ['running',  info['running']],
-                             ['cpu_time', info['cpu_time'] / 1e9],
-                             ['cpu',      info['cpu']],
-                             ['cpumap',   info['cpumap']]])
+                if self.domid is not None:
+                    info = xc.vcpu_getinfo(self.domid, i)
+
+                    sxpr.append(['vcpu',
+                                 ['number',   i],
+                                 ['online',   info['online']],
+                                 ['blocked',  info['blocked']],
+                                 ['running',  info['running']],
+                                 ['cpu_time', info['cpu_time'] / 1e9],
+                                 ['cpu',      info['cpu']],
+                                 ['cpumap',   info['cpumap']]])
+                else:
+                    sxpr.append(['vcpu',
+                                 ['number',   i],
+                                 ['online',   0],
+                                 ['blocked',  0],
+                                 ['running',  0],
+                                 ['cpu_time', 0.0],
+                                 ['cpu',      -1],
+                                 ['cpumap',   self.info['cpus'] and \
+                                              self.info['cpus'] or range(64)]])
 
             return sxpr
 
@@ -1111,6 +1122,8 @@ class XendDomainInfo:
                     self._clearRestart()
 
                     if reason == 'suspend':
+                        if self._stateGet() != DOM_STATE_SUSPENDED:
+                            self.image.saveDeviceModel()
                         self._stateSet(DOM_STATE_SUSPENDED)
                         # Don't destroy the domain.  XendCheckpoint will do
                         # this once it has finished.  However, stop watching
@@ -1447,9 +1460,13 @@ class XendDomainInfo:
         # allocation of 1MB. We free up 2MB here to be on the safe side.
         balloon.free(2*1024) # 2MB should be plenty
 
-        ssidref = security.calc_dom_ssidref_from_info(self.info)
-        if ssidref == 0 and security.on():
-            raise VmError('VM is not properly labeled.')
+        ssidref = 0
+        if security.on():
+            ssidref = security.calc_dom_ssidref_from_info(self.info)
+            if ssidref == 0:
+                raise VmError('VM is not properly labeled.')
+            if security.has_authorization(ssidref) == False:
+                raise VmError("VM is not authorized to run.")
 
         try:
             self.domid = xc.domain_create(
@@ -1594,6 +1611,7 @@ class XendDomainInfo:
                 log.exception("Removing domain path failed.")
 
             self._stateSet(DOM_STATE_HALTED)
+            self.domid = None  # Do not push into _stateSet()!
         finally:
             self.refresh_shutdown_lock.release()
 
@@ -1752,6 +1770,9 @@ class XendDomainInfo:
             ResumeDomain(self.domid)
         except:
             log.exception("XendDomainInfo.resume: xc.domain_resume failed on 
domain %s." % (str(self.domid)))
+        if self.is_hvm():
+            self.image.resumeDeviceModel()
+
 
     #
     # Channels for xenstore and console
@@ -2419,6 +2440,8 @@ class XendDomainInfo:
                 config['io_read_kbs'] = 0.0
                 config['io_write_kbs'] = 0.0                
 
+            config['security_label'] = config.get('security_label', '')
+
         if dev_class == 'vbd':
 
             if self._stateGet() not in (XEN_API_VM_POWER_STATE_HALTED,):
@@ -2610,6 +2633,9 @@ class XendDomainInfo:
 
         return dev_uuid
 
+    def set_console_other_config(self, console_uuid, other_config):
+        self.info.console_update(console_uuid, 'other_config', other_config)
+
     def destroy_device_by_uuid(self, dev_type, dev_uuid):
         if dev_uuid not in self.info['devices']:
             raise XendError('Device does not exist')
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendPIF.py
--- a/tools/python/xen/xend/XendPIF.py  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/XendPIF.py  Fri Jul 27 08:15:16 2007 -0600
@@ -24,6 +24,7 @@ from xen.xend.XendBase import XendBase
 from xen.xend.XendBase import XendBase
 from xen.xend.XendPIFMetrics import XendPIFMetrics
 from xen.xend.XendError import *
+from xen.xend import Vifctl
 
 log = logging.getLogger("xend.XendPIF")
 log.setLevel(logging.TRACE)
@@ -31,14 +32,17 @@ MAC_RE = re.compile(':'.join(['[0-9a-f]{
 MAC_RE = re.compile(':'.join(['[0-9a-f]{2}'] * 6))
 IP_IFACE_RE = re.compile(r'^\d+: (\w+):.*mtu (\d+) .* link/\w+ ([0-9a-f:]+)')
 
+
+Vifctl.network('start')
+
 def linux_phy_to_virt(pif_name):
     return 'eth' + re.sub(r'^[a-z]+', '', pif_name)
 
 def linux_get_phy_ifaces():
     """Returns a list of physical interfaces.
 
-    Identifies PIFs as those that have a interface name starting with 'p'
-    and have the fake 'fe:ff:ff:ff:ff:ff' MAC address.
+    Identifies PIFs as those that have a interface name starting with
+    'peth'.
 
     See /etc/xen/scripts/network-bridge for how the devices are renamed.
 
@@ -58,7 +62,7 @@ def linux_get_phy_ifaces():
                 
         # resolve pifs' mac addresses
         for name, mtu, mac in ifaces.values():
-            if name[0] == 'p' and mac == 'fe:ff:ff:ff:ff:ff':
+            if name.startswith('peth'):
                 bridged_ifname = linux_phy_to_virt(name)
                 bridged_if = ifaces.get(bridged_ifname)
                 if bridged_if:
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendVDI.py
--- a/tools/python/xen/xend/XendVDI.py  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/XendVDI.py  Fri Jul 27 08:15:16 2007 -0600
@@ -24,6 +24,7 @@ from xen.util.xmlrpclib2 import stringif
 from xen.util.xmlrpclib2 import stringify
 from xmlrpclib import dumps, loads
 from xen.util import security, xsconstants
+from xen.xend.XendError import SecurityError
 
 KB = 1024
 MB = 1024 * 1024
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/XendXSPolicyAdmin.py
--- a/tools/python/xen/xend/XendXSPolicyAdmin.py        Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/python/xen/xend/XendXSPolicyAdmin.py        Fri Jul 27 08:15:16 
2007 -0600
@@ -56,7 +56,10 @@ class XSPolicyAdmin:
             typ = data[1]
             try:
                 if typ == xsconstants.ACM_POLICY_ID:
-                    self.xsobjs[ref] = ACMPolicy(name=name, ref=ref)
+                    try:
+                        self.xsobjs[ref] = ACMPolicy(name=name, ref=ref)
+                    except Exception, e:
+                        del self.policies[ref]
                 else:
                     del self.policies[ref]
             except Exception, e:
@@ -271,6 +274,10 @@ class XSPolicyAdmin:
                 return pol
         return None
 
+    def get_hv_loaded_policy_name(self):
+        security.refresh_security_policy()
+        return security.active_policy
+
     def get_policy_by_name(self, name):
         for pol in self.xsobjs.values():
             if pol.get_name() == name:
@@ -305,6 +312,18 @@ class XSPolicyAdmin:
             vmlabel = pol.policy_get_domain_label_by_ssidref_formatted(ssidref)
         return vmlabel
 
+    def get_stes_of_vmlabel(self, vmlabel_xapi):
+        """ Get the list of STEs given a VM label in XenAPI format """
+        stes = []
+        loadedpol = self.get_loaded_policy()
+        if loadedpol:
+            tmp = vmlabel_xapi.split(":")
+            if len(tmp) != 3:
+                return []
+            stes = loadedpol.policy_get_stes_of_vmlabel(tmp[2])
+        return stes
+
+
 poladmin = None
 
 def XSPolicyAdminInstance(maxpolicies=1):
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/balloon.py
--- a/tools/python/xen/xend/balloon.py  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/balloon.py  Fri Jul 27 08:15:16 2007 -0600
@@ -94,7 +94,9 @@ def free(need_mem):
     # track the last used value so that we don't trigger too many watches.
 
     xoptions = XendOptions.instance()
+    dom0 = XendDomain.instance().privilegedDomain()
     xc = xen.lowlevel.xc.xc()
+    dom0_start_alloc_mb = get_dom0_current_alloc() / 1024
 
     try:
         dom0_min_mem = xoptions.get_dom0_min_mem() * 1024
@@ -133,7 +135,6 @@ def free(need_mem):
                         new_alloc_mb = new_alloc / 1024  # Round down
                         log.debug("Balloon: setting dom0 target to %d MiB.",
                                   new_alloc_mb)
-                        dom0 = XendDomain.instance().privilegedDomain()
                         dom0.setMemoryTarget(new_alloc_mb)
                         last_new_alloc = new_alloc
                 # Continue to retry, waiting for ballooning or scrubbing.
@@ -158,7 +159,10 @@ def free(need_mem):
                 (need_mem, dom0_min_mem, dom0_min_mem,
                  free_mem + scrub_mem + dom0_alloc - dom0_min_mem))
         else:
-            raise VmError('The privileged domain did not balloon!')
+            dom0.setMemoryTarget(dom0_start_alloc_mb)
+            raise VmError(
+                ('Not enough memory is available, and dom0 cannot'
+                 ' be shrunk any further'))
 
     finally:
         del xc
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/image.py
--- a/tools/python/xen/xend/image.py    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/image.py    Fri Jul 27 08:15:16 2007 -0600
@@ -20,6 +20,7 @@ import os, string
 import os, string
 import re
 import math
+import time
 import signal
 
 import xen.lowlevel.xc
@@ -27,6 +28,7 @@ from xen.xend.XendError import VmError, 
 from xen.xend.XendError import VmError, XendError, HVMRequired
 from xen.xend.XendLogging import log
 from xen.xend.XendOptions import instance as xenopts
+from xen.xend.xenstore.xstransact import xstransact
 from xen.xend.xenstore.xswatch import xswatch
 from xen.xend import arch
 
@@ -175,6 +177,14 @@ class ImageHandler:
         """Create device model for the domain (define in subclass if 
needed)."""
         pass
     
+    def saveDeviceModel(self):
+        """Save device model for the domain (define in subclass if needed)."""
+        pass
+
+    def resumeDeviceModel(self):
+        """Unpause device model for the domain (define in subclass if 
needed)."""
+        pass
+
     def destroy(self):
         """Extra cleanup on domain destroy (define in subclass if needed)."""
         pass
@@ -443,17 +453,34 @@ class HVMImageHandler(ImageHandler):
         self.vm.storeDom("image/device-model-pid", self.pid)
         log.info("device model pid: %d", self.pid)
 
+    def saveDeviceModel(self):
+        # Signal the device model to pause itself and save its state
+        xstransact.Store("/local/domain/0/device-model/%i"
+                         % self.vm.getDomid(), ('command', 'save'))
+        # Wait for confirmation.  Could do this with a watch but we'd
+        # still end up spinning here waiting for the watch to fire. 
+        state = ''
+        count = 0
+        while state != 'paused':
+            state = xstransact.Read("/local/domain/0/device-model/%i/state"
+                                    % self.vm.getDomid())
+            time.sleep(0.1)
+            count += 1
+            if count > 100:
+                raise VmError('Timed out waiting for device model to save')
+
+    def resumeDeviceModel(self):
+        # Signal the device model to resume activity after pausing to save.
+        xstransact.Store("/local/domain/0/device-model/%i"
+                         % self.vm.getDomid(), ('command', 'continue'))
+
     def recreate(self):
         self.pid = self.vm.gatherDom(('image/device-model-pid', int))
 
     def destroy(self, suspend = False):
-        if self.pid:
+        if self.pid and not suspend:
             try:
-                sig = signal.SIGKILL
-                if suspend:
-                    log.info("use sigusr1 to signal qemu %d", self.pid)
-                    sig = signal.SIGUSR1
-                os.kill(self.pid, sig)
+                os.kill(self.pid, signal.SIGKILL)
             except OSError, exn:
                 log.exception(exn)
             try:
@@ -464,6 +491,8 @@ class HVMImageHandler(ImageHandler):
                 # but we can't wait for it because it's not our child.
                 pass
             self.pid = None
+            state = xstransact.Remove("/local/domain/0/device-model/%i"
+                                      % self.vm.getDomid())
 
 
 class IA64_HVM_ImageHandler(HVMImageHandler):
@@ -506,6 +535,7 @@ class X86_HVM_ImageHandler(HVMImageHandl
         # were given (but the Xen minimum is for safety, not performance).
         return max(4 * (256 * self.vm.getVCpuCount() + 2 * (maxmem_kb / 1024)),
                    shadow_mem_kb)
+
 
 class X86_Linux_ImageHandler(LinuxImageHandler):
 
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/server/SrvServer.py
--- a/tools/python/xen/xend/server/SrvServer.py Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/server/SrvServer.py Fri Jul 27 08:15:16 2007 -0600
@@ -49,7 +49,6 @@ from xen.web.httpserver import HttpServe
 from xen.web.httpserver import HttpServer, UnixHttpServer
 
 from xen.xend import XendNode, XendOptions, XendAPI
-from xen.xend import Vifctl
 from xen.xend.XendLogging import log
 from xen.xend.XendClient import XEN_API_SOCKET
 from xen.xend.XendDomain import instance as xenddomain
@@ -101,8 +100,6 @@ class XendServers:
         if status:
             fcntl.fcntl(status, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
         
-        Vifctl.network('start')
-
         # Prepare to catch SIGTERM (received when 'xend stop' is executed)
         # and call each server's cleanup if possible
         signal.signal(signal.SIGTERM, self.cleanup)
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/server/netif.py
--- a/tools/python/xen/xend/server/netif.py     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/server/netif.py     Fri Jul 27 08:15:16 2007 -0600
@@ -26,6 +26,11 @@ import re
 
 from xen.xend import XendOptions
 from xen.xend.server.DevController import DevController
+from xen.xend.XendError import VmError
+from xen.util import security
+from xen.xend.XendXSPolicyAdmin import XSPolicyAdminInstance
+
+from xen.xend.XendLogging import log
 
 xoptions = XendOptions.instance()
 
@@ -108,6 +113,7 @@ class NetifController(DevController):
         ipaddr  = config.get('ip')
         model   = config.get('model')
         accel   = config.get('accel')
+        sec_lab = config.get('security_label')
 
         if not typ:
             typ = xoptions.netback_type
@@ -134,6 +140,8 @@ class NetifController(DevController):
             back['model'] = model
         if accel:
             back['accel'] = accel
+        if sec_lab:
+            back['security_label'] = sec_lab
 
         config_path = "device/%s/%d/" % (self.deviceClass, devid)
         for x in back:
@@ -149,7 +157,32 @@ class NetifController(DevController):
             front = { 'handle' : "%i" % devid,
                       'mac'    : mac }
 
+        if security.on():
+            self.do_access_control(config)
+
         return (devid, back, front)
+
+
+    def do_access_control(self, config):
+        """ do access control checking. Throws a VMError if access is denied 
"""
+        domain_label = self.vm.get_security_label()
+        stes = XSPolicyAdminInstance().get_stes_of_vmlabel(domain_label)
+        res_label = config.get('security_label')
+        if len(stes) > 1 or res_label:
+            if not res_label:
+                raise VmError("'VIF' must be labeled")
+            (label, ssidref, policy) = \
+                              security.security_label_to_details(res_label)
+            if domain_label:
+                rc = security.res_security_check_xapi(label, ssidref,
+                                                      policy,
+                                                      domain_label)
+                if rc == 0:
+                    raise VmError("VM's access to network device denied. "
+                                  "Check labeling")
+            else:
+                raise VmError("VM must have a security label to access "
+                              "network device")
 
 
     def getDeviceConfiguration(self, devid):
@@ -160,10 +193,12 @@ class NetifController(DevController):
         config_path = "device/%s/%d/" % (self.deviceClass, devid)
         devinfo = ()
         for x in ( 'script', 'ip', 'bridge', 'mac',
-                   'type', 'vifname', 'rate', 'uuid', 'model', 'accel'):
+                   'type', 'vifname', 'rate', 'uuid', 'model', 'accel',
+                   'security_label'):
             y = self.vm._readVm(config_path + x)
             devinfo += (y,)
-        (script, ip, bridge, mac, typ, vifname, rate, uuid, model, accel) = 
devinfo
+        (script, ip, bridge, mac, typ, vifname, rate, uuid,
+         model, accel, security_label) = devinfo
 
         if script:
             result['script'] = script
@@ -185,5 +220,7 @@ class NetifController(DevController):
             result['model'] = model
         if accel:
             result['accel'] = accel
-            
+        if security_label:
+            result['security_label'] = security_label
+
         return result
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xend/server/tpmif.py
--- a/tools/python/xen/xend/server/tpmif.py     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xend/server/tpmif.py     Fri Jul 27 08:15:16 2007 -0600
@@ -31,9 +31,10 @@ import re
 
 xoptions = XendOptions.instance()
 
-def destroy_vtpmstate(name):
+def destroy_vtpmstate(uuids):
     if os.path.exists(VTPM_DELETE_SCRIPT):
-        os.system(VTPM_DELETE_SCRIPT + " " + name)
+        for uuid in uuids:
+            os.system(VTPM_DELETE_SCRIPT + " " + uuid)
 
 class TPMifController(DevController):
     """TPM interface controller. Handles all TPM devices for a domain.
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/activatepolicy.py
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/python/xen/xm/activatepolicy.py     Fri Jul 27 08:15:16 2007 -0600
@@ -0,0 +1,86 @@
+#============================================================================
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of version 2.1 of the GNU Lesser General Public
+# License as published by the Free Software Foundation.
+#
+# 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#============================================================================
+# Copyright (C) 2007 International Business Machines Corp.
+# Author: Stefan Berger <stefanb@xxxxxxxxxx>
+#============================================================================
+
+"""Activate the managed policy of the system.
+"""
+
+import sys
+from xen.util import xsconstants
+from xml.dom import minidom
+from xen.xm.opts import OptionError
+from xen.xm import getpolicy
+from xen.xm import main as xm_main
+from xen.xm.main import server
+
+def help():
+    return """
+    Usage: xm activatepolicy [options]
+
+    Activate the xend-managed policy.
+
+    The following options are defined:
+      --load     Load the policy into the hypervisor.
+      --boot     Have the system boot with the policy. Changes the default
+                 title in grub.conf.
+      --noboot   Remove the policy from the default entry in grub.conf.
+    """
+
+def activate_policy(flags):
+    policystate = server.xenapi.XSPolicy.get_xspolicy()
+    xs_ref = policystate['xs_ref']
+    if int(policystate['type']) == 0 or xs_ref == "":
+        print "No policy is installed."
+        return
+    rc = int(server.xenapi.XSPolicy.activate_xspolicy(xs_ref, flags))
+    if rc == flags:
+        print "Successfully activated the policy."
+    else:
+        print "An error occurred trying to activate the policy: %s" % \
+              xsconstants.xserr2string(rc)
+
+def remove_bootpolicy():
+    server.xenapi.XSPolicy.rm_xsbootpolicy()
+
+def main(argv):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('xm needs to be configured to use the xen-api.')
+    flags = 0
+    c = 1
+
+    while c < len(argv):
+        if '--boot' == argv[c]:
+            flags |= xsconstants.XS_INST_BOOT
+        elif '--load' == argv[c]:
+            flags |= xsconstants.XS_INST_LOAD
+        elif '--noboot' == argv[c]:
+            remove_bootpolicy()
+        else:
+            raise OptionError("Unknown command line option '%s'" % argv[c])
+        c += 1
+
+    if flags != 0:
+        activate_policy(flags)
+
+    getpolicy.getpolicy(False)
+
+if __name__ == '__main__':
+    try:
+        main(sys.argv)
+    except Exception, e:
+        sys.stderr.write('Error: %s\n' % str(e))
+        sys.exit(-1)
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/addlabel.py
--- a/tools/python/xen/xm/addlabel.py   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/addlabel.py   Fri Jul 27 08:15:16 2007 -0600
@@ -25,17 +25,30 @@ from xen.util import dictio
 from xen.util import dictio
 from xen.util import security
 from xen.xm.opts import OptionError
+from xen.util import xsconstants
+from xen.xm import main as xm_main
+from xen.xm.main import server
 
 def help():
     return """
     Format: xm addlabel <label> dom <configfile> [<policy>]
-            xm addlabel <label> res <resource> [<policy>]
+            xm addlabel <label> mgt <domain name> [<policy type>:<policy>]
+            xm addlabel <label> res <resource> [[<policy type>:]<policy>]
+            xm addlabel <label> vif-<idx> <domain name> [<policy 
type>:<policy>]
     
     This program adds an acm_label entry into the 'configfile'
-    for a domain or to the global resource label file for a
-    resource. It derives the policy from the running hypervisor
+    for a domain or allows to label a xend-managed domain.
+    The global resource label file for is extended with labels for
+    resources. It derives the policy from the running hypervisor
     if it is not given (optional parameter). If a label already
-    exists for the given domain or resource, then addlabel fails."""
+    exists for the given domain or resource, then addlabel fails.
+
+    For xend-managed domains, the 'mgt' parameter should be used and
+    the 'xm' tool must have been configured to use the xen-api for
+    communication with xen. If a policy is provided as last parameter,
+    its type must also be given. Currently only one type of policy is
+    supported and identified as 'ACM'. An example for a valid string
+    is 'ACM:xm-test'. """
 
 
 def validate_config_file(configfile):
@@ -66,32 +79,47 @@ def validate_config_file(configfile):
         return 1
 
 
-def add_resource_label(label, resource, policyref):
+def add_resource_label(label, resource, policyref, policy_type):
     """Adds a resource label to the global resource label file.
     """
-    # sanity check: make sure this label can be instantiated later on
-    ssidref = security.label2ssidref(label, policyref, 'res')
-
-    #build canonical resource name
-    resource = security.unify_resname(resource)
-
-    # see if this resource is already in the file
-    access_control = {}
-    file = security.res_label_filename
-    try:
-        access_control = dictio.dict_read("resources", file)
-    except:
-        print "Resource file not found, creating new file at:"
-        print "%s" % (file)
-
-    if access_control.has_key(resource):
-        security.err("This resource is already labeled.")
-
-    # write the data to file
-    new_entry = { resource : tuple([policyref, label]) }
-    access_control.update(new_entry)
-    dictio.dict_write(access_control, "resources", file)
-
+
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+
+        # sanity check: make sure this label can be instantiated later on
+        ssidref = security.label2ssidref(label, policyref, 'res')
+
+        #build canonical resource name
+        resource = security.unify_resname(resource,mustexist=False)
+
+        # see if this resource is already in the file
+        access_control = {}
+        fil = security.res_label_filename
+        try:
+            access_control = dictio.dict_read("resources", fil)
+        except:
+            print "Resource file not found, creating new file at:"
+            print "%s" % (fil)
+
+        if access_control.has_key(resource):
+            security.err("This resource is already labeled.")
+
+        # write the data to file
+        new_entry = { resource : tuple([policy_type, policyref, label]) }
+        access_control.update(new_entry)
+        dictio.dict_write(access_control, "resources", fil)
+    else:
+        res = [ policy_type, policyref, label ]
+        res_xapi = security.format_resource_label(res)
+        old = server.xenapi.XSPolicy.get_resource_label(resource)
+        if old == "":
+            try:
+                server.xenapi.XSPolicy.set_resource_label(resource,
+                                                          res_xapi,
+                                                          "")
+            except Exception, e:
+                security.err("Could not label this resource: %s" % e)
+        else:
+            security.err("'%s' is already labeled with '%s'" % (resource,old))
 
 def add_domain_label(label, configfile, policyref):
     # sanity checks: make sure this label can be instantiated later on
@@ -109,9 +137,61 @@ def add_domain_label(label, configfile, 
     config_fd.write(new_label)
     config_fd.close()
 
+def add_domain_label_xapi(label, domainname, policyref, policy_type):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('Xm must be configured to use the xen-api.')
+    uuids = server.xenapi.VM.get_by_name_label(domainname)
+    if len(uuids) == 0:
+        raise OptionError('A VM with that name does not exist.')
+    if len(uuids) != 1:
+        raise OptionError('There are multiple domains with the same name.')
+    uuid = uuids[0]
+    sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
+    try:
+        old_lab = server.xenapi.VM.get_security_label(uuid)
+        rc = server.xenapi.VM.set_security_label(uuid, sec_lab, old_lab)
+    except:
+        rc = -1
+    if int(rc) < 0:
+        raise OptionError('Could not label domain.')
+    else:
+        ssidref = int(rc)
+        if ssidref != 0:
+            print "Set the label of domain '%s' to '%s'. New ssidref = %08x" % 
\
+                  (domainname,label,ssidref)
+        else:
+            print "Set the label of dormant domain '%s' to '%s'." % \
+                  (domainname,label)
+
+def add_vif_label(label, vmname, idx, policyref, policy_type):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('Need to be configure for using xen-api.')
+    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
+    if len(vm_refs) == 0:
+        raise OptionError('A VM with the name %s does not exist.' %
+                          vmname)
+    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
+    if len(vif_refs) <= idx:
+        raise OptionError("Bad VIF index.")
+    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
+    if not vif_ref:
+        print "Internal error: VIF does not exist."
+    sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
+    try:
+        old_lab = server.xenapi.VIF.get_security_label(vif_ref)
+        rc = server.xenapi.VIF.set_security_label(vif_ref,
+                                                  sec_lab, old_lab)
+        if int(rc) != 0:
+            print "Could not label the VIF."
+        else:
+            print "Successfully labeled the VIF."
+    except Exception, e:
+        print "Could not label the VIF: %s" % str(e)
+
 
 def main(argv):
     policyref = None
+    policy_type = ""
     if len(argv) not in (4, 5):
         raise OptionError('Needs either 2 or 3 arguments')
     
@@ -121,6 +201,7 @@ def main(argv):
         policyref = argv[4]
     elif security.on():
         policyref = security.active_policy
+        policy_type = xsconstants.ACM_POLICY_ID
     else:
         raise OptionError("No active policy. Must specify policy on the "
                           "command line.")
@@ -136,11 +217,41 @@ def main(argv):
             raise OptionError('Invalid config file')
         else:
             add_domain_label(label, configfile, policyref)
+    elif argv[2].lower() == "mgt":
+        domain = argv[3]
+        if policy_type == "":
+            tmp = policyref.split(":")
+            if len(tmp) != 2:
+                raise OptionError("Policy name in wrong format.")
+            policy_type, policyref = tmp
+        add_domain_label_xapi(label, domain, policyref, policy_type)
     elif argv[2].lower() == "res":
         resource = argv[3]
-        add_resource_label(label, resource, policyref)
-    else:
-        raise OptionError('Need to specify either "dom" or "res" as '
+        if policy_type == "":
+            tmp = policyref.split(":")
+            if len(tmp) == 1:
+                policy_type = xsconstants.ACM_POLICY_ID
+            elif len(tmp) == 2:
+                policy_type, policyref = tmp
+            else:
+                raise OptionError("Policy name in wrong format.")
+        add_resource_label(label, resource, policyref, policy_type)
+    elif argv[2].lower().startswith("vif-"):
+        try:
+            idx = int(argv[2][4:])
+            if idx < 0:
+                raise
+        except:
+            raise OptionError("Bad VIF device index.")
+        vmname = argv[3]
+        if policy_type == "":
+            tmp = policyref.split(":")
+            if len(tmp) != 2:
+                raise OptionError("Policy name in wrong format.")
+            policy_type, policyref = tmp
+        add_vif_label(label, vmname, idx, policyref, policy_type)
+    else:
+        raise OptionError('Need to specify either "dom", "mgt" or "res" as '
                           'object to add label to.')
             
 if __name__ == '__main__':
@@ -149,6 +260,3 @@ if __name__ == '__main__':
     except Exception, e:
         sys.stderr.write('Error: %s\n' % str(e))
         sys.exit(-1)
-    
-
-
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/cfgbootpolicy.py
--- a/tools/python/xen/xm/cfgbootpolicy.py      Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/cfgbootpolicy.py      Fri Jul 27 08:15:16 2007 -0600
@@ -31,7 +31,11 @@ from xen.util.security import boot_filen
 from xen.util.security import boot_filename, altboot_filename
 from xen.util.security import any_title_re, xen_kernel_re, any_module_re
 from xen.util.security import empty_line_re, binary_name_re, policy_name_re
+from xen.util import xsconstants
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.xm.main import server
+from xen.util.acmpolicy import ACMPolicy
 
 def help():
     return """
@@ -144,6 +148,40 @@ def insert_policy(boot_file, alt_boot_fi
         pass
     return extended_titles[0]
 
+def cfgbootpolicy_xapi(policy, user_title=None):
+    xstype = int(server.xenapi.XSPolicy.get_xstype())
+    if xstype & xsconstants.XS_POLICY_ACM == 0:
+        raise OptionError("ACM policy not supported on system.")
+    if user_title:
+        raise OptionError("Only the default title is supported with Xen-API.")
+
+    policystate = server.xenapi.XSPolicy.get_xspolicy()
+    if int(policystate['type']) == 0:
+        print "No policy is installed."
+        return
+
+    if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
+        print "Unknown policy type '%s'." % policystate['type']
+        return
+    else:
+        xml = policystate['repr']
+        xs_ref = policystate['xs_ref']
+        if not xml:
+            OptionError("No policy installed on system?")
+        acmpol = ACMPolicy(xml=xml)
+        if acmpol.get_name() != policy:
+            raise OptionError("Policy installed on system '%s' does not "
+                              "match the requested policy '%s'" %
+                              (acmpol.get_name(), policy))
+        flags = int(policystate['flags']) | xsconstants.XS_INST_BOOT
+        rc = int(server.xenapi.XSPolicy.activate_xspolicy(xs_ref, flags))
+        if rc == flags:
+            print "Successfully enabled the policy for having the system" \
+                  " booted with."
+        else:
+            print "An error occurred during the operation: %s" % \
+                  xsconstants.xserr2string(rc)
+
 
 def main(argv):
     user_kver = None
@@ -159,24 +197,27 @@ def main(argv):
     if not policy_name_re.match(policy):
         raise OptionError("Illegal policy name: '%s'" % policy)
 
-    policy_file = '/'.join([policy_dir_prefix] + policy.split('.'))
-    src_binary_policy_file = policy_file + ".bin"
-    #check if .bin exists or if policy file exists
-    if not os.path.isfile(src_binary_policy_file):
-        if not os.path.isfile(policy_file + "-security_policy.xml"):
-            raise OptionError("Unknown policy '%s'" % policy)
-        else:
-            err_msg = "Cannot find binary file for policy '%s'." % policy
-            err_msg += " Please use makepolicy to create binary file."
-            raise OptionError(err_msg)
-    
-    dst_binary_policy_file = "/boot/" + policy + ".bin"
-    shutil.copyfile(src_binary_policy_file, dst_binary_policy_file)
-    
-    entryname = insert_policy(boot_filename, altboot_filename,
-                              user_title, policy)
-    print "Boot entry '%s' extended and \'%s\' copied to /boot" \
-          % (entryname, policy + ".bin")
+    if xm_main.serverType == xm_main.SERVER_XEN_API:
+        cfgbootpolicy_xapi(policy)
+    else:
+        policy_file = '/'.join([policy_dir_prefix] + policy.split('.'))
+        src_binary_policy_file = policy_file + ".bin"
+        #check if .bin exists or if policy file exists
+        if not os.path.isfile(src_binary_policy_file):
+            if not os.path.isfile(policy_file + "-security_policy.xml"):
+                raise OptionError("Unknown policy '%s'" % policy)
+            else:
+                err_msg = "Cannot find binary file for policy '%s'." % policy
+                err_msg += " Please use makepolicy to create binary file."
+                raise OptionError(err_msg)
+    
+        dst_binary_policy_file = "/boot/" + policy + ".bin"
+        shutil.copyfile(src_binary_policy_file, dst_binary_policy_file)
+    
+        entryname = insert_policy(boot_filename, altboot_filename,
+                                  user_title, policy)
+        print "Boot entry '%s' extended and \'%s\' copied to /boot" \
+              % (entryname, policy + ".bin")
 
 if __name__ == '__main__':
     try:
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/create.dtd
--- a/tools/python/xen/xm/create.dtd    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/create.dtd    Fri Jul 27 08:15:16 2007 -0600
@@ -38,6 +38,7 @@
                  memory,
                  vbd*,
                  vif*,
+                 vtpm*,
                  console*,
                  platform*,
                  vcpu_param*,
@@ -49,7 +50,8 @@
                  actions_after_shutdown %NORMAL_EXIT; #REQUIRED 
                  actions_after_reboot   %NORMAL_EXIT; #REQUIRED
                  actions_after_crash    %CRASH_BEHAVIOUR; #REQUIRED
-                 PCI_bus                CDATA #REQUIRED> 
+                 PCI_bus                CDATA #REQUIRED
+                 security_label         CDATA #IMPLIED>
 
 <!ELEMENT memory EMPTY> 
 <!ATTLIST memory static_min      CDATA #REQUIRED
@@ -72,7 +74,11 @@
                  mtu             CDATA       #REQUIRED
                  device          CDATA       #REQUIRED
                  qos_algorithm_type CDATA    #REQUIRED
-                 network         CDATA       #IMPLIED> 
+                 network         CDATA       #IMPLIED
+                 security_label  CDATA       #IMPLIED>
+
+<!ELEMENT vtpm   (name*)>
+<!ATTLIST vtpm   backend         CDATA #REQUIRED>
 
 <!ELEMENT console (other_config*)>
 <!ATTLIST console protocol       (vt100|rfb|rdp) #REQUIRED>
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/create.py
--- a/tools/python/xen/xm/create.py     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/create.py     Fri Jul 27 08:15:16 2007 -0600
@@ -643,22 +643,12 @@ def configure_security(config, vals):
                                  ['policy', policy],
                                  ['label', label] ]
 
-        #ssidref cannot be specified together with access_control
-        if sxp.child_value(config, 'ssidref'):
-            err("ERROR: SSIDREF and access_control are mutually exclusive but 
both specified!")
-        #else calculate ssidre from label
+        #calculate ssidref from label
         ssidref = security.label2ssidref(label, policy, 'dom')
         if not ssidref :
             err("ERROR calculating ssidref from access_control.")
         security_label = ['security', [ config_access_control, ['ssidref' , 
ssidref ] ] ]
         config.append(security_label)
-    elif num == 0:
-        if hasattr(vals, 'ssidref'):
-            if not security.on():
-                err("ERROR: Security ssidref specified but no policy active.")
-            ssidref = getattr(vals, 'ssidref')
-            security_label = ['security', [ [ 'ssidref' , int(ssidref) ] ] ]
-            config.append(security_label)
     elif num > 1:
         err("VM config error: Multiple access_control definitions!")
 
@@ -714,7 +704,8 @@ def configure_vifs(config_devs, vals):
 
         def f(k):
             if k not in ['backend', 'bridge', 'ip', 'mac', 'script', 'type',
-                         'vifname', 'rate', 'model', 'accel']:
+                         'vifname', 'rate', 'model', 'accel',
+                         'policy', 'label']:
                 err('Invalid vif option: ' + k)
 
             config_vif.append([k, d[k]])
@@ -1231,13 +1222,13 @@ def config_security_check(config, verbos
 
         except security.ACMError:
             print "   %s: DENIED" % (resource)
-            (res_label, res_policy) = security.get_res_label(resource)
+            (poltype, res_label, res_policy) = security.get_res_label(resource)
             if not res_label:
                 res_label = ""
-            print "   --> res: %s (%s)" % (str(res_label),
-                                           str(res_policy))
-            print "   --> dom: %s (%s)" % (str(domain_label),
-                                           str(domain_policy))
+            print "   --> res: %s (%s:%s)" % (str(res_label),
+                                           str(poltype), str(res_policy))
+            print "   --> dom: %s (%s:%s)" % (str(domain_label),
+                                           str(poltype), str(domain_policy))
 
             answer = 0
 
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/getlabel.py
--- a/tools/python/xen/xm/getlabel.py   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/getlabel.py   Fri Jul 27 08:15:16 2007 -0600
@@ -21,14 +21,20 @@ import sys, os, re
 import sys, os, re
 from xen.util import dictio
 from xen.util import security
+from xen.util import xsconstants
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.xm.main import server
 
 def help():
     return """
     Usage: xm getlabel dom <configfile>
+           xm getlabel mgt <domain name>
            xm getlabel res <resource>
+           xm getlabel vif-<idx> <vmname>
            
-    This program shows the label for a domain or resource."""
+    This program shows the label for a domain, resource or virtual network
+    interface of a Xend-managed domain."""
 
 def get_resource_label(resource):
     """Gets the resource label
@@ -37,17 +43,24 @@ def get_resource_label(resource):
     resource = security.unify_resname(resource)
 
     # read in the resource file
-    file = security.res_label_filename
+    fil = security.res_label_filename
     try:
-        access_control = dictio.dict_read("resources", file)
+        access_control = dictio.dict_read("resources", fil)
     except:
         raise OptionError("Resource label file not found")
 
     # get the entry and print label
     if access_control.has_key(resource):
-        policy = access_control[resource][0]
-        label = access_control[resource][1]
-        print "policy="+policy+",label="+label
+        tmp = access_control[resource]
+        if len(tmp) == 2:
+            policy, label = tmp
+            policytype = xsconstants.ACM_POLICY_ID
+        elif len(tmp) == 3:
+            policytype, policy, label = tmp
+        else:
+            raise security.ACMError("Resource not properly labeled. "
+                                    "Please relabel the resource.")
+        print policytype+":"+policy+":"+label
     else:
         raise security.ACMError("Resource not labeled")
 
@@ -89,8 +102,35 @@ def get_domain_label(configfile):
     data = data.strip()
     data = data.lstrip("[\'")
     data = data.rstrip("\']")
-    print data
+    print "policytype=%s," % xsconstants.ACM_POLICY_ID + data
 
+def get_vif_label(vmname, idx):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('xm needs to be configure to use the xen-api.')
+    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
+    if len(vm_refs) == 0:
+        raise OptionError('A VM with the name %s does not exist.' %
+                          vmname)
+    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
+    if len(vif_refs) <= idx:
+        raise OptionError("Bad VIF index.")
+    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
+    if not vif_ref:
+        print "No VIF with this UUID."
+    sec_lab = server.xenapi.VIF.get_security_label(vif_ref)
+    print "%s" % sec_lab
+
+def get_domain_label_xapi(domainname):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('xm needs to be configure to use the xen-api.')
+    uuids = server.xenapi.VM.get_by_name_label(domainname)
+    if len(uuids) == 0:
+        raise OptionError('A VM with that name does not exist.')
+    if len(uuids) != 1:
+        raise OptionError('There are multiple domains with the same name.')
+    uuid = uuids[0]
+    sec_lab = server.xenapi.VM.get_security_label(uuid)
+    print "%s" %sec_lab
 
 def main(argv):
     if len(argv) != 3:
@@ -99,11 +139,24 @@ def main(argv):
     if argv[1].lower() == "dom":
         configfile = argv[2]
         get_domain_label(configfile)
+    elif argv[1].lower() == "mgt":
+        domainname = argv[2]
+        get_domain_label_xapi(domainname)
     elif argv[1].lower() == "res":
         resource = argv[2]
         get_resource_label(resource)
+    elif argv[1].lower().startswith("vif-"):
+        try:
+            idx = int(argv[1][4:])
+            if idx < 0:
+                raise
+        except:
+            raise OptionError("Bad VIF device index.")
+        vmname = argv[2]
+        get_vif_label(vmname, idx)
     else:
-        raise OptionError('First subcommand argument must be "dom" or "res"')
+        raise OptionError('First subcommand argument must be "dom"'
+                          ', "mgt" or "res"')
 
 if __name__ == '__main__':
     try:
@@ -111,6 +164,4 @@ if __name__ == '__main__':
     except Exception, e:
         sys.stderr.write('Error: %s\n' % str(e))
         sys.exit(-1)
-        
 
-
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/getpolicy.py
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/python/xen/xm/getpolicy.py  Fri Jul 27 08:15:16 2007 -0600
@@ -0,0 +1,94 @@
+#============================================================================
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of version 2.1 of the GNU Lesser General Public
+# License as published by the Free Software Foundation.
+#
+# 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#============================================================================
+# Copyright (C) 2007 International Business Machines Corp.
+# Author: Stefan Berger <stefanb@xxxxxxxxxx>
+#============================================================================
+
+"""Get the managed policy of the system.
+"""
+
+import sys
+from xen.util import xsconstants
+from xml.dom import minidom
+from xen.xm.opts import OptionError
+from xen.util.acmpolicy import ACMPolicy
+from xen.xm import main as xm_main
+from xen.xm.main import server
+
+def help():
+    return """
+    Usage: xm getpolicy [options]
+
+    The following options are defined
+      --dumpxml     Display the XML of the policy
+
+    Get the policy managed by xend."""
+
+def getpolicy(dumpxml):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('xm needs to be configured to use the xen-api.')
+    types = []
+    xstype = int(server.xenapi.XSPolicy.get_xstype())
+    if xstype & xsconstants.XS_POLICY_ACM:
+        types.append("ACM")
+        xstype ^= xsconstants.XS_POLICY_ACM
+    if xstype != 0:
+        types.append("unsupported (%08x)" % xstype)
+    print "Supported security subsystems   : %s \n" % ", ".join(types)
+
+    policystate = server.xenapi.XSPolicy.get_xspolicy()
+    if int(policystate['type']) == 0:
+        print "No policy is installed."
+        return
+    if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
+        print "Unknown policy type '%s'." % policystate['type']
+    else:
+        xml = policystate['repr']
+        acmpol = None
+        if xml:
+            acmpol = ACMPolicy(xml=xml)
+        print "Policy installed on the system:"
+        if acmpol:
+            print "Policy name           : %s" % acmpol.get_name()
+        print "Policy type           : %s" % xsconstants.ACM_POLICY_ID
+        print "Reference             : %s" % policystate['xs_ref']
+        print "Version of XML policy : %s" % policystate['version']
+        state = []
+        flags = int(policystate['flags'])
+        if flags & xsconstants.XS_INST_LOAD:
+            state.append("loaded")
+        if flags & xsconstants.XS_INST_BOOT:
+            state.append("system booted with")
+        print "State of the policy   : %s" % ", ".join(state)
+        if dumpxml:
+            xml = policystate['repr']
+            if xml:
+                dom = minidom.parseString(xml.encode("utf-8"))
+                print "%s" % dom.toprettyxml(indent="   ",newl="\n")
+
+def main(argv):
+    dumpxml = False
+
+    if '--dumpxml' in argv:
+        dumpxml = True
+
+    getpolicy(dumpxml)
+
+if __name__ == '__main__':
+    try:
+        main(sys.argv)
+    except Exception, e:
+        sys.stderr.write('Error: %s\n' % str(e))
+        sys.exit(-1)
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/labels.py
--- a/tools/python/xen/xm/labels.py     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/labels.py     Fri Jul 27 08:15:16 2007 -0600
@@ -24,6 +24,10 @@ from xen.util.security import ACMError, 
 from xen.util.security import ACMError, err, list_labels, active_policy
 from xen.util.security import vm_label_re, res_label_re, all_label_re
 from xen.xm.opts import OptionError
+from xen.util.acmpolicy import ACMPolicy
+from xen.util import xsconstants
+from xen.xm.main import server
+from xen.xm import main as xm_main
 
 
 def help():
@@ -48,6 +52,12 @@ def main(argv):
         else:
             raise OptionError('Unrecognised option: %s' % arg)
 
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        labels(policy, ptype)
+    else:
+        labels_xapi(policy, ptype)
+
+def labels(policy, ptype):
     if not policy:
         policy = active_policy
         if active_policy in ['NULL', 'INACTIVE', 'DEFAULT']:
@@ -73,7 +83,30 @@ def main(argv):
     except:
         traceback.print_exc(limit = 1)
 
+def labels_xapi(policy, ptype):
+    policystate = server.xenapi.XSPolicy.get_xspolicy()
+    if int(policystate['type']) == xsconstants.XS_POLICY_ACM:
+        acmpol = ACMPolicy(xml=policystate['repr'])
+        if policy and policy != acmpol.get_name():
+            print "Warning: '%s' is not the currently loaded policy." % policy
+            return labels(policy, ptype)
+        names1 = []
+        names2 = []
+        if not ptype or ptype == 'dom' or ptype == 'any':
+            names1 = acmpol.policy_get_virtualmachinelabel_names()
+        if ptype == 'res' or ptype == 'any':
+            names2 = acmpol.policy_get_resourcelabel_names()
+        if len(names1) > 0:
+            names = set(names1)
+            names.union(names2)
+        else:
+            names = set(names2)
+        for n in names:
+            print n
+    elif int(policystate['type']) == 0:
+        print "No policy installed on the system."
+    else:
+        print "Unsupported type of policy installed on the system."
+
 if __name__ == '__main__':
     main(sys.argv)
-
-
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/loadpolicy.py
--- a/tools/python/xen/xm/loadpolicy.py Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/loadpolicy.py Fri Jul 27 08:15:16 2007 -0600
@@ -22,6 +22,11 @@ import traceback
 import traceback
 from xen.util.security import ACMError, err, load_policy
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.util import xsconstants
+from xen.xm.activatepolicy import activate_policy
+from xen.xm.main import server
+from xen.util.acmpolicy import ACMPolicy
 
 def help():
     return """Load the compiled binary (.bin) policy into the running
@@ -30,8 +35,31 @@ def main(argv):
 def main(argv):
     if len(argv) != 2:
         raise OptionError('No policy defined')
-    
-    load_policy(argv[1])
+    if xm_main.serverType == xm_main.SERVER_XEN_API:
+        policy = argv[1]
+        print "This command is deprecated for use with Xen-API " \
+              "configuration. Consider using\n'xm activatepolicy'."
+        policystate = server.xenapi.XSPolicy.get_xspolicy()
+        if int(policystate['type']) == 0:
+            print "No policy is installed."
+            return
+
+        if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
+            print "Unknown policy type '%s'." % policystate['type']
+            return
+        else:
+            xml = policystate['repr']
+            xs_ref = policystate['xs_ref']
+            if not xml:
+                OptionError("No policy installed on system?")
+            acmpol = ACMPolicy(xml=xml)
+            if acmpol.get_name() != policy:
+                OptionError("Policy installed on system '%s' does not match"\
+                            " the request policy '%s'" % \
+                            (acmpol.get_name(), policy))
+            activate_policy(xsconstants.XS_INST_LOAD)
+    else:
+        load_policy(argv[1])
 
 if __name__ == '__main__':
     try:
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/main.py
--- a/tools/python/xen/xm/main.py       Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/main.py       Fri Jul 27 08:15:16 2007 -0600
@@ -50,6 +50,7 @@ from xen.xm.opts import OptionError, Opt
 from xen.xm.opts import OptionError, Opts, wrap, set_true
 from xen.xm import console
 from xen.util.xmlrpcclient import ServerProxy
+from xen.util.security import ACMError
 
 import XenAPI
 
@@ -171,11 +172,12 @@ SUBCOMMAND_HELP = {
 
     # security
 
-    'addlabel'      :  ('<label> {dom <ConfigFile>|res <resource>} [<policy>]',
+    'addlabel'      :  ('<label> {dom <ConfigFile>|res <resource>|mgt <managed 
domain>}\n'
+                        '                   [<policy>]',
                         'Add security label to domain.'),
-    'rmlabel'       :  ('{dom <ConfigFile>|res <Resource>}',
+    'rmlabel'       :  ('{dom <ConfigFile>|res <Resource>|mgt<managed 
domain>}',
                         'Remove a security label from domain.'),
-    'getlabel'      :  ('{dom <ConfigFile>|res <Resource>}',
+    'getlabel'      :  ('{dom <ConfigFile>|res <Resource>|mgt <managed 
domain>}',
                         'Show security label for domain or resource.'),
     'dry-run'       :  ('<ConfigFile>',
                         'Test if a domain can access its resources.'),
@@ -186,6 +188,10 @@ SUBCOMMAND_HELP = {
     'loadpolicy'    :  ('<policy.bin>', 'Load binary policy into hypervisor.'),
     'makepolicy'    :  ('<policy>', 'Build policy and create .bin/.map '
                         'files.'),
+    'setpolicy'     :  ('<policytype> <policyfile> [options]',
+                        'Set the policy of the system.'),
+    'getpolicy'     :  ('[options]', 'Get the policy of the system.'),
+    'activatepolicy':  ('[options]', 'Activate the xend-managed policy.'),
     'labels'        :  ('[policy] [type=dom|res|any]',
                         'List <type> labels for (active) policy.'),
     'serve'         :  ('', 'Proxy Xend XMLRPC over stdio.'),
@@ -343,6 +349,9 @@ acm_commands = [
     "loadpolicy",
     "cfgbootpolicy",
     "dumppolicy",
+    "activatepolicy",
+    "setpolicy",
+    "getpolicy",
     ]
 
 all_commands = (domain_commands + host_commands + scheduler_commands +
@@ -861,13 +870,13 @@ def parse_doms_info(info):
         'up_time'  : up_time
         }
 
-    # We're not supporting security stuff just yet via XenAPI
-
-    if serverType != SERVER_XEN_API:
-        from xen.util import security
-        parsed_info['seclabel'] = security.get_security_printlabel(info)
-    else:
-        parsed_info['seclabel'] = ""
+    security_label = get_info('security_label', str, '')
+    tmp = security_label.split(":")
+    if len(tmp) != 3:
+        seclabel = ""
+    else:
+        seclabel = tmp[2]
+    parsed_info['seclabel'] = seclabel
 
     if serverType == SERVER_XEN_API:
         parsed_info['mem'] = get_info('memory_actual', int, 0) / 1024
@@ -925,28 +934,26 @@ def xm_brief_list(doms):
         print format % d
 
 def xm_label_list(doms):
-    print '%-32s %5s %5s %5s %5s %9s %-8s' % \
+    print '%-32s %5s %5s %5s %10s %9s %-8s' % \
           ('Name', 'ID', 'Mem', 'VCPUs', 'State', 'Time(s)', 'Label')
     
     output = []
     format = '%(name)-32s %(domid)5s %(mem)5d %(vcpus)5d %(state)10s ' \
              '%(cpu_time)8.1f %(seclabel)9s'
 
-    if serverType != SERVER_XEN_API:
-        from xen.util import security
+    from xen.util import security
         
-        for dom in doms:
-            d = parse_doms_info(dom)
-
-            if security.active_policy not in ['INACTIVE', 'NULL', 'DEFAULT']:
-                if not d['seclabel']:
-                    d['seclabel'] = 'ERROR'
-            elif security.active_policy in ['DEFAULT']:
-                d['seclabel'] = 'DEFAULT'
-            else:
-                d['seclabel'] = 'INACTIVE'
-
-            output.append((format % d, d['seclabel']))
+    for dom in doms:
+        d = parse_doms_info(dom)
+        if security.active_policy not in ['INACTIVE', 'NULL', 'DEFAULT']:
+            if not d['seclabel']:
+                d['seclabel'] = 'ERROR'
+        elif security.active_policy in ['DEFAULT']:
+            d['seclabel'] = 'DEFAULT'
+        else:
+            d['seclabel'] = 'INACTIVE'
+
+        output.append((format % d, d['seclabel']))
         
     #sort by labels
     output.sort(lambda x,y: cmp( x[1].lower(), y[1].lower()))
@@ -1016,13 +1023,13 @@ def xm_vcpu_list(args):
         if args:
             dominfo = map(server.xend.domain.getVCPUInfo, args)
         else:
-            doms = server.xend.domains(False)
+            doms = server.xend.domains_with_state(False, 'all', False)
             dominfo = map(server.xend.domain.getVCPUInfo, doms)
 
     print '%-32s %5s %5s %5s %5s %9s %s' % \
           ('Name', 'ID', 'VCPU', 'CPU', 'State', 'Time(s)', 'CPU Affinity')
 
-    format = '%(name)-32s %(domid)5d %(number)5d %(c)5s %(s)5s ' \
+    format = '%(name)-32s %(domid)5s %(number)5d %(c)5s %(s)5s ' \
              ' %(cpu_time)8.1f %(cpumap)s'
 
     for dom in dominfo:
@@ -1091,8 +1098,12 @@ def xm_vcpu_list(args):
 
             return format_pairs(list_to_rangepairs(cpumap))
 
-        name  =     get_info('name')
-        domid = int(get_info('domid'))
+        name  = get_info('name')
+        domid = get_info('domid')
+        if domid is not None:
+            domid = str(domid)
+        else:
+            domid = ''
 
         for vcpu in sxp.children(dom, 'vcpu'):
             def vinfo(n, t):
@@ -1106,7 +1117,10 @@ def xm_vcpu_list(args):
             running  = vinfo('running',  int)
             blocked  = vinfo('blocked',  int)
 
-            if online:
+            if cpu < 0:
+                c = ''
+                s = ''
+            elif online:
                 c = str(cpu)
                 if running:
                     s = 'r'
@@ -1118,8 +1132,8 @@ def xm_vcpu_list(args):
                     s += '-'
                 s += '-'
             else:
-                c = "-"
-                s = "--p"
+                c = '-'
+                s = '--p'
 
             print format % locals()
 
@@ -1722,14 +1736,16 @@ def xm_uptime(args):
         if k in ['-s', '--short']:
             short_mode = 1
 
-    doms = getDomains(params, 'running')
+    doms = getDomains(params, 'all')
 
     if short_mode == 0:
         print '%-33s %4s %s ' % ('Name','ID','Uptime')
 
     for dom in doms:
         d = parse_doms_info(dom)
-        if int(d['domid']) > 0:
+        if d['domid'] == '':
+            uptime = 0
+        elif int(d['domid']) > 0:
             uptime = int(round(d['up_time']))
         else:
             f=open('/proc/uptime', 'r')
@@ -1989,16 +2005,24 @@ def xm_block_list(args):
                    % ni)
 
 def xm_vtpm_list(args):
-    xenapi_unsupported()
     (use_long, params) = arg_check_for_resource_list(args, "vtpm-list")
 
     dom = params[0]
+
+    if serverType == SERVER_XEN_API:
+        vtpm_refs = server.xenapi.VM.get_VTPMs(get_single_vm(dom))
+        vtpm_properties = \
+            map(server.xenapi.VTPM.get_runtime_properties, vtpm_refs)
+        devs = map(lambda (handle, properties): [handle, map2sxp(properties)],
+                   zip(range(len(vtpm_properties)), vtpm_properties))
+    else:
+        devs = server.xend.domain.getDeviceSxprs(dom, 'vtpm')
+
     if use_long:
-        devs = server.xend.domain.getDeviceSxprs(dom, 'vtpm')
         map(PrettyPrint.prettyprint, devs)
     else:
         hdr = 0
-        for x in server.xend.domain.getDeviceSxprs(dom, 'vtpm'):
+        for x in devs:
             if hdr == 0:
                 print 'Idx  BE handle state evt-ch ring-ref BE-path'
                 hdr = 1
@@ -2028,18 +2052,6 @@ def parse_block_configuration(args):
            ['mode',  args[3]]]
     if len(args) == 5:
         vbd.append(['backend', args[4]])
-
-    if serverType != SERVER_XEN_API:
-        # verify that policy permits attaching this resource
-        from xen.util import security
-    
-        if security.on():
-            dominfo = server.xend.domain(dom)
-            label = security.get_security_printlabel(dominfo)
-        else:
-            label = None
-
-        security.res_security_check(args[1], label)
 
     return (dom, vbd)
 
@@ -2440,6 +2452,9 @@ IMPORTED_COMMANDS = [
     'getlabel',
     'dry-run',
     'resources',
+    'getpolicy',
+    'setpolicy',
+    'activatepolicy',
     ]
 
 for c in IMPORTED_COMMANDS:
@@ -2563,6 +2578,8 @@ def _run_cmd(cmd, cmd_name, args):
         print e.usage
     except XenAPIUnsupportedException, e:
         err(str(e))
+    except ACMError, e:
+        err(str(e))
     except Exception, e:
         if serverType != SERVER_XEN_API:
            from xen.util import security
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/makepolicy.py
--- a/tools/python/xen/xm/makepolicy.py Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/makepolicy.py Fri Jul 27 08:15:16 2007 -0600
@@ -20,7 +20,10 @@ import sys
 import sys
 import traceback
 from xen.util.security import ACMError, err, make_policy
+from xen.util import xsconstants
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.xm.setpolicy import setpolicy
 
 def usage():
     print "\nUsage: xm makepolicy <policy>\n"
@@ -32,8 +35,13 @@ def main(argv):
 def main(argv):
     if len(argv) != 2:
         raise OptionError('No XML policy file specified')
-
-    make_policy(argv[1])
+    if xm_main.serverType == xm_main.SERVER_XEN_API:
+        print "This command is deprecated for use with Xen-API " \
+              "configuration. Consider using\n'xm setpolicy'."
+        setpolicy(xsconstants.ACM_POLICY_ID, argv[1],
+                  xsconstants.XS_INST_LOAD, True)
+    else:
+        make_policy(argv[1])
 
 if __name__ == '__main__':
     try:
@@ -41,5 +49,3 @@ if __name__ == '__main__':
     except Exception, e:
         sys.stderr.write('Error: %s\n' % str(e))
         sys.exit(-1)
-
-
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/resources.py
--- a/tools/python/xen/xm/resources.py  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/resources.py  Fri Jul 27 08:15:16 2007 -0600
@@ -21,7 +21,10 @@ import sys
 import sys
 from xen.util import dictio
 from xen.util import security
+from xen.util import xsconstants
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.xm.main import server
 
 def help():
     return """
@@ -32,20 +35,32 @@ def print_resource_data(access_control):
     """Prints out a resource dictionary to stdout
     """
     for resource in access_control:
-        (policy, label) = access_control[resource]
+        tmp = access_control[resource]
+        if len(tmp) == 2:
+            policytype = xsconstants.ACM_POLICY_ID
+            (policy, label) = access_control[resource]
+        elif len(tmp) == 3:
+            policytype, policy, label = access_control[resource]
         print resource
-        print "    policy: "+policy
-        print "    label:  "+label
+        print "      type: "+ policytype
+        print "    policy: "+ policy
+        print "    label:  "+ label
 
 def main (argv):
     if len(argv) > 1:
         raise OptionError("No arguments required")
-    
-    try:
-        filename = security.res_label_filename
-        access_control = dictio.dict_read("resources", filename)
-    except:
-        raise OptionError("Resource file not found")
+
+    if xm_main.serverType == xm_main.SERVER_XEN_API:
+        access_control = server.xenapi.XSPolicy.get_labeled_resources()
+        for key, value in access_control.items():
+            access_control[key] = tuple(value.split(':'))
+    else:
+        try:
+            filename = security.res_label_filename
+            access_control = dictio.dict_read("resources", filename)
+            print access_control
+        except:
+            raise OptionError("Resource file not found")
 
     print_resource_data(access_control)
 
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/rmlabel.py
--- a/tools/python/xen/xm/rmlabel.py    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/rmlabel.py    Fri Jul 27 08:15:16 2007 -0600
@@ -22,35 +22,53 @@ from xen.util import dictio
 from xen.util import dictio
 from xen.util import security
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.xm.main import server
 
 def help():
     return """
     Example: xm rmlabel dom <configfile>
              xm rmlabel res <resource>
+             xm rmlabel mgt <domain name>
+             xm rmlabel vif-<idx> <domain name>
 
     This program removes an acm_label entry from the 'configfile'
-    for a domain or from the global resource label file for a
-    resource. If the label does not exist for the given domain or
-    resource, then rmlabel fails."""
+    for a domain, from a Xend-managed domain, from the global resource label
+    file for a resource or from the virtual network interface of a Xend-managed
+    domain. If the label does not exist for the given domain or resource, then
+    rmlabel fails."""
 
 
 def rm_resource_label(resource):
     """Removes a resource label from the global resource label file.
     """
+    # Try Xen-API first if configured to use it
+    if xm_main.serverType == xm_main.SERVER_XEN_API:
+        try:
+            oldlabel = server.xenapi.XSPolicy.get_resource_label(resource)
+            if oldlabel != "":
+                server.xenapi.XSPolicy.set_resource_label(resource,"",
+                                                          oldlabel)
+            else:
+                raise security.ACMError("Resource not labeled")
+        except Exception, e:
+            print "Could not remove label from resource: %s" % e
+        return
+
     #build canonical resource name
     resource = security.unify_resname(resource)
 
     # read in the resource file
-    file = security.res_label_filename
+    fil = security.res_label_filename
     try:
-        access_control = dictio.dict_read("resources", file)
+        access_control = dictio.dict_read("resources", fil)
     except:
         raise security.ACMError("Resource file not found, cannot remove 
label!")
 
     # remove the entry and update file
     if access_control.has_key(resource):
         del access_control[resource]
-        dictio.dict_write(access_control, "resources", file)
+        dictio.dict_write(access_control, "resources", fil)
     else:
         raise security.ACMError("Resource not labeled")
 
@@ -58,15 +76,15 @@ def rm_domain_label(configfile):
 def rm_domain_label(configfile):
     # open the domain config file
     fd = None
-    file = None
+    fil = None
     if configfile[0] == '/':
-        file = configfile
-        fd = open(file, "rb")
+        fil = configfile
+        fd = open(fil, "rb")
     else:
         for prefix in [".", "/etc/xen"]:
-            file = prefix + "/" + configfile
-            if os.path.isfile(file):
-                fd = open(file, "rb")
+            fil = prefix + "/" + configfile
+            if os.path.isfile(fil):
+                fd = open(fil, "rb")
                 break
     if not fd:
         raise OptionError("Configuration file '%s' not found." % configfile)
@@ -93,9 +111,47 @@ def rm_domain_label(configfile):
         raise security.ACMError('Domain not labeled')
 
     # write the data back out to the file
-    fd = open(file, "wb")
+    fd = open(fil, "wb")
     fd.writelines(file_contents)
     fd.close()
+
+def rm_domain_label_xapi(domainname):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('Need to be configure for using xen-api.')
+    uuids = server.xenapi.VM.get_by_name_label(domainname)
+    if len(uuids) == 0:
+        raise OptionError('A VM with that name does not exist.')
+    if len(uuids) != 1:
+        raise OptionError('Too many domains with the same name.')
+    uuid = uuids[0]
+    try:
+        old_lab = server.xenapi.VM.get_security_label(uuid)
+        server.xenapi.VM.set_security_label(uuid, "", old_lab)
+    except Exception, e:
+        print('Could not remove label from domain: %s' % e)
+
+def rm_vif_label(vmname, idx):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('Need to be configure for using xen-api.')
+    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
+    if len(vm_refs) == 0:
+        raise OptionError('A VM with the name %s does not exist.' %
+                          vmname)
+    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
+    if len(vif_refs) <= idx:
+        raise OptionError("Bad VIF index.")
+    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
+    if not vif_ref:
+        print "A VIF with this UUID does not exist."
+    try:
+        old_lab = server.xenapi.VIF.get_security_label(vif_ref)
+        rc = server.xenapi.VIF.set_security_label(vif_ref, "", old_lab)
+        if int(rc) != 0:
+            print "Could not remove the label from the VIF."
+        else:
+            print "Successfully removed the label from the VIF."
+    except Exception, e:
+        print "Could not remove the label the VIF: %s" % str(e)
 
 
 def main (argv):
@@ -103,15 +159,26 @@ def main (argv):
     if len(argv) != 3:
         raise OptionError('Requires 2 arguments')
     
-    if argv[1].lower() not in ('dom', 'res'):
-        raise OptionError('Unrecognised type argument: %s' % argv[1])
-
     if argv[1].lower() == "dom":
         configfile = argv[2]
         rm_domain_label(configfile)
+    elif argv[1].lower() == "mgt":
+        domain = argv[2]
+        rm_domain_label_xapi(domain)
+    elif argv[1].lower().startswith("vif-"):
+        try:
+            idx = int(argv[1][4:])
+            if idx < 0:
+                raise
+        except:
+            raise OptionError("Bad VIF device index.")
+        vmname = argv[2]
+        rm_vif_label(vmname, idx)
     elif argv[1].lower() == "res":
         resource = argv[2]
         rm_resource_label(resource)
+    else:
+        raise OptionError('Unrecognised type argument: %s' % argv[1])
 
 if __name__ == '__main__':
     try:
@@ -119,5 +186,3 @@ if __name__ == '__main__':
     except Exception, e:
         sys.stderr.write('Error: %s\n' % str(e))
         sys.exit(-1)    
-
-
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/setpolicy.py
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/python/xen/xm/setpolicy.py  Fri Jul 27 08:15:16 2007 -0600
@@ -0,0 +1,117 @@
+#============================================================================
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of version 2.1 of the GNU Lesser General Public
+# License as published by the Free Software Foundation.
+#
+# 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#============================================================================
+# Copyright (C) 2007 International Business Machines Corp.
+# Author: Stefan Berger <stefanb@xxxxxxxxxx>
+#============================================================================
+
+"""Get the managed policy of the system.
+"""
+
+import base64
+import struct
+import sys
+import string
+from xen.util import xsconstants
+from xen.xm.opts import OptionError
+from xen.util.security import policy_dir_prefix
+from xen.xm import main as xm_main
+from xen.xm.main import server
+
+def help():
+    return """
+    Usage: xm setpolicy <policytype> <policy> [options]
+
+    Set the policy managed by xend.
+
+    The only policytype that is currently supported is 'ACM'.
+
+    The following options are defined
+      --load     Load the policy immediately
+      --boot     Have the system load the policy during boot
+    """
+
+def setpolicy(policytype, policy_name, flags, overwrite):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('xm needs to be configured to use the xen-api.')
+    if policytype != xsconstants.ACM_POLICY_ID:
+        raise OptionError("Unsupported policytype '%s'." % policytype)
+    else:
+        xs_type = xsconstants.XS_POLICY_ACM
+
+        policy_file = policy_dir_prefix + "/" + \
+                      string.join(string.split(policy_name, "."), "/")
+        policy_file += "-security_policy.xml"
+
+        try:
+            f = open(policy_file,"r")
+            xml = f.read(-1)
+            f.close()
+        except:
+            raise OptionError("Not a valid policy file")
+
+        try:
+            policystate = server.xenapi.XSPolicy.set_xspolicy(xs_type,
+                                                              xml,
+                                                              flags,
+                                                              overwrite)
+        except Exception, e:
+            print "An error occurred setting the policy: %s" % str(e)
+            return
+        xserr = int(policystate['xserr'])
+        if xserr != 0:
+            print "An error occurred trying to set the policy: %s" % \
+                  xsconstants.xserr2string(abs(xserr))
+            errors = policystate['errors']
+            if len(errors) > 0:
+                print "Hypervisor reported errors:"
+                err = base64.b64decode(errors)
+                i = 0
+                while i + 7 < len(err):
+                    code, data = struct.unpack("!ii", errors[i:i+8])
+                    print "(0x%08x, 0x%08x)" % (code, data)
+                    i += 8
+        else:
+            print "Successfully set the new policy."
+
+
+def main(argv):
+    if len(argv) < 3:
+       raise OptionError("Need at least 3 arguments.")
+
+    if "-?" in argv:
+        help()
+        return
+
+    policytype  = argv[1]
+    policy_name = argv[2]
+
+    flags = 0
+    if '--load' in argv:
+        flags |= xsconstants.XS_INST_LOAD
+    if '--boot' in argv:
+        flags |= xsconstants.XS_INST_BOOT
+
+    overwrite = True
+    if '--nooverwrite' in argv:
+        overwrite = False
+
+    setpolicy(policytype, policy_name, flags, overwrite)
+
+if __name__ == '__main__':
+    try:
+        main(sys.argv)
+    except Exception, e:
+        sys.stderr.write('Error: %s\n' % str(e))
+        sys.exit(-1)
diff -r 37833b33ae77 -r 4492a0285bae tools/python/xen/xm/xenapi_create.py
--- a/tools/python/xen/xm/xenapi_create.py      Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/python/xen/xm/xenapi_create.py      Fri Jul 27 08:15:16 2007 -0600
@@ -25,6 +25,7 @@ from xen.xend.XendAPIConstants import XE
 from xen.xend.XendAPIConstants import XEN_API_ON_NORMAL_EXIT, \
      XEN_API_ON_CRASH_BEHAVIOUR
 from xen.xm.opts import OptionError
+from xen.util import xsconstants
 
 import sys
 import os
@@ -308,6 +309,12 @@ class xenapi_create:
                ""
             }
 
+        if vm.attributes.has_key("security_label"):
+            vm_record.update({
+                "security_label":
+                    vm.attributes["security_label"].value
+                })
+
         if len(vm.getElementsByTagName("pv")) > 0:
             vm_record.update({
                 "PV_bootloader":
@@ -348,6 +355,12 @@ class xenapi_create:
 
             self.create_vifs(vm_ref, vifs, networks)
 
+            # Now create vtpms
+
+            vtpms = vm.getElementsByTagName("vtpm")
+
+            self.create_vtpms(vm_ref, vtpms)
+
             # Now create consoles
 
             consoles = vm.getElementsByTagName("console")
@@ -427,7 +440,9 @@ class xenapi_create:
                 vif.attributes["qos_algorithm_type"].value,
             "qos_algorithm_params":
                 get_child_nodes_as_dict(vif,
-                    "qos_algorithm_param", "key", "value")
+                    "qos_algorithm_param", "key", "value"),
+            "security_label":
+                vif.attributes["security_label"].value
         }
 
         return server.xenapi.VIF.create(vif_record)
@@ -440,6 +455,21 @@ class xenapi_create:
         except IndexError:
             self._network_refs = server.xenapi.network.get_all()
             return self._network_refs.pop(0)
+
+    def create_vtpms(self, vm_ref, vtpms):
+        if len(vtpms) > 1:
+            vtpms = [ vtpms[0] ]
+        log(DEBUG, "create_vtpms")
+        return map(lambda vtpm: self.create_vtpm(vm_ref, vtpm), vtpms)
+
+    def create_vtpm(self, vm_ref, vtpm):
+        vtpm_record = {
+            "VM":
+                vm_ref,
+            "backend":
+                vtpm.attributes["backend"].value
+        }
+        return server.xenapi.VTPM.create(vtpm_record)
 
     def create_consoles(self, vm_ref, consoles):
         log(DEBUG, "create_consoles")
@@ -482,6 +512,10 @@ class sxp2xml:
 
         vifs_sxp = map(lambda x: x[1], [device for device in devices
                                         if device[1][0] == "vif"])
+
+        vtpms_sxp = map(lambda x: x[1], [device for device in devices
+                                         if device[1][0] == "vtpm"])
+
         # Create XML Document
         
         impl = getDOMImplementation()
@@ -530,6 +564,14 @@ class sxp2xml:
             = str(get_child_by_name(config, "vcpus", 1))
         vm.attributes["vcpus_at_startup"] \
             = str(get_child_by_name(config, "vcpus", 1))
+
+        sec_data = get_child_by_name(config, "security")
+        if sec_data:
+            try :
+                vm.attributes['security_label'] = \
+                      "%s:%s:%s" % (xsconstants.ACM_POLICY_ID, 
sec_data[0][1][1],sec_data[0][2][1])
+            except Exception, e:
+                raise "Invalid security data format: %s" % str(sec_data)
 
         # Make the name tag
 
@@ -601,6 +643,12 @@ class sxp2xml:
 
         map(vm.appendChild, vifs)
 
+        # And now the vTPMs
+
+        vtpms = map(lambda vtpm: self.extract_vtpm(vtpm, document), vtpms_sxp)
+
+        map(vm.appendChild, vtpms)
+
         # Last but not least the consoles...
 
         consoles = self.extract_consoles(image, document)
@@ -702,11 +750,29 @@ class sxp2xml:
         vif.attributes["device"] = dev
         vif.attributes["qos_algorithm_type"] = ""
 
+        policy = get_child_by_name(vif_sxp, "policy")
+        label = get_child_by_name(vif_sxp, "label")
+
+        if label and policy:
+            vif.attributes["security_label"] \
+                 = "%s:%s:%s" % (xsconstants.ACM_POLICY_ID, policy, label)
+        else:
+            vif.attributes["security_label"] = ""
+
         if get_child_by_name(vif_sxp, "bridge") is not None:
             vif.attributes["network"] \
                 = get_child_by_name(vif_sxp, "bridge")
         
         return vif
+
+    def extract_vtpm(self, vtpm_sxp, document):
+
+        vtpm = document.createElement("vtpm")
+
+        vtpm.attributes["backend"] \
+             = get_child_by_name(vtpm_sxp, "backend", "0")
+
+        return vtpm
 
     _eths = -1
 
diff -r 37833b33ae77 -r 4492a0285bae tools/security/policies/security_policy.xsd
--- a/tools/security/policies/security_policy.xsd       Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/security/policies/security_policy.xsd       Fri Jul 27 08:15:16 
2007 -0600
@@ -99,7 +99,7 @@
                        <xsd:sequence>
                                <xsd:element name="Name" 
type="NameWithFrom"></xsd:element>
                                <xsd:element ref="SimpleTypeEnforcementTypes" 
minOccurs="0" maxOccurs="unbounded" />
-                               <xsd:element name="ChineseWallTypes" 
type="SingleChineseWallType" />
+                               <xsd:element ref="ChineseWallTypes" 
minOccurs="0" maxOccurs="unbounded" />
                        </xsd:sequence>
                </xsd:complexType>
        </xsd:element>
@@ -143,9 +143,4 @@
                        <xsd:element maxOccurs="1" minOccurs="1" ref="Type" />
                </xsd:sequence>
        </xsd:complexType>
-       <xsd:complexType name="SingleChineseWallType">
-               <xsd:sequence>
-                       <xsd:element maxOccurs="1" minOccurs="1" ref="Type" />
-               </xsd:sequence>
-       </xsd:complexType>
 </xsd:schema>
diff -r 37833b33ae77 -r 4492a0285bae tools/vtpm_manager/util/hashtable_itr.c
--- a/tools/vtpm_manager/util/hashtable_itr.c   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/vtpm_manager/util/hashtable_itr.c   Fri Jul 27 08:15:16 2007 -0600
@@ -225,7 +225,7 @@ hashtable_iterator_search(struct hashtab
     
 egress:
 #ifdef HASHTABLE_THREADED
-    pthread_mutex_lock(&h->mutex);
-#endif 
-    return ret;
-}
+    pthread_mutex_unlock(&h->mutex);
+#endif 
+    return ret;
+}
diff -r 37833b33ae77 -r 4492a0285bae tools/xcutils/xc_save.c
--- a/tools/xcutils/xc_save.c   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xcutils/xc_save.c   Fri Jul 27 08:15:16 2007 -0600
@@ -54,7 +54,17 @@ static int suspend(int domid)
 
 static char *qemu_active_path;
 static char *qemu_next_active_path;
+static int qemu_shmid = -1;
 static struct xs_handle *xs;
+
+
+/* Mark the shared-memory segment for destruction */
+static void qemu_destroy_buffer(void)
+{
+    if (qemu_shmid != -1)
+        shmctl(qemu_shmid, IPC_RMID, NULL);
+    qemu_shmid = -1;
+}
 
 /* Get qemu to change buffers. */
 static void qemu_flip_buffer(int domid, int next_active)
@@ -97,22 +107,23 @@ static void * init_qemu_maps(int domid, 
 {
     key_t key;
     char key_ascii[17] = {0,};
-    int shmid = -1;
     void *seg; 
     char *path, *p;
 
     /* Make a shared-memory segment */
-    while (shmid == -1)
-    {
+    do {
         key = rand(); /* No security, just a sequence of numbers */
-        shmid = shmget(key, 2 * bitmap_size, 
+        qemu_shmid = shmget(key, 2 * bitmap_size, 
                        IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR);
-        if (shmid == -1 && errno != EEXIST)
+        if (qemu_shmid == -1 && errno != EEXIST)
             errx(1, "can't get shmem to talk to qemu-dm");
-    }
+    } while (qemu_shmid == -1);
+
+    /* Remember to tidy up after ourselves */
+    atexit(qemu_destroy_buffer);
 
     /* Map it into our address space */
-    seg = shmat(shmid, NULL, 0);
+    seg = shmat(qemu_shmid, NULL, 0);
     if (seg == (void *) -1) 
         errx(1, "can't map shmem to talk to qemu-dm");
     memset(seg, 0, 2 * bitmap_size);
@@ -123,11 +134,13 @@ static void * init_qemu_maps(int domid, 
     /* Tell qemu about it */
     if ((xs = xs_daemon_open()) == NULL)
         errx(1, "Couldn't contact xenstore");
-    if (!(path = xs_get_domain_path(xs, domid)))
+    if (!(path = strdup("/local/domain/0/device-model/")))
         errx(1, "can't get domain path in store");
     if (!(path = realloc(path, strlen(path) 
+                         + 10 
                          + strlen("/logdirty/next-active") + 1))) 
         errx(1, "no memory for constructing xenstore path");
+    snprintf(path + strlen(path), 11, "%i", domid);
     strcat(path, "/logdirty/");
     p = path + strlen(path);
 
diff -r 37833b33ae77 -r 4492a0285bae tools/xenfb/vncfb.c
--- a/tools/xenfb/vncfb.c       Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xenfb/vncfb.c       Fri Jul 27 08:15:16 2007 -0600
@@ -55,11 +55,46 @@ unsigned char keycode_table[512];
 unsigned char keycode_table[512];
 
 static void *kbd_layout;
+uint8_t modifiers_state[256];
 
 static int btnmap[] = {
        BTN_LEFT, BTN_MIDDLE, BTN_RIGHT, BTN_SIDE,
        BTN_EXTRA, BTN_FORWARD, BTN_BACK, BTN_TASK
 };
+
+static void press_key_shift_down(struct xenfb* xenfb, int down, int scancode)
+{
+       if (down)
+               xenfb_send_key(xenfb, 1, keycode_table[0x2a]);
+
+       if (xenfb_send_key(xenfb, down, keycode_table[scancode]) < 0)
+               fprintf(stderr, "Key %d %s lost (%s)\n",
+                       scancode, "down", strerror(errno));
+
+       if (!down)
+               xenfb_send_key(xenfb, 0, keycode_table[0x2a]);
+}
+
+static void press_key_shift_up(struct xenfb* xenfb, int down, int scancode)
+{
+       if (down) {
+               if (modifiers_state[0x2a])
+                       xenfb_send_key(xenfb, 0, keycode_table[0x2a]);
+               if (modifiers_state[0x36])
+                       xenfb_send_key(xenfb, 0, keycode_table[0x36]);
+       }
+
+       if (xenfb_send_key(xenfb, down, keycode_table[scancode]) < 0)
+               fprintf(stderr, "Key %d %s lost (%s)\n",
+                       scancode, "down", strerror(errno));
+
+       if (!down) {
+               if (modifiers_state[0x2a])
+                       xenfb_send_key(xenfb, 1, keycode_table[0x2a]);
+               if (modifiers_state[0x36])
+                       xenfb_send_key(xenfb, 1, keycode_table[0x36]);
+       }
+}
 
 static void on_kbd_event(rfbBool down, rfbKeySym keycode, rfbClientPtr cl)
 {
@@ -75,14 +110,75 @@ static void on_kbd_event(rfbBool down, r
        rfbScreenInfoPtr server = cl->screen;
        struct xenfb *xenfb = server->screenData;
        int scancode;
-
-       if (keycode >= 'A' && keycode <= 'Z')
+       int shift = 0;
+       int shift_keys = 0;
+
+       if (keycode >= 'A' && keycode <= 'Z') {
                keycode += 'a' - 'A';
-
-       scancode = keycode_table[keysym2scancode(kbd_layout, keycode)];
+               shift = 1;
+       }
+       else {
+               shift = keysymIsShift(kbd_layout, keycode);
+       }
+       shift_keys = modifiers_state[0x2a] | modifiers_state[0x36];     
+
+       scancode = keysym2scancode(kbd_layout, keycode);
        if (scancode == 0)
                return;
-       if (xenfb_send_key(xenfb, down, scancode) < 0)
+
+       switch(scancode) {
+       case 0x2a:                      /* Left Shift */
+       case 0x36:                      /* Right Shift */
+       case 0x1d:                      /* Left CTRL */
+       case 0x9d:                      /* Right CTRL */
+       case 0x38:                      /* Left ALT */
+       case 0xb8:                      /* Right ALT */
+               if (down)
+                       modifiers_state[scancode] = 1;
+               else
+                       modifiers_state[scancode] = 0;
+               xenfb_send_key(xenfb, down, keycode_table[scancode]); 
+               return;
+       case 0x45:                      /* NumLock */
+               if (!down)
+                       modifiers_state[scancode] ^= 1;
+               xenfb_send_key(xenfb, down, keycode_table[scancode]);
+               return;
+       }
+
+       if (keycodeIsKeypad(kbd_layout, scancode)) {
+       /* If the numlock state needs to change then simulate an additional
+          keypress before sending this one.  This will happen if the user
+          toggles numlock away from the VNC window.
+       */
+               if (keysymIsNumlock(kbd_layout, keycode)) {
+                       if (!modifiers_state[0x45]) {
+                               modifiers_state[0x45] = 1;
+                               xenfb_send_key(xenfb, 1, keycode_table[0x45]);
+                               xenfb_send_key(xenfb, 0, keycode_table[0x45]);
+                       }
+               } else {
+                       if (modifiers_state[0x45]) {
+                               modifiers_state[0x45] = 0;
+                               xenfb_send_key(xenfb, 1, keycode_table[0x45]);
+                               xenfb_send_key(xenfb, 0, keycode_table[0x45]);
+                       }
+               }
+       }
+
+       /* If the shift state needs to change then simulate an additional
+          keypress before sending this one.
+       */
+       if (shift && !shift_keys) {
+               press_key_shift_down(xenfb, down, scancode);
+               return;
+       }
+       else if (!shift && shift_keys) {
+               press_key_shift_up(xenfb, down, scancode);
+               return;
+       }
+
+       if (xenfb_send_key(xenfb, down, keycode_table[scancode]) < 0)
                fprintf(stderr, "Key %d %s lost (%s)\n",
                        scancode, down ? "down" : "up",
                        strerror(errno));
@@ -314,6 +410,10 @@ int main(int argc, char **argv)
                        atkbd_set2_keycode[atkbd_unxlate_table[i] | 0x80];
        }
 
+       for (i = 0; i < 256; i++ ) {
+               modifiers_state[i] = 0;
+       }
+
        fake_argv[2] = portstr;
 
         if (title != NULL)
diff -r 37833b33ae77 -r 4492a0285bae tools/xenstore/talloc.c
--- a/tools/xenstore/talloc.c   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xenstore/talloc.c   Fri Jul 27 08:15:16 2007 -0600
@@ -97,6 +97,7 @@ struct talloc_chunk {
        struct talloc_chunk *next, *prev;
        struct talloc_chunk *parent, *child;
        struct talloc_reference_handle *refs;
+       unsigned int null_refs; /* references from null_context */
        talloc_destructor_t destructor;
        const char *name;
        size_t size;
@@ -189,6 +190,7 @@ void *_talloc(const void *context, size_
        tc->child = NULL;
        tc->name = NULL;
        tc->refs = NULL;
+       tc->null_refs = 0;
 
        if (context) {
                struct talloc_chunk *parent = talloc_chunk_from_ptr(context);
@@ -225,7 +227,11 @@ void talloc_set_destructor(const void *p
 */
 void talloc_increase_ref_count(const void *ptr)
 {
-       talloc_reference(null_context, ptr);
+       struct talloc_chunk *tc;
+       if (ptr == NULL) return;
+
+       tc = talloc_chunk_from_ptr(ptr);
+       tc->null_refs++;
 }
 
 /*
@@ -285,6 +291,11 @@ static int talloc_unreference(const void
 
        if (context == NULL) {
                context = null_context;
+       }
+
+       if ((context == null_context) && tc->null_refs) {
+               tc->null_refs--;
+               return 0;
        }
 
        for (h=tc->refs;h;h=h->next) {
@@ -538,6 +549,11 @@ int talloc_free(void *ptr)
        }
 
        tc = talloc_chunk_from_ptr(ptr);
+
+       if (tc->null_refs) {
+               tc->null_refs--;
+               return -1;
+       }
 
        if (tc->refs) {
                talloc_reference_destructor(tc->refs);
diff -r 37833b33ae77 -r 4492a0285bae tools/xenstore/xenstored_core.c
--- a/tools/xenstore/xenstored_core.c   Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xenstore/xenstored_core.c   Fri Jul 27 08:15:16 2007 -0600
@@ -299,10 +299,14 @@ static void set_fd(int fd, fd_set *set, 
 }
 
 
-static int initialize_set(fd_set *inset, fd_set *outset, int sock, int ro_sock)
-{
-       struct connection *i;
+static int initialize_set(fd_set *inset, fd_set *outset, int sock, int ro_sock,
+                         struct timeval **ptimeout)
+{
+       static struct timeval zero_timeout = { 0 };
+       struct connection *conn;
        int max = -1;
+
+       *ptimeout = NULL;
 
        FD_ZERO(inset);
        FD_ZERO(outset);
@@ -314,13 +318,19 @@ static int initialize_set(fd_set *inset,
        if (xce_handle != -1)
                set_fd(xc_evtchn_fd(xce_handle), inset, &max);
 
-       list_for_each_entry(i, &connections, list) {
-               if (i->domain)
-                       continue;
-               set_fd(i->fd, inset, &max);
-               if (!list_empty(&i->out_list))
-                       FD_SET(i->fd, outset);
-       }
+       list_for_each_entry(conn, &connections, list) {
+               if (conn->domain) {
+                       if (domain_can_read(conn) ||
+                           (domain_can_write(conn) &&
+                            !list_empty(&conn->out_list)))
+                               *ptimeout = &zero_timeout;
+               } else {
+                       set_fd(conn->fd, inset, &max);
+                       if (!list_empty(&conn->out_list))
+                               FD_SET(conn->fd, outset);
+               }
+       }
+
        return max;
 }
 
@@ -1256,7 +1266,7 @@ static void handle_input(struct connecti
        if (in->inhdr) {
                bytes = conn->read(conn, in->hdr.raw + in->used,
                                   sizeof(in->hdr) - in->used);
-               if (bytes <= 0)
+               if (bytes < 0)
                        goto bad_client;
                in->used += bytes;
                if (in->used != sizeof(in->hdr))
@@ -1278,7 +1288,7 @@ static void handle_input(struct connecti
 
        bytes = conn->read(conn, in->buffer + in->used,
                           in->hdr.msg.len - in->used);
-       if (bytes <= 0)
+       if (bytes < 0)
                goto bad_client;
 
        in->used += bytes;
@@ -1331,12 +1341,40 @@ struct connection *new_connection(connwr
 
 static int writefd(struct connection *conn, const void *data, unsigned int len)
 {
-       return write(conn->fd, data, len);
+       int rc;
+
+       while ((rc = write(conn->fd, data, len)) < 0) {
+               if (errno == EAGAIN) {
+                       rc = 0;
+                       break;
+               }
+               if (errno != EINTR)
+                       break;
+       }
+
+       return rc;
 }
 
 static int readfd(struct connection *conn, void *data, unsigned int len)
 {
-       return read(conn->fd, data, len);
+       int rc;
+
+       while ((rc = read(conn->fd, data, len)) < 0) {
+               if (errno == EAGAIN) {
+                       rc = 0;
+                       break;
+               }
+               if (errno != EINTR)
+                       break;
+       }
+
+       /* Reading zero length means we're done with this connection. */
+       if ((rc == 0) && (len != 0)) {
+               errno = EBADF;
+               rc = -1;
+       }
+
+       return rc;
 }
 
 static void accept_connection(int sock, bool canwrite)
@@ -1429,13 +1467,13 @@ static unsigned int hash_from_key_fn(voi
 static unsigned int hash_from_key_fn(void *k)
 {
        char *str = k;
-        unsigned int hash = 5381;
-        char c;
-
-        while ((c = *str++))
+       unsigned int hash = 5381;
+       char c;
+
+       while ((c = *str++))
                hash = ((hash << 5) + hash) + (unsigned int)c;
 
-        return hash;
+       return hash;
 }
 
 
@@ -1709,6 +1747,7 @@ int main(int argc, char *argv[])
        bool no_domain_init = false;
        const char *pidfile = NULL;
        int evtchn_fd = -1;
+       struct timeval *timeout;
 
        while ((opt = getopt_long(argc, argv, "DE:F:HNPS:t:T:RLVW:", options,
                                  NULL)) != -1) {
@@ -1850,17 +1889,16 @@ int main(int argc, char *argv[])
                evtchn_fd = xc_evtchn_fd(xce_handle);
 
        /* Get ready to listen to the tools. */
-       max = initialize_set(&inset, &outset, *sock, *ro_sock);
+       max = initialize_set(&inset, &outset, *sock, *ro_sock, &timeout);
 
        /* Tell the kernel we're up and running. */
        xenbus_notify_running();
 
        /* Main loop. */
-       /* FIXME: Rewrite so noone can starve. */
        for (;;) {
-               struct connection *i;
-
-               if (select(max+1, &inset, &outset, NULL, NULL) < 0) {
+               struct connection *conn, *old_conn;
+
+               if (select(max+1, &inset, &outset, NULL, timeout) < 0) {
                        if (errno == EINTR)
                                continue;
                        barf_perror("Select failed");
@@ -1882,41 +1920,31 @@ int main(int argc, char *argv[])
                if (evtchn_fd != -1 && FD_ISSET(evtchn_fd, &inset))
                        handle_event();
 
-               list_for_each_entry(i, &connections, list) {
-                       if (i->domain)
-                               continue;
-
-                       /* Operations can delete themselves or others
-                        * (xs_release): list is not safe after input,
-                        * so break. */
-                       if (FD_ISSET(i->fd, &inset)) {
-                               handle_input(i);
-                               break;
+               conn = list_entry(connections.next, typeof(*conn), list);
+               while (&conn->list != &connections) {
+                       talloc_increase_ref_count(conn);
+
+                       if (conn->domain) {
+                               if (domain_can_read(conn))
+                                       handle_input(conn);
+                               if (domain_can_write(conn) &&
+                                   !list_empty(&conn->out_list))
+                                       handle_output(conn);
+                       } else {
+                               if (FD_ISSET(conn->fd, &inset))
+                                       handle_input(conn);
+                               if (FD_ISSET(conn->fd, &outset))
+                                       handle_output(conn);
                        }
-                       if (FD_ISSET(i->fd, &outset)) {
-                               handle_output(i);
-                               break;
-                       }
-               }
-
-               /* Handle all possible I/O for domain connections. */
-       more:
-               list_for_each_entry(i, &connections, list) {
-                       if (!i->domain)
-                               continue;
-
-                       if (domain_can_read(i)) {
-                               handle_input(i);
-                               goto more;
-                       }
-
-                       if (domain_can_write(i) && !list_empty(&i->out_list)) {
-                               handle_output(i);
-                               goto more;
-                       }
-               }
-
-               max = initialize_set(&inset, &outset, *sock, *ro_sock);
+
+                       old_conn = conn;
+                       conn = list_entry(old_conn->list.next,
+                                         typeof(*conn), list);
+                       talloc_free(old_conn);
+               }
+
+               max = initialize_set(&inset, &outset, *sock, *ro_sock,
+                                    &timeout);
        }
 }
 
diff -r 37833b33ae77 -r 4492a0285bae tools/xenstore/xenstored_domain.c
--- a/tools/xenstore/xenstored_domain.c Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xenstore/xenstored_domain.c Fri Jul 27 08:15:16 2007 -0600
@@ -76,7 +76,6 @@ struct domain
 
 static LIST_HEAD(domains);
 
-/* FIXME: Mark connection as broken (close it?) when this happens. */
 static bool check_indexes(XENSTORE_RING_IDX cons, XENSTORE_RING_IDX prod)
 {
        return ((prod - cons) <= XENSTORE_RING_SIZE);
@@ -102,7 +101,8 @@ static const void *get_input_chunk(XENST
        return buf + MASK_XENSTORE_IDX(cons);
 }
 
-static int writechn(struct connection *conn, const void *data, unsigned int 
len)
+static int writechn(struct connection *conn,
+                   const void *data, unsigned int len)
 {
        uint32_t avail;
        void *dest;
@@ -113,6 +113,7 @@ static int writechn(struct connection *c
        cons = intf->rsp_cons;
        prod = intf->rsp_prod;
        mb();
+
        if (!check_indexes(cons, prod)) {
                errno = EIO;
                return -1;
@@ -174,6 +175,8 @@ static int destroy_domain(void *_domain)
 
        if (domain->interface)
                munmap(domain->interface, getpagesize());
+
+       fire_watches(NULL, "@releaseDomain", false);
 
        return 0;
 }
@@ -197,7 +200,7 @@ static void domain_cleanup(void)
                                continue;
                }
                talloc_free(domain->conn);
-               notify = 1;
+               notify = 0; /* destroy_domain() fires the watch */
        }
 
        if (notify)
@@ -246,7 +249,6 @@ static struct domain *new_domain(void *c
 {
        struct domain *domain;
        int rc;
-
 
        domain = talloc(context, struct domain);
        domain->port = 0;
@@ -361,7 +363,7 @@ void do_introduce(struct connection *con
                /* Now domain belongs to its connection. */
                talloc_steal(domain->conn, domain);
 
-               fire_watches(conn, "@introduceDomain", false);
+               fire_watches(NULL, "@introduceDomain", false);
        } else if ((domain->mfn == mfn) && (domain->conn != conn)) {
                /* Use XS_INTRODUCE for recreating the xenbus event-channel. */
                if (domain->port)
@@ -413,8 +415,6 @@ void do_release(struct connection *conn,
        }
 
        talloc_free(domain->conn);
-
-       fire_watches(conn, "@releaseDomain", false);
 
        send_ack(conn, XS_RELEASE);
 }
diff -r 37833b33ae77 -r 4492a0285bae tools/xenstore/xenstored_watch.c
--- a/tools/xenstore/xenstored_watch.c  Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xenstore/xenstored_watch.c  Fri Jul 27 08:15:16 2007 -0600
@@ -73,11 +73,10 @@ static void add_event(struct connection 
        data = talloc_array(watch, char, len);
        strcpy(data, name);
        strcpy(data + strlen(name) + 1, watch->token);
-        send_reply(conn, XS_WATCH_EVENT, data, len);
+       send_reply(conn, XS_WATCH_EVENT, data, len);
        talloc_free(data);
 }
 
-/* FIXME: we fail to fire on out of memory.  Should drop connections. */
 void fire_watches(struct connection *conn, const char *name, bool recurse)
 {
        struct connection *i;
@@ -130,7 +129,7 @@ void do_watch(struct connection *conn, s
        /* Check for duplicates. */
        list_for_each_entry(watch, &conn->watches, list) {
                if (streq(watch->node, vec[0]) &&
-                    streq(watch->token, vec[1])) {
+                   streq(watch->token, vec[1])) {
                        send_error(conn, EEXIST);
                        return;
                }
diff -r 37833b33ae77 -r 4492a0285bae tools/xenstore/xsls.c
--- a/tools/xenstore/xsls.c     Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xenstore/xsls.c     Fri Jul 27 08:15:16 2007 -0600
@@ -8,6 +8,7 @@
 #include <sys/ioctl.h>
 #include <termios.h>
 
+#define STRING_MAX PATH_MAX
 static int max_width = 80;
 static int desired_width = 60;
 
@@ -19,7 +20,8 @@ void print_dir(struct xs_handle *h, char
 void print_dir(struct xs_handle *h, char *path, int cur_depth, int show_perms)
 {
     char **e;
-    char newpath[512], *val;
+    char newpath[STRING_MAX], *val;
+    int newpath_len;
     int i;
     unsigned int num, len;
 
@@ -33,13 +35,26 @@ void print_dir(struct xs_handle *h, char
         unsigned int nperms;
         int linewid;
 
-        for (linewid=0; linewid<cur_depth; linewid++) putchar(' ');
+        /* Print indent and path basename */
+        for (linewid=0; linewid<cur_depth; linewid++) {
+            putchar(' ');
+        }
         linewid += printf("%.*s",
                           (int) (max_width - TAG_LEN - linewid), e[i]);
-        sprintf(newpath, "%s%s%s", path, 
+
+        /* Compose fullpath and fetch value */
+        newpath_len = snprintf(newpath, sizeof(newpath), "%s%s%s", path, 
                 path[strlen(path)-1] == '/' ? "" : "/", 
                 e[i]);
-        val = xs_read(h, XBT_NULL, newpath, &len);
+        if ( newpath_len < sizeof(newpath) ) {
+            val = xs_read(h, XBT_NULL, newpath, &len);
+        }
+        else {
+            /* Path was truncated and thus invalid */
+            val = NULL;
+        }
+
+        /* Print value */
         if (val == NULL) {
             printf(":\n");
         }
@@ -88,7 +103,7 @@ void print_dir(struct xs_handle *h, char
 
 void usage(int argc, char *argv[])
 {
-    fprintf(stderr, "Usage: %s [-p] [path]\n", argv[0]);
+    fprintf(stderr, "Usage: %s [-w] [-p] [path]\n", argv[0]);
 }
 
 int main(int argc, char *argv[])
@@ -104,11 +119,14 @@ int main(int argc, char *argv[])
     if (!ret)
         max_width = ws.ws_col - PAD;
 
-    while (0 < (c = getopt(argc, argv, "ps"))) {
+    while (0 < (c = getopt(argc, argv, "psw"))) {
         switch (c) {
+        case 'w':
+            max_width= STRING_MAX - PAD;
+            desired_width = 0;
+            break;
         case 'p':
             show_perm = 1;
-            max_width -= 16;
             break;
         case 's':
             socket = 1;
@@ -121,6 +139,11 @@ int main(int argc, char *argv[])
         }
     }
 
+    /* Adjust the width here to avoid argument order dependency */
+    if ( show_perm ) {
+        max_width -= 16;
+    }
+
     xsh = socket ? xs_daemon_open() : xs_domain_open();
     if (xsh == NULL)
         err(1, socket ? "xs_daemon_open" : "xs_domain_open");
diff -r 37833b33ae77 -r 4492a0285bae tools/xm-test/lib/XmTestLib/XenAPIDomain.py
--- a/tools/xm-test/lib/XmTestLib/XenAPIDomain.py       Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/lib/XmTestLib/XenAPIDomain.py       Fri Jul 27 08:15:16 
2007 -0600
@@ -23,6 +23,7 @@ import sys
 import sys
 from XmTestLib import *
 from types import DictType
+from acm import *
 
 
 class XenAPIConfig:
@@ -38,6 +39,9 @@ class XenAPIConfig:
                            'kernel' : 'PV_kernel',
                            'ramdisk': 'PV_ramdisk',
                            'root'   : 'PV_args'}
+        if isACMEnabled():
+            #A default so every VM can start with ACM enabled
+            self.opts["security_label"] = "ACM:xm-test:red"
 
     def setOpt(self, name, value):
         """Set an option in the config"""
diff -r 37833b33ae77 -r 4492a0285bae tools/xm-test/lib/XmTestLib/acm.py
--- a/tools/xm-test/lib/XmTestLib/acm.py        Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xm-test/lib/XmTestLib/acm.py        Fri Jul 27 08:15:16 2007 -0600
@@ -19,6 +19,9 @@
 """
 from Test import *
 from xen.util import security
+from xen.xm.main import server
+from xen.util import xsconstants
+import re
 
 try:
     from acm_config import *
@@ -32,16 +35,47 @@ def isACMEnabled():
     return security.on()
 
 
+def getSystemPolicyName():
+    s,o = traceCommand("xm getpolicy")
+    m = re.compile("Policy name[\s]*: ([A-z\-]+)").search(o)
+    if m:
+        polname = m.group(1)
+        return polname
+    return ""
+
+
+def ACMLoadPolicy_XenAPI(policy='xm-test'):
+    polname = getSystemPolicyName()
+    if polname != policy:
+        # Try it, maybe it's not activated
+        traceCommand("xm setpolicy %s %s" %
+                     (xsconstants.XS_POLICY_ACM, policy))
+        polname = getSystemPolicyName()
+        if polname != policy:
+            FAIL("Need to have a system with no or policy '%s' active, "
+                 "not %s" % (policy,polname))
+        else:
+            s, o = traceCommand("xm activatepolicy --load")
+    else:
+        s, o = traceCommand("xm activatepolicy --load")
+        if not re.search("Successfully", o):
+            FAIL("Could not set the policy '%s'." % policy)
+
+
 def ACMLoadPolicy(policy='xm-test'):
-    s, o = traceCommand("xm makepolicy %s" % (policy))
-    if s != 0:
-        FAIL("Need to be able to do 'xm makepolicy %s' but could not" %
-             (policy))
-    s, o = traceCommand("xm loadpolicy %s" % (policy))
-    if s != 0:
-        FAIL("Could not load the required policy '%s'.\n"
-             "Start the system without any policy.\n%s" %
-             (policy, o))
+    from xen.xm import main
+    if main.serverType == main.SERVER_XEN_API:
+        ACMLoadPolicy_XenAPI()
+    else:
+        s, o = traceCommand("xm makepolicy %s" % (policy))
+        if s != 0:
+            FAIL("Need to be able to do 'xm makepolicy %s' but could not" %
+                 (policy))
+        s, o = traceCommand("xm loadpolicy %s" % (policy))
+        if s != 0:
+            FAIL("Could not load the required policy '%s'.\n"
+                 "Start the system without any policy.\n%s" %
+                 (policy, o))
 
 def ACMPrepareSystem(resources):
     if isACMEnabled():
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/security-acm/01_security-acm_basic.py
--- a/tools/xm-test/tests/security-acm/01_security-acm_basic.py Thu Jul 26 
14:35:01 2007 -0600
+++ b/tools/xm-test/tests/security-acm/01_security-acm_basic.py Fri Jul 27 
08:15:16 2007 -0600
@@ -15,6 +15,7 @@
 
 from XmTestLib import *
 from xen.util import security
+from xen.util import xsconstants
 import commands
 import os
 import re
@@ -28,7 +29,7 @@ if not isACMEnabled():
     SKIP("Not running this test since ACM not enabled.")
 
 status, output = traceCommand("xm makepolicy %s" % (testpolicy))
-if status != 0 or output != "":
+if status != 0:
     FAIL("'xm makepolicy' failed with status %d and output\n%s" %
          (status,output));
 
@@ -47,7 +48,7 @@ status, output = traceCommand("xm addlab
 status, output = traceCommand("xm addlabel %s dom %s %s" %
                               (testlabel, vmconfigfile, testpolicy))
 if status != 0:
-    FAIL("'xm addlabel' failed with status %d.\n" % status)
+    FAIL("(1) 'xm addlabel' failed with status %d.\n" % status)
 
 status, output = traceCommand("xm getlabel dom %s" %
                               (vmconfigfile))
@@ -55,8 +56,9 @@ if status != 0:
 if status != 0:
     FAIL("'xm getlabel' failed with status %d, output:\n%s" %
          (status, output))
-if output != "policy=%s,label=%s" % (testpolicy,testlabel):
-    FAIL("Received unexpected output from 'xm getlabel': \n%s" %
+if output != "policytype=%s,policy=%s,label=%s" % \
+             (xsconstants.ACM_POLICY_ID, testpolicy, testlabel):
+    FAIL("(1) Received unexpected output from 'xm getlabel dom': \n%s" %
          (output))
 
 
@@ -74,30 +76,34 @@ status, output = traceCommand("xm getlab
                               (vmconfigfile))
 
 if output != "Error: 'Domain not labeled'":
-    FAIL("Received unexpected output from 'xm getlabel': \n%s" %
+    FAIL("(2) Received unexpected output from 'xm getlabel dom': \n%s" %
          (output))
 
 #Whatever label the resource might have, remove it
 status, output = traceCommand("xm rmlabel res %s" %
                               (testresource))
+if status != 0:
+    FAIL("'xm rmlabel' on resource failed with status %d.\n" % status)
 
 status, output = traceCommand("xm addlabel %s res %s %s" %
                               (testlabel, testresource, testpolicy))
 if status != 0:
-    FAIL("'xm addlabel' on resource failed with status %d.\n" % status)
+    FAIL("(2) 'xm addlabel' on resource failed with status %d.\n" % status)
 
 status, output = traceCommand("xm getlabel res %s" % (testresource))
 
 if status != 0:
     FAIL("'xm getlabel' on resource failed with status %d, output:\n%s" %
          (status, output))
-if output != "policy=%s,label=%s" % (testpolicy,testlabel):
-    FAIL("Received unexpected output from 'xm getlabel': \n%s" %
+if output != "%s:%s:%s" % (xsconstants.ACM_POLICY_ID,\
+                           testpolicy,testlabel):
+    FAIL("Received unexpected output from 'xm getlabel res': \n%s" %
          (output))
 
 status, output = traceCommand("xm resources")
 
 if status != 0:
+    print "status = %s" % str(status)
     FAIL("'xm resources' did not run properly")
 if not re.search(security.unify_resname(testresource), output):
     FAIL("'xm resources' did not show the tested resource '%s'." %
@@ -117,5 +123,5 @@ status, output = traceCommand("xm getlab
                               (testresource))
 
 if output != "Error: 'Resource not labeled'":
-    FAIL("Received unexpected output from 'xm getlabel': \n%s" %
+    FAIL("Received unexpected output from 'xm getlabel res': \n%s" %
          (output))
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/security-acm/07_security-acm_pol_update.py
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/xm-test/tests/security-acm/07_security-acm_pol_update.py    Fri Jul 
27 08:15:16 2007 -0600
@@ -0,0 +1,303 @@
+#!/usr/bin/python
+
+# Copyright (C) International Business Machines Corp., 2006
+# Author: Stefan Berger <stefanb@xxxxxxxxxx>
+
+# Test to exercise the xspolicy class
+
+from XmTestLib import xapi
+from XmTestLib.XenAPIDomain import XmTestAPIDomain
+from XmTestLib import *
+from xen.xend import XendAPIConstants
+from xen.util import acmpolicy, security, xsconstants
+from xen.util.acmpolicy import ACMPolicy
+from xen.xend.XendDomain import DOM0_UUID
+
+import commands
+import os
+import base64
+
+xm_test = {}
+xm_test['policyname'] = "xm-test"
+xm_test['date'] = "Fri Sep 29 14:44:38 2006"
+xm_test['url']  = None
+
+vm_label_red   = "%s:xm-test:red" % xsconstants.ACM_POLICY_ID
+vm_label_green = "%s:xm-test:green" % xsconstants.ACM_POLICY_ID
+vm_label_blue  = "%s:xm-test:blue" % xsconstants.ACM_POLICY_ID
+vm_label_sys   = "%s:xm-test:SystemManagement" % xsconstants.ACM_POLICY_ID
+
+vm_label_black = "%s:xm-test:black"
+
+session = xapi.connect()
+
+oldlabel = session.xenapi.VM.get_security_label(DOM0_UUID)
+
+ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
+                                               vm_label_sys,
+                                               oldlabel)
+if int(ssidref) <= 0 or int(ssidref) != 0x00010001:
+    FAIL("(0) Domain-0 label for '%s' has unexpected failure: %08x" %
+         (vm_label_sys, int(ssidref)))
+print "ssidref for '%s' is 0x%08x" % (vm_label_sys, int(ssidref))
+
+
+xstype = session.xenapi.XSPolicy.get_xstype()
+if int(xstype) & xsconstants.XS_POLICY_ACM == 0:
+    SKIP("ACM not enabled/compiled in Xen")
+
+policystate = session.xenapi.XSPolicy.get_xspolicy()
+if not policystate.has_key('xs_ref'):
+    FAIL("get_xspolicy must return member 'xs_ref'")
+
+xs_ref = policystate['xs_ref']
+if xs_ref != "":
+    origpolicyxml = session.xenapi.ACMPolicy.get_xml(xs_ref)
+else:
+    origpolicyxml = ""
+
+f = open("xm-test-security_policy.xml", 'r')
+if f:
+    newpolicyxml = f.read()
+    f.close()
+else:
+    FAIL("Could not read 'xm-test' policy")
+
+try:
+    os.unlink("/boot/xm-test.bin")
+except:
+    pass
+
+policystate = session.xenapi.XSPolicy.get_xspolicy()
+
+if int(policystate['type']) == 0:
+    policystate = session.xenapi.XSPolicy.set_xspolicy(
+                          xsconstants.XS_POLICY_ACM,
+                          newpolicyxml,
+                          xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT,
+                          1)
+    if int(policystate['flags']) == -1:
+        FAIL("Could not set the new policy.")
+
+print "state of policy = %s " % policystate
+
+rc = session.xenapi.XSPolicy.activate_xspolicy(
+                          policystate['xs_ref'],
+                          xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT)
+if int(rc) != xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT:
+    FAIL("Could not activate the current policy: rc = %08x" % int(rc))
+
+if not os.path.exists("/boot/xm-test.bin"):
+    FAIL("Binary policy was not installed. Check grub config file.")
+
+policystate = session.xenapi.XSPolicy.get_xspolicy()
+
+if int(policystate['flags']) != xsconstants.XS_INST_BOOT | \
+                                xsconstants.XS_INST_LOAD:
+    FAIL("Flags (%x) are not indicating the correct state of the policy.",
+         int(policystate['flags']))
+
+policystate = session.xenapi.XSPolicy.get_xspolicy()
+xs_ref = policystate['xs_ref']
+
+newpolicyxml = None
+f = open("xm-test-new-security_policy.xml", 'r')
+if f:
+    newpolicyxml = f.read()
+    f.close()
+else:
+    FAIL("Could not read 'xm-test-new' policy")
+
+cur_acmpol = ACMPolicy(xml = policystate['repr'])
+new_acmpol = ACMPolicy(xml = newpolicyxml)
+
+new_acmpol.update_frompolicy(cur_acmpol)
+
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                          new_acmpol.toxml(),
+                          xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT,
+                          1)
+
+f = open("xm-test-security_policy.xml", 'r')
+if f:
+    newpolicyxml = f.read()
+    f.close()
+else:
+    FAIL("Could not read 'xm-test-new' policy")
+
+cur_acmpol = new_acmpol
+new_acmpol = ACMPolicy(xml = newpolicyxml)
+
+new_acmpol.update_frompolicy(cur_acmpol)
+
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                          new_acmpol.toxml(),
+                          xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT,
+                          1)
+
+dom0_lab = session.xenapi.VM.get_security_label(DOM0_UUID)
+
+ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
+                                               vm_label_sys, dom0_lab)
+if int(ssidref) <= 0 or int(ssidref) != 0x00010001:
+    FAIL("(1) Domain-0 label for '%s' has unexpected failure: %08x" %
+         (vm_label_sys, int(ssidref)))
+print "ssidref for '%s' is 0x%08x" % (vm_label_sys, int(ssidref))
+
+try:
+    ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
+                                                   vm_label_black,
+                                                   vm_label_sys)
+    FAIL("Could set label '%s', although it's not in the policy. "
+         "ssidref=%s" % (vm_label_black, ssidref))
+except:
+    pass
+
+ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
+                                               vm_label_red,
+                                               vm_label_sys)
+if int(ssidref) <= 0:
+    FAIL("(2) Domain-0 label for '%s' has unexpected failure: %08x" %
+         (vm_label_red, int(ssidref)))
+print "ssidref for '%s' is 0x%08x" % (vm_label_red, int(ssidref))
+
+label = session.xenapi.VM.get_security_label(DOM0_UUID)
+
+if label != vm_label_red:
+    FAIL("Dom0 label '%s' not as expected '%s'" % (label, vm_label_red))
+
+
+ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
+                                               vm_label_sys,
+                                               vm_label_red)
+if int(ssidref) <= 0 or int(ssidref) != 0x00010001:
+    FAIL("(3) Domain-0 label for '%s' has unexpected failure: %08x" %
+         (vm_label_sys, int(ssidref)))
+
+label = session.xenapi.VM.get_security_label(DOM0_UUID)
+
+if label != vm_label_sys:
+    FAIL("Dom0 label '%s' not as expected '%s'" % label, dom0_label)
+
+header = session.xenapi.ACMPolicy.get_header(xs_ref)
+
+if header['policyname'] != xm_test['policyname']:
+    FAIL("Name in header is '%s', expected is '%s'." %
+         (header['policyname'],xm_test['policyname']))
+if header['date'] != xm_test['date']:
+    FAIL("Date in header is '%s', expected is '%s'." %
+         (header['date'],xm_test['date']))
+if header.has_key("url") and header['url' ] != xm_test['url' ]:
+    FAIL("URL  in header is '%s', expected is '%s'." %
+         (header['url' ],xm_test['url' ]))
+
+# Create another domain
+try:
+    # XmTestAPIDomain tries to establish a connection to XenD
+    domain = XmTestAPIDomain(extraConfig={ 'security_label' : vm_label_blue })
+except Exception, e:
+    SKIP("Skipping test. Error: %s" % str(e))
+
+
+vm_uuid = domain.get_uuid()
+
+res = session.xenapi.VM.get_security_label(vm_uuid)
+if res != vm_label_blue:
+    FAIL("VM has security label '%s', expected is '%s'" %
+         (res, vm_label_blue))
+
+try:
+    domain.start(noConsole=True)
+except:
+    FAIL("Could not create domain")
+
+
+# Attempt to relabel the running domain
+ssidref = session.xenapi.VM.set_security_label(vm_uuid,
+                                               vm_label_red,
+                                               vm_label_blue)
+if int(ssidref) <= 0:
+    FAIL("Could not relabel running domain to '%s'." % vm_label_red)
+
+# user domain is 'red', dom0 is current 'SystemManagement'.
+# Try to move domain-0 to 'red' first, then to 'blue'.
+
+# Moving domain-0 to 'red' should work
+ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
+                                               vm_label_red,
+                                               vm_label_sys)
+if int(ssidref) <= 0:
+    FAIL("Could not label domain-0 '%s'" % vm_label_red)
+
+# Moving the guest domain to 'blue' should not work due to conflict set
+try:
+    ssidref = session.xenapi.VM.set_security_label(vm_uuid,
+                                                   vm_label_blue,
+                                                   vm_label_red)
+    FAIL("Could label guest domain with '%s', although this is in a conflict "
+         "set. ssidref=%x" % (vm_label_blue,int(ssidref)))
+except:
+    pass
+
+label = session.xenapi.VM.get_security_label(vm_uuid)
+if label != vm_label_red:
+    FAIL("User domain has wrong label '%s', expected '%s'." %
+         (label, vm_label_red))
+
+label = session.xenapi.VM.get_security_label(DOM0_UUID)
+if label != vm_label_red:
+    FAIL("Domain-0 has wrong label '%s'; expected '%s'." %
+         (label, vm_label_red))
+
+ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
+                                               vm_label_sys,
+                                               vm_label_red)
+if int(ssidref) < 0:
+    FAIL("Could not set the domain-0 security label to '%s'." %
+         (vm_label_sys))
+
+# pause the domain and relabel it...
+session.xenapi.VM.pause(vm_uuid)
+
+label = session.xenapi.VM.get_security_label(vm_uuid)
+if label != vm_label_red:
+    FAIL("User domain has wrong label '%s', expected '%s'." %
+         (label, vm_label_red))
+
+ssidref = session.xenapi.VM.set_security_label(vm_uuid,
+                                               vm_label_blue,
+                                               vm_label_red)
+print "guest domain new label '%s'; ssidref is 0x%08x" % \
+      (vm_label_blue, int(ssidref))
+if int(ssidref) <= 0:
+    FAIL("Could not label guest domain with '%s'" % (vm_label_blue))
+
+label = session.xenapi.VM.get_security_label(vm_uuid)
+if label != vm_label_blue:
+    FAIL("User domain has wrong label '%s', expected '%s'." %
+         (label, vm_label_blue))
+
+session.xenapi.VM.unpause(vm_uuid)
+
+rc = session.xenapi.VM.suspend(vm_uuid)
+
+ssidref = session.xenapi.VM.set_security_label(vm_uuid,
+                                               vm_label_green,
+                                               vm_label_blue)
+print "guest domain new label '%s'; ssidref is 0x%08x" % \
+      (vm_label_green, int(ssidref))
+if int(ssidref) < 0:
+    FAIL("Could not label suspended guest domain with '%s'" % (vm_label_blue))
+
+label = session.xenapi.VM.get_security_label(vm_uuid)
+if label != vm_label_green:
+    FAIL("User domain has wrong label '%s', expected '%s'." %
+         (label, vm_label_green))
+
+
+rc = session.xenapi.VM.resume(vm_uuid, False)
+
+label = session.xenapi.VM.get_security_label(vm_uuid)
+if label != vm_label_green:
+    FAIL("User domain has wrong label '%s', expected '%s'." %
+         (label, vm_label_green))
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/security-acm/08_security-acm_xapi.py
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/xm-test/tests/security-acm/08_security-acm_xapi.py  Fri Jul 27 
08:15:16 2007 -0600
@@ -0,0 +1,354 @@
+#!/usr/bin/python
+
+# Copyright (C) International Business Machines Corp., 2007
+# Author: Stefan Berger <stefanb@xxxxxxxxxx>
+
+# VM creation test with labeled VM and labeled VDI
+
+from XmTestLib import xapi
+from XmTestLib.XenAPIDomain import XmTestAPIDomain
+from XmTestLib import *
+from xen.xend import XendAPIConstants
+from xen.util import acmpolicy, security, xsconstants
+import commands
+import os
+
+vm_label_red    = xsconstants.ACM_POLICY_ID + ":xm-test:red"
+vm_label_green  = xsconstants.ACM_POLICY_ID + ":xm-test:green"
+vdi_label_red   = xsconstants.ACM_POLICY_ID + ":xm-test:red"
+vdi_label_green = xsconstants.ACM_POLICY_ID + ":xm-test:green"
+
+vdi_file = "/dev/ram0"
+vdi_path = "phy:" + vdi_file
+
+#Note:
+# If during the suspend/resume operations 'red' instead of 'green' is
+# used, the Chinese Wall policy goes into effect and disallows the
+# suspended VM from being resumed...
+
+try:
+    # XmTestAPIDomain tries to establish a connection to XenD
+    domain = XmTestAPIDomain(extraConfig={ 'security_label' : vm_label_red })
+except Exception, e:
+    SKIP("Skipping test. Error: %s" % str(e))
+
+vm_uuid = domain.get_uuid()
+
+session = xapi.connect()
+xstype = session.xenapi.XSPolicy.get_xstype()
+if int(xstype) & xsconstants.XS_POLICY_ACM == 0:
+    SKIP("ACM not enabled/compiled in Xen")
+
+f = open("xm-test-security_policy.xml", 'r')
+if f:
+    newpolicyxml = f.read()
+    f.close()
+else:
+    FAIL("Could not read 'xm-test' policy")
+
+policystate = session.xenapi.XSPolicy.get_xspolicy()
+if int(policystate['type']) == 0:
+    policystate = session.xenapi.XSPolicy.set_xspolicy(
+                         xsconstants.XS_POLICY_ACM,
+                         newpolicyxml,
+                         xsconstants.XS_INST_BOOT | xsconstants.XS_INST_LOAD,
+                         True)
+    if int(policystate['flags']) == -1:
+        FAIL("Could not set the new policy.")
+
+policystate = session.xenapi.XSPolicy.get_xspolicy()
+print "policystate = %s" % policystate
+acm_ref = policystate['xs_ref']
+
+
+#
+# Some tests with labeling of resources
+#
+labels = session.xenapi.XSPolicy.get_labeled_resources()
+print "labeled resources are:\n%s" % labels
+
+oldlabel = session.xenapi.XSPolicy.get_resource_label("phy:/dev/ram0")
+
+rc  = session.xenapi.XSPolicy.set_resource_label("phy:/dev/ram0", "",
+                                                 oldlabel)
+
+rc  = session.xenapi.XSPolicy.set_resource_label("phy:/dev/ram0",
+                                                 vdi_label_green,
+                                                 "")
+
+res = session.xenapi.XSPolicy.get_resource_label("phy:/dev/ram0")
+if res != vdi_label_green:
+    FAIL("(1) get_resource_label returned unexpected result %s, wanted %s" %
+         (res, vdi_label_green))
+
+
+#
+# Some test with labeling of VMs
+#
+
+res = session.xenapi.VM.get_security_label(vm_uuid)
+
+if res != vm_label_red:
+    FAIL("VM.get_security_label returned wrong security label '%s'." % res)
+
+res = session.xenapi.VM.set_security_label(vm_uuid, vm_label_green,
+                                                    vm_label_red)
+
+res = session.xenapi.VM.get_security_label(vm_uuid)
+if res != vm_label_green:
+     FAIL("VM does not show expected label '%s' but '%s'." %
+          (vm_label_green, res))
+
+res = session.xenapi.VM.set_security_label(vm_uuid, "", vm_label_green)
+if int(res) != 0:
+    FAIL("Should be able to unlabel the domain while it's halted.")
+
+res = session.xenapi.VM.get_security_label(vm_uuid)
+if res != "":
+    FAIL("Unexpected VM security label after removal: %s" % res)
+
+res = session.xenapi.VM.set_security_label(vm_uuid, vm_label_red, res)
+if int(res) != 0:
+    FAIL("Could not label the VM to '%s'" % vm_label_red)
+
+res = session.xenapi.VM.get_security_label(vm_uuid)
+if res != vm_label_red:
+    FAIL("VM has wrong label '%s', expected '%s'." % (res, vm_label_red))
+
+sr_uuid = session.xenapi.SR.get_by_name_label("Local")
+if len(sr_uuid) == 0:
+    FAIL("Could not get a handle on SR 'Local'")
+
+
+vdi_rec = { 'name_label'  : "My disk",
+            'SR'          : sr_uuid[0],
+            'virtual_size': 0,
+            'sector_size' : 512,
+            'parent'      : '',
+            'SR_name'     : 'Local',
+            'type'        : 'system',
+            'shareable'   : False,
+            'read-only'   : False,
+            'other_config': {'location': vdi_path}
+}
+
+vdi_ref = session.xenapi.VDI.create(vdi_rec)
+
+res = session.xenapi.VDI.get_name_label(vdi_ref)
+if res != vdi_rec['name_label']:
+    print "Destroying VDI now"
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("VDI_get_name_label return wrong information")
+
+res = session.xenapi.VDI.get_record(vdi_ref)
+print "vdi_record : %s" % res
+
+oldlabel = session.xenapi.XSPolicy.get_resource_label(vdi_path)
+
+#Remove label from VDI device
+rc  = session.xenapi.XSPolicy.set_resource_label(vdi_path,
+                                                 "",
+                                                 oldlabel)
+
+
+# Attach a VBD to the VM
+
+vbd_rec = { 'VM'      : vm_uuid,
+            'VDI'     : vdi_ref,
+            'device'  : "xvda1",
+            'mode'    : 1,
+            'bootable': 0,
+}
+
+vbd_ref = session.xenapi.VBD.create(vbd_rec)
+
+res = session.xenapi.VBD.get_record(vbd_ref)
+
+try:
+    domain.start(noConsole=True)
+    # Should not get here.
+    print "Destroying VDI now"
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Could start VM with a VBD that it is not allowed to access.")
+except:
+    pass
+    print "Could not create domain -- that's good"
+
+
+#
+# Label the VDI now
+#
+
+rc    = session.xenapi.VDI.set_security_label(vdi_ref, vdi_label_red, "")
+if int(rc) != 0:
+    FAIL("Could not set the VDI label to '%s'" % vdi_label_red)
+
+label = session.xenapi.VDI.get_security_label(vdi_ref)
+if label != vdi_label_red:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Unexpected label '%s' on VDI, wanted '%s'" %
+         (label, vdi_label_red))
+
+rc    = session.xenapi.VDI.set_security_label(vdi_ref, "", label)
+if int(rc) != 0:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Should be able to unlabel VDI.")
+
+rc    = session.xenapi.VDI.set_security_label(vdi_ref, vdi_label_red, "")
+if int(rc) != 0:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Should be able to label VDI with label '%s'" % vid_label_red)
+
+res   = session.xenapi.XSPolicy.get_resource_label(vdi_path)
+if res != vdi_label_red:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("(2) get_resource_label on %s returned unexpected result %s, wanted 
'%s'" %
+         (vdi_path, res, vdi_label_red))
+
+res = session.xenapi.VDI.get_security_label(vdi_ref)
+if res != vdi_label_red:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("get_security_label returned unexpected result %s, wanted '%s'" %
+         (res, vdi_label_red))
+
+domain.start(noConsole=True)
+
+console = domain.getConsole()
+
+domName = domain.getName()
+
+try:
+    run = console.runCmd("cat /proc/interrupts")
+except ConsoleError, e:
+    saveLog(console.getHistory())
+    FAIL("Could not access proc-filesystem")
+
+# Try to relabel while VM is running
+try:
+    res = session.xenapi.VM.set_security_label(vm_uuid, vm_label_green,
+                                               vm_label_red)
+except:
+    pass
+
+lab = session.xenapi.VM.get_security_label(vm_uuid)
+if lab == vm_label_green:
+    FAIL("Should not be able to reset the security label while running."
+         "tried to set to %s, got %s, old: %s" %(vm_label_green, lab,
+         vm_label_red))
+
+
+#
+# Suspend the domain and relabel it
+#
+
+try:
+    status, output = traceCommand("xm suspend %s" % domName,
+                                  timeout=30)
+except TimeoutError, e:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Failure from suspending VM: %s." % str(e))
+
+# Try to relabel while VM is suspended -- this should work
+
+rc  = session.xenapi.VM.set_security_label(vm_uuid, vm_label_green,
+                                           vm_label_red)
+if int(rc) != 0:
+    FAIL("VM security label could not be set to %s" % vm_label_green)
+
+res = session.xenapi.VM.get_security_label(vm_uuid)
+if res != vm_label_green:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("VM (suspended) has label '%s', expected '%s'." %
+         (res, vm_label_green))
+
+status, output = traceCommand("xm list")
+
+#Try to resume now -- should fail due to denied access to block device
+try:
+    status, output = traceCommand("xm resume %s" % domName,
+                                  timeout=30)
+    if status == 0:
+        session.xenapi.VDI.destroy(vdi_ref)
+        FAIL("Could resume re-labeled VM: %s" % output)
+except Exception, e:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("1. Error resuming the VM: %s." % str(e))
+
+# Relabel VM so it would resume
+res = session.xenapi.VM.set_security_label(vm_uuid, vm_label_red,
+                                           vm_label_green)
+if int(res) != 0:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Could not relabel VM to have it resume.")
+
+res = session.xenapi.VM.get_security_label(vm_uuid)
+if res != vm_label_red:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("VM (suspended) has label '%s', expected '%s'." %
+         (res, vm_label_red))
+
+
+# Relabel the resource so VM should not resume
+try:
+    session.xenapi.XSPolicy.set_resource_label(vdi_path,
+                                               vdi_label_green,
+                                               "")
+except Exception, e:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Could not label the VDI to '%s': %x" %
+         (vdi_label_green, int(rc)))
+
+#Try to resume now -- should fail due to denied access to block device
+try:
+    status, output = traceCommand("xm resume %s" % domName,
+                                  timeout=30)
+    if status == 0:
+        session.xenapi.VDI.destroy(vdi_ref)
+        FAIL("Could resume re-labeled VM: %s" % output)
+except Exception, e:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("2. Error resuming the VM: %s." % str(e))
+
+
+status, output = traceCommand("xm list")
+
+# Relabel the resource so VM can resume
+try:
+    session.xenapi.XSPolicy.set_resource_label(vdi_path,
+                                               vdi_label_red,
+                                               vdi_label_green)
+except Exception, e:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Could not label the resource to '%s'" % vid_label_red)
+
+res = session.xenapi.XSPolicy.get_resource_label(vdi_path)
+if res != vdi_label_red:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("'%s' has label '%s', expected '%s'." %
+         (vdi_path, res, vdi_label_red))
+
+#Try to resume now -- should work
+try:
+    status, output = traceCommand("xm resume %s" % domName,
+                                  timeout=30)
+    if status != 0:
+        session.xenapi.VDI.destroy(vdi_ref)
+        FAIL("Could not resume re-labeled VM: %s" % output)
+except Exception, e:
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("3. Error resuming the VM: %s." % str(e))
+
+
+status, output = traceCommand("xm list")
+
+console = domain.getConsole()
+
+try:
+    run = console.runCmd("cat /proc/interrupts")
+except ConsoleError, e:
+    saveLog(console.getHistory())
+    session.xenapi.VDI.destroy(vdi_ref)
+    FAIL("Could not access proc-filesystem")
+
+domain.stop()
+domain.destroy()
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/security-acm/09_security-acm_pol_update.py
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/xm-test/tests/security-acm/09_security-acm_pol_update.py    Fri Jul 
27 08:15:16 2007 -0600
@@ -0,0 +1,427 @@
+#!/usr/bin/python
+
+# Copyright (C) International Business Machines Corp., 2007
+# Author: Stefan Berger <stefanb@xxxxxxxxxx>
+
+# Test to exercise the xspolicy and acmpolicy classes
+
+from XmTestLib import xapi
+from XmTestLib.XenAPIDomain import XmTestAPIDomain
+from XmTestLib import *
+from xen.xend import XendAPIConstants
+from xen.util import security, xsconstants
+from xen.util.acmpolicy import ACMPolicy
+from xen.xend.XendDomain import DOM0_UUID
+import base64
+import struct
+import time
+
+def typestoxml(types):
+    res = ""
+    for t in types:
+        res += "<Type>" + t + "</Type>\n"
+    return res
+
+def cfstoxml(cfss):
+    res = ""
+    for cfs in cfss:
+        res += "<Conflict name=\"" + cfs['name'] + "\">\n" + \
+               typestoxml(cfs['chws']) + \
+               "</Conflict>\n"
+    return res
+
+def vmlabelstoxml(vmlabels, vmfrommap):
+    res = ""
+    for vmlabel in vmlabels:
+        res += "<VirtualMachineLabel>\n"
+        if vmlabel['name'] in vmfrommap:
+            res += "<Name from=\""+ vmfrommap[vmlabel['name']] +"\">"
+        else:
+            res += "<Name>"
+        res += vmlabel['name'] + "</Name>\n"
+        res += "<SimpleTypeEnforcementTypes>\n" + \
+                  typestoxml(vmlabel['stes']) + \
+               "</SimpleTypeEnforcementTypes>\n"
+        if vmlabel.has_key('chws'):
+            res += "<ChineseWallTypes>\n" + \
+                     typestoxml(vmlabel['chws']) + \
+                   "</ChineseWallTypes>\n"
+        res += "</VirtualMachineLabel>\n"
+    return res
+
+
+def reslabelstoxml(reslabels, resfrommap):
+    res = ""
+    for reslabel in reslabels:
+        res += "<ResourceLabel>\n"
+        if resfrommap.has_key(reslabel['name']):
+            res += "<Name from=\""+ resfrommap[reslabel['name']] +"\">"
+        else:
+            res += "<Name>"
+        res += reslabel['name'] + "</Name>\n"
+        res += "<SimpleTypeEnforcementTypes>\n" + \
+                  typestoxml(reslabel['stes']) + \
+               "</SimpleTypeEnforcementTypes>\n"
+        res += "</ResourceLabel>\n"
+    return res
+
+def create_xml_policy(hdr, stes, chws,
+                      vmlabels, vmfrommap, bootstrap,
+                      reslabels, resfrommap,
+                      cfss):
+    hdr_xml ="<PolicyHeader>\n" + \
+             "  <PolicyName>" + hdr['name'] + "</PolicyName>\n" + \
+             "  <Version>"    + hdr['version'] + "</Version>\n" + \
+             "  <FromPolicy>\n" + \
+             "    <PolicyName>" + hdr['oldname'] + "</PolicyName>\n" + \
+             "    <Version>"    + hdr['oldversion'] + "</Version>\n" + \
+             "  </FromPolicy>\n" + \
+               "</PolicyHeader>\n"
+
+    stes_xml = "<SimpleTypeEnforcement>\n" + \
+               "  <SimpleTypeEnforcementTypes>\n" + \
+                typestoxml(stes) + \
+               "  </SimpleTypeEnforcementTypes>\n" + \
+               "</SimpleTypeEnforcement>\n"
+
+    chws_xml = "<ChineseWall>\n" + \
+               "  <ChineseWallTypes>\n" + \
+               typestoxml(chws) + \
+               "  </ChineseWallTypes>\n" + \
+               "  <ConflictSets>\n" + \
+               cfstoxml(cfss) + \
+               "  </ConflictSets>\n" + \
+               "</ChineseWall>\n"
+
+    subjlabel_xml = "<SubjectLabels bootstrap=\""+ bootstrap +"\">\n" + \
+                     vmlabelstoxml(vmlabels, vmfrommap) + \
+                    "</SubjectLabels>\n"
+    objlabel_xml  = "<ObjectLabels>\n" + \
+                      reslabelstoxml(reslabels, resfrommap) + \
+                    "</ObjectLabels>\n"
+
+    policyxml = "<?xml version=\"1.0\" ?>\n" + \
+                "<SecurityPolicyDefinition xmlns=\"http://www.ibm.com\"; 
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"; 
xsi:schemaLocation=\"http://www.ibm.com ../../security_policy.xsd \">\n" + \
+                hdr_xml + \
+                stes_xml + \
+                chws_xml + \
+                "<SecurityLabelTemplate>\n" + \
+                  subjlabel_xml + \
+                  objlabel_xml + \
+                "</SecurityLabelTemplate>\n" + \
+                "</SecurityPolicyDefinition>\n"
+    return policyxml
+
+
+def update_hdr(hdr):
+    """ Update the version information in the header """
+    hdr['oldversion'] = hdr['version']
+    hdr['oldname']    = hdr['name']
+    vers = hdr['version']
+    tmp = vers.split('.')
+    if len(tmp) == 1:
+        rev = 1
+    else:
+        rev = int(tmp[1]) + 1
+    hdr['version'] = "%s.%s" % (tmp[0],rev)
+    return hdr
+
+session = xapi.connect()
+
+policystate = session.xenapi.XSPolicy.get_xspolicy()
+
+if policystate['repr'] != "":
+    print "%s" % policystate['repr']
+    try:
+        acmpol = ACMPolicy(xml=policystate['repr'])
+    except Exception, e:
+        FAIL("Failure from creating ACMPolicy object: %s" % str(e))
+    oldname = acmpol.policy_dom_get_hdr_item("PolicyName")
+    oldvers = acmpol.policy_dom_get_hdr_item("Version")
+    tmp = oldvers.split(".")
+    if len(tmp) == 1:
+        rev = 1
+    else:
+        rev = int(tmp[1]) + 1
+    newvers = "%s.%s" % (tmp[0], str(rev))
+    print "old name/version = %s/%s" % (oldname, oldvers)
+else:
+    oldname = None
+    oldvers = None
+    newvers = "1.0"
+
+# Initialize the header of the policy
+hdr = {}
+hdr['name'] = "xm-test"
+hdr['version'] = newvers
+
+if oldname:
+    hdr['oldname']    = oldname
+    if oldvers and oldvers != "":
+        hdr['oldversion'] = oldvers
+
+stes = [ "SystemManagement", "red", "green", "blue" ]
+
+chws = [ "SystemManagement", "red", "green", "blue" ]
+
+bootstrap = "SystemManagement"
+
+vm_sysmgt = { 'name' : bootstrap,
+              'stes' : stes,
+              'chws' : [ "SystemManagement" ] }
+
+vm_red   = { 'name' : "red" ,
+             'stes' : ["red"] ,
+             'chws' : ["red"] }
+
+vm_green = { 'name' : "green" ,
+             'stes' : ["green"] ,
+             'chws' : ["green"] }
+
+vm_blue  = { 'name' : "blue" ,
+             'stes' : ["blue"] ,
+             'chws' : ["blue"] }
+
+res_red   = { 'name' : "red" ,
+              'stes' : ["red"] }
+
+res_green = { 'name' : "green" ,
+              'stes' : ["green"] }
+
+res_blue  = { 'name' : "blue" ,
+              'stes' : ["blue"] }
+
+cfs_1 = { 'name' : "CFS1",
+          'chws' : [ "red" , "blue" ] }
+
+vmlabels = [ vm_sysmgt, vm_red, vm_green, vm_blue ]
+vmfrommap = {}
+reslabels = [ res_red, res_green, res_blue ]
+resfrommap = {}
+cfss = [ cfs_1 ]
+
+vm_label_red    = xsconstants.ACM_POLICY_ID + ":xm-test:red"
+vm_label_green  = xsconstants.ACM_POLICY_ID + ":xm-test:green"
+vm_label_blue   = xsconstants.ACM_POLICY_ID + ":xm-test:blue"
+
+xml = create_xml_policy(hdr, stes, chws,
+                        vmlabels, vmfrommap, bootstrap,
+                        reslabels, resfrommap,
+                        cfss)
+
+xml_good = xml
+
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                                                   xml,
+                                                   xsconstants.XS_INST_LOAD,
+                                                   True)
+
+print "\n\npolicystate = %s" % policystate
+
+policystate = session.xenapi.XSPolicy.get_xspolicy()
+
+#
+# Create two non-conflicting domains and start them
+#
+try:
+    # XmTestAPIDomain tries to establish a connection to XenD
+    domain1 = XmTestAPIDomain(extraConfig={ 'security_label' : vm_label_red })
+except Exception, e:
+    SKIP("Skipping test. Error: %s" % str(e))
+
+
+vm1_uuid = domain1.get_uuid()
+
+try:
+    domain1.start(noConsole=True)
+except:
+    FAIL("Could not start domain1")
+
+print "Domain 1 started"
+
+try:
+    # XmTestAPIDomain tries to establish a connection to XenD
+    domain2 = XmTestAPIDomain(extraConfig={'security_label': vm_label_green })
+except Exception, e:
+    SKIP("Skipping test. Error: %s" % str(e))
+
+vm2_uuid = domain2.get_uuid()
+
+try:
+    domain2.start(noConsole=True)
+except:
+    FAIL("Could not start domain1")
+
+
+print "Domain 2 started"
+
+# Try a policy that would put the two domains into conflict
+cfs_2 = { 'name' : "CFS1",
+          'chws' : [ "red" , "green" ] }
+cfss = [ cfs_2 ]
+
+hdr = update_hdr(hdr)
+xml = create_xml_policy(hdr, stes, chws,
+                        vmlabels, vmfrommap, bootstrap,
+                        reslabels, resfrommap,
+                        cfss)
+
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                                                   xml,
+                                                   xsconstants.XS_INST_LOAD,
+                                                   True)
+
+print "policystate %s" % policystate
+
+if int(policystate['xserr']) == 0:
+    FAIL("(1) Should not have been able to set this policy.")
+
+if len(policystate['errors']) == 0:
+    FAIL("Hypervisor should have reported errros.")
+
+errors = base64.b64decode(policystate['errors'])
+
+print "Length of errors: %d" % len(errors)
+a,b = struct.unpack("!ii",errors)
+
+print "%08x , %08x" % (a,b)
+
+#
+# Create a faulty policy with 'red' STE missing
+#
+
+cfss = [ cfs_1 ]
+stes = [ "SystemManagement", "green", "blue" ]
+
+xml = create_xml_policy(hdr, stes, chws,
+                        vmlabels, vmfrommap, bootstrap,
+                        reslabels, resfrommap,
+                        cfss)
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                                                   xml,
+                                                   xsconstants.XS_INST_LOAD,
+                                                   True)
+
+print "Result from setting faulty(!) policy with STE 'red' missing:"
+print "policystate %s" % policystate
+
+if int(policystate['xserr']) == 0:
+    FAIL("(2) Should not have been able to set this policy.")
+
+#
+# Create a policy with 'red' VMLabel missing -- should not work since it is
+# in use.
+#
+stes = [ "SystemManagement", "red", "green", "blue" ]
+
+vmlabels = [ vm_sysmgt, vm_green, vm_blue ]
+
+xml = create_xml_policy(hdr, stes, chws,
+                        vmlabels, vmfrommap, bootstrap,
+                        reslabels, resfrommap,
+                        cfss)
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                                                   xml,
+                                                   xsconstants.XS_INST_LOAD,
+                                                   True)
+print "Result from setting faulty(!) policy with VMlabel 'red' missing:"
+print "policystate %s" % policystate
+
+if int(policystate['xserr']) == 0:
+    FAIL("(3) Should not have been able to set this policy.")
+
+#
+# Create a policy with 'blue' VMLabel missing -- should work since it is NOT
+# in use.
+#
+vmlabels = [ vm_sysmgt, vm_red, vm_green ]
+
+xml = create_xml_policy(hdr, stes, chws,
+                        vmlabels, vmfrommap, bootstrap,
+                        reslabels, resfrommap,
+                        cfss)
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                                                   xml,
+                                                   xsconstants.XS_INST_LOAD,
+                                                   True)
+
+print "Result from setting (good) policy with VMlabel 'blue' missing:"
+print "policystate %s" % policystate
+
+if int(policystate['xserr']) != 0:
+    FAIL("(4) Should have been able to set this policy: %s" % xml)
+
+#
+# Move the green VMLabel towards blue which should put the running
+# domain with label blue into a conflict set
+#
+vmlabels = [ vm_sysmgt, vm_red, vm_blue ]
+
+vmfrommap = { "blue" : "green" }  #  new : old
+
+hdr = update_hdr(hdr)  #Needed, since last update was successful
+xml = create_xml_policy(hdr, stes, chws,
+                        vmlabels, vmfrommap, bootstrap,
+                        reslabels, resfrommap,
+                        cfss)
+
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                                                   xml,
+                                                   xsconstants.XS_INST_LOAD,
+                                                   True)
+
+print "policystate %s" % policystate
+
+if int(policystate['xserr']) == 0:
+    FAIL("(5) Should not have been able to set this policy.")
+
+#
+# Try to install a policy where a VM label has a faulty VM label name
+#
+vmfrommap = {}
+
+vm_blue_bad = { 'name' : "blue:x" ,   # ':' no allowed
+                'stes' : ["blue"],
+                'chws' : ["blue"] }
+
+vmlabels = [ vm_sysmgt, vm_red, vm_green, vm_blue_bad ]
+
+xml = create_xml_policy(hdr, stes, chws,
+                        vmlabels, vmfrommap, bootstrap,
+                        reslabels, resfrommap,
+                        cfss)
+
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                                                   xml,
+                                                   xsconstants.XS_INST_LOAD,
+                                                   True)
+
+print "policystate %s" % policystate
+
+if int(policystate['xserr']) == 0:
+    FAIL("(6) Should not have been able to set this policy.")
+
+#
+# End the test by installing the initial policy again
+#
+
+cur_version = hdr['version']
+(maj, min) = cur_version.split(".")
+cur_version = "%s.%s" % (maj, str(int(min)-1) )
+
+orig_acmpol = ACMPolicy(xml=xml_good)
+orig_acmpol.set_frompolicy_version(cur_version)
+orig_acmpol.set_policy_version(hdr['version'])
+
+policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
+                                                   orig_acmpol.toxml(),
+                                                   xsconstants.XS_INST_LOAD,
+                                                   True)
+
+if int(policystate['xserr']) != 0:
+    FAIL("(END) Should have been able to set this policy.")
+
+domain1.stop()
+domain2.stop()
+domain1.destroy()
+domain2.destroy()
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/security-acm/Makefile.am
--- a/tools/xm-test/tests/security-acm/Makefile.am      Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/security-acm/Makefile.am      Fri Jul 27 08:15:16 
2007 -0600
@@ -5,7 +5,10 @@ TESTS = 01_security-acm_basic.test \
         03_security-acm_dom_conflict.test \
         04_security-acm_dom_res.test \
         05_security-acm_dom_res_conf.test \
-        06_security-acm_dom_block_attach.test
+        06_security-acm_dom_block_attach.test \
+        07_security-acm_pol_update.test \
+        08_security-acm_xapi.test \
+        09_security-acm_pol_update.test
 
 XFAIL_TESTS =
 
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/security-acm/xm-test-new-security_policy.xml
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/xm-test/tests/security-acm/xm-test-new-security_policy.xml  Fri Jul 
27 08:15:16 2007 -0600
@@ -0,0 +1,97 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Auto-generated by ezPolicy        -->
+<SecurityPolicyDefinition xmlns="http://www.ibm.com"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
xsi:schemaLocation="http://www.ibm.com ../../security_policy.xsd ">
+    <PolicyHeader>
+        <PolicyName>xm-test</PolicyName>
+        <Date>Fri Sep 29 14:44:38 2006</Date>
+        <Version>1.1</Version>
+        <FromPolicy>
+            <PolicyName>xm-test</PolicyName>
+            <Version>1.0</Version>
+        </FromPolicy>
+    </PolicyHeader>
+
+    <SimpleTypeEnforcement>
+        <SimpleTypeEnforcementTypes>
+            <Type>SystemManagement</Type>
+            <Type>green</Type>
+            <Type>red</Type>
+        </SimpleTypeEnforcementTypes>
+    </SimpleTypeEnforcement>
+
+    <ChineseWall priority="PrimaryPolicyComponent">
+        <ChineseWallTypes>
+            <Type>SystemManagement</Type>
+            <Type>green</Type>
+            <Type>red</Type>
+        </ChineseWallTypes>
+
+        <ConflictSets>
+            <Conflict name="RER">
+                <Type>green</Type>
+                <Type>red</Type>
+            </Conflict>
+       </ConflictSets>
+    </ChineseWall>
+
+    <SecurityLabelTemplate>
+        <SubjectLabels bootstrap="SystemManagement">
+            <VirtualMachineLabel>
+                <Name>SystemManagement</Name>
+                <SimpleTypeEnforcementTypes>
+                    <Type>SystemManagement</Type>
+                    <Type>green</Type>
+                    <Type>red</Type>
+                </SimpleTypeEnforcementTypes>
+                <ChineseWallTypes>
+                    <Type>SystemManagement</Type>
+                </ChineseWallTypes>
+            </VirtualMachineLabel>
+
+            <VirtualMachineLabel>
+                <Name>green</Name>
+                <SimpleTypeEnforcementTypes>
+                    <Type>green</Type>
+                </SimpleTypeEnforcementTypes>
+                <ChineseWallTypes>
+                    <Type>green</Type>
+                </ChineseWallTypes>
+            </VirtualMachineLabel>
+
+            <VirtualMachineLabel>
+                <Name>red</Name>
+                <SimpleTypeEnforcementTypes>
+                    <Type>red</Type>
+                </SimpleTypeEnforcementTypes>
+                <ChineseWallTypes>
+                    <Type>red</Type>
+                </ChineseWallTypes>
+            </VirtualMachineLabel>
+
+        </SubjectLabels>
+
+        <ObjectLabels>
+            <ResourceLabel>
+                <Name>SystemManagement</Name>
+                <SimpleTypeEnforcementTypes>
+                    <Type>SystemManagement</Type>
+                </SimpleTypeEnforcementTypes>
+            </ResourceLabel>
+
+            <ResourceLabel>
+                <Name>green</Name>
+                <SimpleTypeEnforcementTypes>
+                    <Type>green</Type>
+                </SimpleTypeEnforcementTypes>
+            </ResourceLabel>
+
+            <ResourceLabel>
+                <Name>red</Name>
+                <SimpleTypeEnforcementTypes>
+                    <Type>red</Type>
+                </SimpleTypeEnforcementTypes>
+            </ResourceLabel>
+
+        </ObjectLabels>
+    </SecurityLabelTemplate>
+</SecurityPolicyDefinition>
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/vtpm/01_vtpm-list_pos.py
--- a/tools/xm-test/tests/vtpm/01_vtpm-list_pos.py      Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/vtpm/01_vtpm-list_pos.py      Fri Jul 27 08:15:16 
2007 -0600
@@ -11,6 +11,7 @@ from vtpm_utils import *
 from vtpm_utils import *
 import commands
 import os
+import atexit
 
 config = {"vtpm":"instance=1,backend=0"}
 domain = XmTestDomain(extraConfig=config)
@@ -23,18 +24,17 @@ except DomainError, e:
     vtpm_cleanup(domain.getName())
     FAIL("Unable to create domain")
 
+
 domName = domain.getName()
+
+atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
 
 status, output = traceCommand("xm vtpm-list %s" % domain.getId())
 eyecatcher = "/local/domain/0/backend/vtpm"
 where = output.find(eyecatcher)
 if status != 0:
-    vtpm_cleanup(domName)
     FAIL("xm vtpm-list returned bad status, expected 0, status is %i" % status)
 elif where < 0:
-    vtpm_cleanup(domName)
     FAIL("Fail to list virtual TPM device")
 
 domain.stop()
-
-vtpm_cleanup(domName)
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/vtpm/02_vtpm-cat_pcrs.py
--- a/tools/xm-test/tests/vtpm/02_vtpm-cat_pcrs.py      Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/vtpm/02_vtpm-cat_pcrs.py      Fri Jul 27 08:15:16 
2007 -0600
@@ -11,6 +11,7 @@ import commands
 import commands
 import os
 import os.path
+import atexit
 
 config = {"vtpm":"instance=1,backend=0"}
 domain = XmTestDomain(extraConfig=config)
@@ -21,32 +22,28 @@ except DomainError, e:
 except DomainError, e:
     if verbose:
         print e.extra
-    vtpm_cleanup(domName)
     FAIL("Unable to create domain (%s)" % domName)
+
+atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
 
 try:
     console.sendInput("input")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL(str(e))
 
 try:
     run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("No result from dumping the PCRs")
 
 if re.search("No such file",run["output"]):
-    vtpm_cleanup(domName)
     FAIL("TPM frontend support not compiled into (domU?) kernel")
 
 domain.closeConsole()
 
 domain.stop()
 
-vtpm_cleanup(domName)
-
 if not re.search("PCR-00:",run["output"]):
     FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side")
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/vtpm/03_vtpm-susp_res.py
--- a/tools/xm-test/tests/vtpm/03_vtpm-susp_res.py      Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/vtpm/03_vtpm-susp_res.py      Fri Jul 27 08:15:16 
2007 -0600
@@ -12,6 +12,7 @@ import commands
 import commands
 import os
 import os.path
+import atexit
 
 config = {"vtpm":"instance=1,backend=0"}
 domain = XmTestDomain(extraConfig=config)
@@ -23,25 +24,23 @@ except DomainError, e:
 except DomainError, e:
     if verbose:
         print e.extra
-    vtpm_cleanup(domName)
     FAIL("Unable to create domain (%s)" % domName)
+
+atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
 
 try:
     console.sendInput("input")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL(str(e))
 
 try:
     run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("No result from dumping the PCRs")
 
 if re.search("No such file",run["output"]):
-    vtpm_cleanup(domName)
     FAIL("TPM frontend support not compiled into (domU?) kernel")
 
 consoleHistory = console.getHistory()
@@ -56,12 +55,10 @@ while loop < 3:
 
     except TimeoutError, e:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     if status != 0:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL("xm save did not succeed")
 
     try:
@@ -71,32 +68,27 @@ while loop < 3:
     except TimeoutError, e:
         os.remove("%s.save" % domName)
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     os.remove("%s.save" % domName)
 
     if status != 0:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL("xm restore did not succeed")
 
     try:
         console = domain.getConsole()
     except ConsoleError, e:
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     try:
         run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
     except ConsoleError, e:
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     if not re.search("PCR-00:",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend 
side")
 
     loop += 1
@@ -105,5 +97,3 @@ domain.closeConsole()
 
 domain.stop()
 
-vtpm_cleanup(domName)
-
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/vtpm/04_vtpm-loc_migr.py
--- a/tools/xm-test/tests/vtpm/04_vtpm-loc_migr.py      Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/vtpm/04_vtpm-loc_migr.py      Fri Jul 27 08:15:16 
2007 -0600
@@ -13,6 +13,7 @@ import commands
 import commands
 import os
 import os.path
+import atexit
 
 config = {"vtpm":"instance=1,backend=0"}
 domain = XmTestDomain(extraConfig=config)
@@ -24,25 +25,23 @@ except DomainError, e:
 except DomainError, e:
     if verbose:
         print e.extra
-    vtpm_cleanup(domName)
     FAIL("Unable to create domain (%s)" % domName)
+
+atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
 
 try:
     console.sendInput("input")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL(str(e))
 
 try:
     run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("No result from dumping the PCRs")
 
 if re.search("No such file",run["output"]):
-    vtpm_cleanup(domName)
     FAIL("TPM frontend support not compiled into (domU?) kernel")
 
 consoleHistory = console.getHistory()
@@ -58,12 +57,10 @@ while loop < 3:
                                       timeout=90)
     except TimeoutError, e:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     if status != 0:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL("xm migrate did not succeed. External device migration 
activated?")
 
 
@@ -71,26 +68,22 @@ while loop < 3:
     new_domid = domid(domName)
 
     if (old_domid == new_domid):
-        vtpm_cleanup(domName)
         FAIL("xm migrate failed, domain id is still %s (loop=%d)" %
              (old_domid,loop))
 
     try:
         console = domain.getConsole()
     except ConsoleError, e:
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     try:
         run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
     except ConsoleError, e:
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("No result from dumping the PCRs")
 
     if not re.search("PCR-00:",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend 
side")
 
     loop += 1
@@ -98,5 +91,3 @@ domain.closeConsole()
 domain.closeConsole()
 
 domain.stop()
-
-vtpm_cleanup(domName)
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/vtpm/05_vtpm-loc_migr.py
--- a/tools/xm-test/tests/vtpm/05_vtpm-loc_migr.py      Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/vtpm/05_vtpm-loc_migr.py      Fri Jul 27 08:15:16 
2007 -0600
@@ -13,6 +13,7 @@ import commands
 import commands
 import os
 import os.path
+import atexit
 
 config = {"vtpm":"instance=1,backend=0"}
 domain = XmTestDomain(extraConfig=config)
@@ -24,25 +25,23 @@ except DomainError, e:
 except DomainError, e:
     if verbose:
         print e.extra
-    vtpm_cleanup(domName)
     FAIL("Unable to create domain (%s)" % domName)
+
+atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
 
 try:
     console.sendInput("input")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL(str(e))
 
 try:
     run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("No result from dumping the PCRs")
 
 if re.search("No such file",run["output"]):
-    vtpm_cleanup(domName)
     FAIL("TPM frontend support not compiled into (domU?) kernel")
 
 consoleHistory = console.getHistory()
@@ -58,12 +57,10 @@ while loop < 3:
                                       timeout=90)
     except TimeoutError, e:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     if status != 0:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL("xm migrate did not succeed. External device migration 
activated?")
 
 
@@ -71,26 +68,22 @@ while loop < 3:
     new_domid = domid(domName)
 
     if (old_domid == new_domid):
-        vtpm_cleanup(domName)
         FAIL("xm migrate failed, domain id is still %s (loop=%d)" %
              (old_domid,loop))
 
     try:
         console = domain.getConsole()
     except ConsoleError, e:
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     try:
         run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
     except ConsoleError, e:
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("No result from dumping the PCRs")
 
     if not re.search("PCR-00:",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend 
side")
 
     loop += 1
@@ -98,5 +91,3 @@ domain.closeConsole()
 domain.closeConsole()
 
 domain.stop()
-
-vtpm_cleanup(domName)
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/vtpm/06_vtpm-susp_res_pcrs.py
--- a/tools/xm-test/tests/vtpm/06_vtpm-susp_res_pcrs.py Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/vtpm/06_vtpm-susp_res_pcrs.py Fri Jul 27 08:15:16 
2007 -0600
@@ -13,6 +13,7 @@ import commands
 import commands
 import os
 import os.path
+import atexit
 
 config = {"vtpm":"instance=1,backend=0"}
 domain = XmTestDomain(extraConfig=config)
@@ -24,45 +25,40 @@ except DomainError, e:
 except DomainError, e:
     if verbose:
         print e.extra
-    vtpm_cleanup(domName)
     FAIL("Unable to create domain (%s)" % domName)
+
+atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
 
 try:
     console.sendInput("input")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL(str(e))
 
 try:
     run = console.runCmd("mknod /dev/tpm0 c 10 224")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Error while creating /dev/tpm0")
 
 try:
     run = console.runCmd("echo -ne 
\"\\x00\\xc1\\x00\\x00\\x00\\x22\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\0xf\\x10\\x11\\x12\\x13\\x14\"
 > seq; cat seq > /dev/tpm0")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Error while extending PCR 0")
 
 try:
     run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("No result from dumping the PCRs")
 
 
 if re.search("No such file",run["output"]):
-    vtpm_cleanup(domName)
     FAIL("TPM frontend support not compiled into (domU?) kernel")
 
 if not re.search("PCR-00:",run["output"]):
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side: 
\n%s" % run["output"])
 
 if not re.search("PCR-00: 1E A7 BD",run["output"]):
@@ -81,12 +77,10 @@ while loop < 3:
 
     except TimeoutError, e:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     if status != 0:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL("xm save did not succeed")
 
     try:
@@ -96,37 +90,31 @@ while loop < 3:
     except TimeoutError, e:
         os.remove("%s.save" % domName)
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     os.remove("%s.save" % domName)
 
     if status != 0:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL("xm restore did not succeed")
 
     try:
         console = domain.getConsole()
     except ConsoleError, e:
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     try:
         run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
     except ConsoleError, e:
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     if not re.search("PCR-00:",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend 
side")
 
     if not re.search("PCR-00: 1E A7 BD",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM lost PCR 0 value: \n%s" % run["output"])
 
     loop += 1
@@ -135,5 +123,3 @@ domain.closeConsole()
 
 domain.stop()
 
-vtpm_cleanup(domName)
-
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/vtpm/07_vtpm-mig_pcrs.py
--- a/tools/xm-test/tests/vtpm/07_vtpm-mig_pcrs.py      Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/vtpm/07_vtpm-mig_pcrs.py      Fri Jul 27 08:15:16 
2007 -0600
@@ -14,6 +14,7 @@ import commands
 import commands
 import os
 import os.path
+import atexit
 
 config = {"vtpm":"instance=1,backend=0"}
 domain = XmTestDomain(extraConfig=config)
@@ -25,45 +26,40 @@ except DomainError, e:
 except DomainError, e:
     if verbose:
         print e.extra
-    vtpm_cleanup(domName)
     FAIL("Unable to create domain (%s)" % domName)
+
+atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
 
 try:
     console.sendInput("input")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL(str(e))
 
 try:
     run = console.runCmd("mknod /dev/tpm0 c 10 224")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Error while creating /dev/tpm0")
 
 try:
     run = console.runCmd("echo -ne 
\"\\x00\\xc1\\x00\\x00\\x00\\x22\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\0xf\\x10\\x11\\x12\\x13\\x14\"
 > seq; cat seq > /dev/tpm0")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Error while extending PCR 0")
 
 try:
     run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("No result from dumping the PCRs")
 
 
 if re.search("No such file",run["output"]):
-    vtpm_cleanup(domName)
     FAIL("TPM frontend support not compiled into (domU?) kernel")
 
 if not re.search("PCR-00:",run["output"]):
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side: 
\n%s" % run["output"])
 
 if not re.search("PCR-00: 1E A7 BD",run["output"]):
@@ -83,12 +79,10 @@ while loop < 3:
                                       timeout=90)
     except TimeoutError, e:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     if status != 0:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL("xm migrate did not succeed. External device migration 
activated?")
 
 
@@ -96,31 +90,26 @@ while loop < 3:
     new_domid = domid(domName)
 
     if (old_domid == new_domid):
-        vtpm_cleanup(domName)
         FAIL("xm migrate failed, domain id is still %s (loop=%d)" %
              (old_domid,loop))
 
     try:
         console = domain.getConsole()
     except ConsoleError, e:
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     try:
         run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
     except ConsoleError, e:
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("No result from dumping the PCRs")
 
     if not re.search("PCR-00:",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend 
side")
 
     if not re.search("PCR-00: 1E A7 BD",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM lost PCR 0 value: \n%s" % run["output"])
 
     loop += 1
@@ -128,5 +117,3 @@ domain.closeConsole()
 domain.closeConsole()
 
 domain.stop()
-
-vtpm_cleanup(domName)
diff -r 37833b33ae77 -r 4492a0285bae 
tools/xm-test/tests/vtpm/08_vtpm-mig_pcrs.py
--- a/tools/xm-test/tests/vtpm/08_vtpm-mig_pcrs.py      Thu Jul 26 14:35:01 
2007 -0600
+++ b/tools/xm-test/tests/vtpm/08_vtpm-mig_pcrs.py      Fri Jul 27 08:15:16 
2007 -0600
@@ -14,6 +14,7 @@ import commands
 import commands
 import os
 import os.path
+import atexit
 
 config = {"vtpm":"instance=1,backend=0"}
 domain = XmTestDomain(extraConfig=config)
@@ -25,45 +26,40 @@ except DomainError, e:
 except DomainError, e:
     if verbose:
         print e.extra
-    vtpm_cleanup(domName)
     FAIL("Unable to create domain (%s)" % domName)
+
+atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
 
 try:
     console.sendInput("input")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL(str(e))
 
 try:
     run = console.runCmd("mknod /dev/tpm0 c 10 224")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Error while creating /dev/tpm0")
 
 try:
     run = console.runCmd("echo -ne 
\"\\x00\\xc1\\x00\\x00\\x00\\x22\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\0xf\\x10\\x11\\x12\\x13\\x14\"
 > seq; cat seq > /dev/tpm0")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Error while extending PCR 0")
 
 try:
     run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
 except ConsoleError, e:
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("No result from dumping the PCRs")
 
 
 if re.search("No such file",run["output"]):
-    vtpm_cleanup(domName)
     FAIL("TPM frontend support not compiled into (domU?) kernel")
 
 if not re.search("PCR-00:",run["output"]):
     saveLog(console.getHistory())
-    vtpm_cleanup(domName)
     FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side: 
\n%s" % run["output"])
 
 if not re.search("PCR-00: 1E A7 BD",run["output"]):
@@ -83,12 +79,10 @@ while loop < 3:
                                       timeout=90)
     except TimeoutError, e:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     if status != 0:
         saveLog(consoleHistory)
-        vtpm_cleanup(domName)
         FAIL("xm migrate did not succeed. External device migration 
activated?")
 
 
@@ -96,31 +90,26 @@ while loop < 3:
     new_domid = domid(domName)
 
     if (old_domid == new_domid):
-        vtpm_cleanup(domName)
         FAIL("xm migrate failed, domain id is still %s (loop=%d)" %
              (old_domid,loop))
 
     try:
         console = domain.getConsole()
     except ConsoleError, e:
-        vtpm_cleanup(domName)
         FAIL(str(e))
 
     try:
         run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
     except ConsoleError, e:
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("No result from dumping the PCRs")
 
     if not re.search("PCR-00:",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend 
side")
 
     if not re.search("PCR-00: 1E A7 BD",run["output"]):
         saveLog(console.getHistory())
-        vtpm_cleanup(domName)
         FAIL("Virtual TPM lost PCR 0 value: \n%s" % run["output"])
 
     loop += 1
@@ -128,5 +117,3 @@ domain.closeConsole()
 domain.closeConsole()
 
 domain.stop()
-
-vtpm_cleanup(domName)
diff -r 37833b33ae77 -r 4492a0285bae tools/xm-test/tests/vtpm/vtpm_utils.py
--- a/tools/xm-test/tests/vtpm/vtpm_utils.py    Thu Jul 26 14:35:01 2007 -0600
+++ b/tools/xm-test/tests/vtpm/vtpm_utils.py    Fri Jul 27 08:15:16 2007 -0600
@@ -15,4 +15,16 @@ if output == "":
          "need /dev/tpm0")
 
 def vtpm_cleanup(domName):
-    traceCommand("/etc/xen/scripts/vtpm-delete %s" % domName)
+    traceCommand("/etc/xen/scripts/vtpm-delete "
+                 "`xenstore-read /local/domain/0/backend/vtpm/%s/0/uuid`" %
+                 str(domid(domName)))
+
+def vtpm_cleanup(uuid):
+    from xen.xm import main
+    if main.serverType != main.SERVER_XEN_API:
+        traceCommand("/etc/xen/scripts/vtpm-delete %s" % uuid)
+
+def vtpm_get_uuid(domainid):
+    s, o = traceCommand("xenstore-read "
+                        "/local/domain/0/backend/vtpm/%s/0/uuid" % domainid)
+    return o
diff -r 37833b33ae77 -r 4492a0285bae 
unmodified_drivers/linux-2.6/compat-include/xen/platform-compat.h
--- a/unmodified_drivers/linux-2.6/compat-include/xen/platform-compat.h Thu Jul 
26 14:35:01 2007 -0600
+++ b/unmodified_drivers/linux-2.6/compat-include/xen/platform-compat.h Fri Jul 
27 08:15:16 2007 -0600
@@ -107,4 +107,13 @@ extern char *kasprintf(gfp_t gfp, const 
 #define __supported_pte_mask ((maddr_t)0)
 #endif
 
+#if defined(_LINUX_NETDEVICE_H) && LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18)
+#define netif_tx_lock_bh(dev) (spin_lock_bh(&(dev)->xmit_lock))
+#define netif_tx_unlock_bh(dev) (spin_unlock_bh(&(dev)->xmit_lock))
 #endif
+
+#if defined(__LINUX_SEQLOCK_H) && !defined(DEFINE_SEQLOCK)
+#define DEFINE_SEQLOCK(x) seqlock_t x = SEQLOCK_UNLOCKED
+#endif
+
+#endif
diff -r 37833b33ae77 -r 4492a0285bae 
unmodified_drivers/linux-2.6/netfront/Kbuild
--- a/unmodified_drivers/linux-2.6/netfront/Kbuild      Thu Jul 26 14:35:01 
2007 -0600
+++ b/unmodified_drivers/linux-2.6/netfront/Kbuild      Fri Jul 27 08:15:16 
2007 -0600
@@ -2,3 +2,4 @@ include $(M)/overrides.mk
 
 obj-m  = xen-vnif.o
 xen-vnif-objs  := netfront.o
+xen-vnif-objs  += accel.o
diff -r 37833b33ae77 -r 4492a0285bae xen/Makefile
--- a/xen/Makefile      Thu Jul 26 14:35:01 2007 -0600
+++ b/xen/Makefile      Fri Jul 27 08:15:16 2007 -0600
@@ -59,7 +59,6 @@ _clean: delete-unfresh-files
        $(MAKE) -f $(BASEDIR)/Rules.mk -C arch/$(TARGET_ARCH) clean
        rm -f include/asm *.o $(TARGET)* *~ core
        rm -f include/asm-*/asm-offsets.h
-       rm -f include/xen/acm_policy.h
 

_______________________________________________
Xen-changelog mailing list
Xen-changelog@xxxxxxxxxxxxxxxxxxx
http://lists.xensource.com/xen-changelog


 


Rackspace

Lists.xenproject.org is hosted with RackSpace, monitoring our
servers 24x7x365 and backed by RackSpace's Fanatical Support®.