Xen 
 
Home About Xen.org Xen Xen Summit Wiki Mailing List Bug Tracker Xen Downloads
 
   
 

xen-changelog

[Xen-changelog] [xen-unstable] Merge with ia64 xen tree.

To: xen-changelog@xxxxxxxxxxxxxxxxxxx
Subject: [Xen-changelog] [xen-unstable] Merge with ia64 xen tree.
From: Xen patchbot-unstable <patchbot-unstable@xxxxxxxxxxxxxxxxxxx>
Date: Fri, 27 Jul 2007 02:59:34 -0700
Delivery-date: Fri, 27 Jul 2007 02:57:50 -0700
Envelope-to: www-data@xxxxxxxxxxxxxxxxxx
List-help: <mailto:xen-changelog-request@lists.xensource.com?subject=help>
List-id: BK change log <xen-changelog.lists.xensource.com>
List-post: <mailto:xen-changelog@lists.xensource.com>
List-subscribe: <http://lists.xensource.com/cgi-bin/mailman/listinfo/xen-changelog>, <mailto:xen-changelog-request@lists.xensource.com?subject=subscribe>
List-unsubscribe: <http://lists.xensource.com/cgi-bin/mailman/listinfo/xen-changelog>, <mailto:xen-changelog-request@lists.xensource.com?subject=unsubscribe>
Reply-to: xen-devel@xxxxxxxxxxxxxxxxxxx
Sender: xen-changelog-bounces@xxxxxxxxxxxxxxxxxxx
# HG changeset patch
# User kfraser@xxxxxxxxxxxxxxxxxxxxx
# Date 1184230438 -3600
# Node ID d0477293897c08c7b95257f20212e8a241626dbf
# Parent  f536eb8576eeb7363212911b02fbaff4918172df
# Parent  a9103c71565e69f79458cc19a920cc17fcba9de2
Merge with ia64 xen tree.
---
 docs/xen-api/xenapi-datamodel.tex                |  477 ++++++++++++-----------
 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/ide.c                             |    3 
 tools/ioemu/target-i386-dm/exec-dm.c             |    6 
 tools/ioemu/vl.c                                 |    5 
 tools/libxc/xc_domain.c                          |   21 +
 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_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_vm.c                        |   45 ++
 tools/libxen/src/xen_xspolicy.c                  |  327 +++++++++++++++
 tools/python/xen/xend/XendDomain.py              |    8 
 tools/python/xen/xm/activatepolicy.py            |   86 ++++
 tools/python/xen/xm/addlabel.py                  |  135 ++++--
 tools/python/xen/xm/cfgbootpolicy.py             |   76 ++-
 tools/python/xen/xm/create.dtd                   |    7 
 tools/python/xen/xm/create.py                    |   22 -
 tools/python/xen/xm/getlabel.py                  |   45 +-
 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                      |   72 ++-
 tools/python/xen/xm/makepolicy.py                |   14 
 tools/python/xen/xm/resources.py                 |   33 +
 tools/python/xen/xm/rmlabel.py                   |   65 ++-
 tools/python/xen/xm/setpolicy.py                 |  117 +++++
 tools/python/xen/xm/xenapi_create.py             |   55 ++
 tools/vtpm_manager/util/hashtable_itr.c          |    8 
 tools/xenstore/xsls.c                            |   37 +
 xen/arch/ia64/linux-xen/perfmon.c                |    2 
 xen/arch/ia64/xen/oprofile/perfmon.c             |   11 
 xen/arch/x86/acpi/Makefile                       |    1 
 xen/arch/x86/acpi/power.c                        |  273 +++++++++++++
 xen/arch/x86/acpi/suspend.c                      |   85 ++++
 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                        |    8 
 xen/arch/x86/dmi_scan.c                          |    1 
 xen/arch/x86/domain.c                            |   27 +
 xen/arch/x86/e820.c                              |   71 +--
 xen/arch/x86/hvm/hvm.c                           |    3 
 xen/arch/x86/hvm/svm/svm.c                       |    7 
 xen/arch/x86/hvm/vlapic.c                        |    9 
 xen/arch/x86/hvm/vmx/vmcs.c                      |  178 +++++---
 xen/arch/x86/hvm/vmx/vmx.c                       |   20 
 xen/arch/x86/i8259.c                             |    3 
 xen/arch/x86/io_apic.c                           |    3 
 xen/arch/x86/irq.c                               |   33 +
 xen/arch/x86/nmi.c                               |    2 
 xen/arch/x86/oprofile/nmi_int.c                  |   83 +---
 xen/arch/x86/platform_hypercall.c                |   17 
 xen/arch/x86/smpboot.c                           |  336 +++++++++++++++-
 xen/arch/x86/x86_32/traps.c                      |    2 
 xen/arch/x86/x86_64/traps.c                      |    2 
 xen/common/page_alloc.c                          |   20 
 xen/common/sysctl.c                              |   14 
 xen/common/xenoprof.c                            |   52 +-
 xen/drivers/char/ns16550.c                       |    4 
 xen/drivers/char/serial.c                        |    4 
 xen/include/asm-ia64/xenoprof.h                  |    2 
 xen/include/asm-x86/acpi.h                       |    8 
 xen/include/asm-x86/config.h                     |   10 
 xen/include/asm-x86/desc.h                       |    5 
 xen/include/asm-x86/hvm/hvm.h                    |   20 
 xen/include/asm-x86/hvm/vmx/vmcs.h               |    3 
 xen/include/asm-x86/smp.h                        |   13 
 xen/include/asm-x86/system.h                     |    2 
 xen/include/asm-x86/xenoprof.h                   |    4 
 xen/include/public/platform.h                    |   27 +
 xen/include/public/sysctl.h                      |   13 
 xen/include/xen/irq.h                            |   10 
 xen/include/xen/mm.h                             |    2 
 xen/include/xen/xenoprof.h                       |    2 
 85 files changed, 3842 insertions(+), 704 deletions(-)

diff -r f536eb8576ee -r d0477293897c docs/xen-api/xenapi-datamodel.tex
--- a/docs/xen-api/xenapi-datamodel.tex Wed Jul 11 11:32:30 2007 -0600
+++ b/docs/xen-api/xenapi-datamodel.tex Thu Jul 12 09:53:58 2007 +0100
@@ -225,6 +225,249 @@ 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}
 
 \newpage
 \section{Class: session}
@@ -275,6 +518,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}
@@ -7100,7 +7348,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 +7382,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}
@@ -14192,224 +14444,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 f536eb8576ee -r d0477293897c tools/firmware/hvmloader/acpi/dsdt.asl
--- a/tools/firmware/hvmloader/acpi/dsdt.asl    Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/firmware/hvmloader/acpi/dsdt.asl    Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/firmware/hvmloader/acpi/dsdt.c
--- a/tools/firmware/hvmloader/acpi/dsdt.c      Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/firmware/hvmloader/acpi/dsdt.c      Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/firmware/hvmloader/config.h
--- a/tools/firmware/hvmloader/config.h Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/firmware/hvmloader/config.h Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/firmware/hvmloader/hvmloader.c
--- a/tools/firmware/hvmloader/hvmloader.c      Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/firmware/hvmloader/hvmloader.c      Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/firmware/rombios/rombios.c
--- a/tools/firmware/rombios/rombios.c  Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/firmware/rombios/rombios.c  Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/ioemu/hw/ide.c
--- a/tools/ioemu/hw/ide.c      Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/ioemu/hw/ide.c      Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/ioemu/target-i386-dm/exec-dm.c
--- a/tools/ioemu/target-i386-dm/exec-dm.c      Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/ioemu/target-i386-dm/exec-dm.c      Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/ioemu/vl.c
--- a/tools/ioemu/vl.c  Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/ioemu/vl.c  Thu Jul 12 09:53:58 2007 +0100
@@ -7141,13 +7141,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;
     
diff -r f536eb8576ee -r d0477293897c tools/libxc/xc_domain.c
--- a/tools/libxc/xc_domain.c   Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/libxc/xc_domain.c   Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/libxc/xenctrl.h
--- a/tools/libxc/xenctrl.h     Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/libxc/xenctrl.h     Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c 
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      Thu Jul 12 09:53:58 
2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/libxen/include/xen/api/xen_vdi.h
--- a/tools/libxen/include/xen/api/xen_vdi.h    Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/libxen/include/xen/api/xen_vdi.h    Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/libxen/include/xen/api/xen_vm.h
--- a/tools/libxen/include/xen/api/xen_vm.h     Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/libxen/include/xen/api/xen_vm.h     Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c 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       Thu Jul 12 09:53:58 
2007 +0100
@@ -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 f536eb8576ee -r d0477293897c 
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  Thu Jul 12 09:53:58 
2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/libxen/src/xen_acmpolicy.c
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/libxen/src/xen_acmpolicy.c  Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/libxen/src/xen_vdi.c
--- a/tools/libxen/src/xen_vdi.c        Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/libxen/src/xen_vdi.c        Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/libxen/src/xen_vm.c
--- a/tools/libxen/src/xen_vm.c Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/libxen/src/xen_vm.c Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/libxen/src/xen_xspolicy.c
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/libxen/src/xen_xspolicy.c   Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/python/xen/xend/XendDomain.py
--- a/tools/python/xen/xend/XendDomain.py       Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xend/XendDomain.py       Thu Jul 12 09:53:58 2007 +0100
@@ -1164,6 +1164,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 +1541,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 f536eb8576ee -r d0477293897c tools/python/xen/xm/activatepolicy.py
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/python/xen/xm/activatepolicy.py     Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/python/xen/xm/addlabel.py
--- a/tools/python/xen/xm/addlabel.py   Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/addlabel.py   Thu Jul 12 09:53:58 2007 +0100
@@ -25,17 +25,29 @@ 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>]
     
     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 +78,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 +136,35 @@ 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 main(argv):
     policyref = None
+    policy_type = ""
     if len(argv) not in (4, 5):
         raise OptionError('Needs either 2 or 3 arguments')
     
@@ -121,6 +174,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 +190,27 @@ 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)
+    else:
+        raise OptionError('Need to specify either "dom", "mgt" or "res" as '
                           'object to add label to.')
             
 if __name__ == '__main__':
@@ -149,6 +219,3 @@ if __name__ == '__main__':
     except Exception, e:
         sys.stderr.write('Error: %s\n' % str(e))
         sys.exit(-1)
-    
-
-
diff -r f536eb8576ee -r d0477293897c tools/python/xen/xm/cfgbootpolicy.py
--- a/tools/python/xen/xm/cfgbootpolicy.py      Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/cfgbootpolicy.py      Thu Jul 12 09:53:58 2007 +0100
@@ -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,39 @@ 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:
+            OptionError("Policy installed on system '%s' does not match the "
+                        "request 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 +196,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 f536eb8576ee -r d0477293897c tools/python/xen/xm/create.dtd
--- a/tools/python/xen/xm/create.dtd    Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/create.dtd    Thu Jul 12 09:53:58 2007 +0100
@@ -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
@@ -73,6 +75,9 @@
                  device          CDATA       #REQUIRED
                  qos_algorithm_type CDATA    #REQUIRED
                  network         CDATA       #IMPLIED> 
+
+<!ELEMENT vtpm   (name*)>
+<!ATTLIST vtpm   backend         CDATA #REQUIRED>
 
 <!ELEMENT console (other_config*)>
 <!ATTLIST console protocol       (vt100|rfb|rdp) #REQUIRED>
diff -r f536eb8576ee -r d0477293897c tools/python/xen/xm/create.py
--- a/tools/python/xen/xm/create.py     Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/create.py     Thu Jul 12 09:53:58 2007 +0100
@@ -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!")
 
@@ -1231,13 +1221,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 f536eb8576ee -r d0477293897c tools/python/xen/xm/getlabel.py
--- a/tools/python/xen/xm/getlabel.py   Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/getlabel.py   Thu Jul 12 09:53:58 2007 +0100
@@ -21,14 +21,19 @@ 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>
            
-    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 +42,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 +101,19 @@ 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_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 +122,15 @@ 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)
     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 +138,4 @@ if __name__ == '__main__':
     except Exception, e:
         sys.stderr.write('Error: %s\n' % str(e))
         sys.exit(-1)
-        
 
-
diff -r f536eb8576ee -r d0477293897c tools/python/xen/xm/getpolicy.py
--- /dev/null   Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/python/xen/xm/getpolicy.py  Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/python/xen/xm/labels.py
--- a/tools/python/xen/xm/labels.py     Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/labels.py     Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/python/xen/xm/loadpolicy.py
--- a/tools/python/xen/xm/loadpolicy.py Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/loadpolicy.py Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/python/xen/xm/main.py
--- a/tools/python/xen/xm/main.py       Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/main.py       Thu Jul 12 09:53:58 2007 +0100
@@ -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,17 @@ 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'] = ""
+        label = get_info('security_label', unicode, '')
+        tmp = label.split(":")
+        if len(tmp) != 3:
+            label = ""
+        else:
+            label = tmp[2]
+        parsed_info['seclabel'] = label
 
     if serverType == SERVER_XEN_API:
         parsed_info['mem'] = get_info('memory_actual', int, 0) / 1024
@@ -925,28 +938,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()))
@@ -1989,16 +2000,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
@@ -2440,6 +2459,9 @@ IMPORTED_COMMANDS = [
     'getlabel',
     'dry-run',
     'resources',
+    'getpolicy',
+    'setpolicy',
+    'activatepolicy',
     ]
 
 for c in IMPORTED_COMMANDS:
@@ -2563,6 +2585,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 f536eb8576ee -r d0477293897c tools/python/xen/xm/makepolicy.py
--- a/tools/python/xen/xm/makepolicy.py Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/makepolicy.py Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/python/xen/xm/resources.py
--- a/tools/python/xen/xm/resources.py  Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/resources.py  Thu Jul 12 09:53:58 2007 +0100
@@ -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 f536eb8576ee -r d0477293897c tools/python/xen/xm/rmlabel.py
--- a/tools/python/xen/xm/rmlabel.py    Wed Jul 11 11:32:30 2007 -0600
+++ b/tools/python/xen/xm/rmlabel.py    Thu Jul 12 09:53:58 2007 +0100
@@ -22,35 +22,52 @@ 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>
 
     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 +75,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 +110,24 @@ 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 main (argv):
@@ -103,12 +135,15 @@ def main