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

[Xen-changelog] Merge



# HG changeset patch
# User djm@xxxxxxxxxxxxxxx
# Node ID 878a9891b056c19524e4d213f706a5cafc983b3a
# Parent  e62c54ab862f3a2972687967f99bd92e8f3f0d3c
# Parent  04a7decd0645b23f1f398340e927eb191f0e754d
Merge

diff -r e62c54ab862f -r 878a9891b056 .hgignore
--- a/.hgignore Sat Nov 19 05:06:09 2005
+++ b/.hgignore Sat Nov 19 05:16:29 2005
@@ -148,6 +148,8 @@
 ^tools/vtpm_manager/manager/vtpm_managerd$
 ^tools/xcutils/xc_restore$
 ^tools/xcutils/xc_save$
+^tools/xenmon/setmask$
+^tools/xenmon/xenbaked$
 ^tools/xenstat/xentop/xentop$
 ^tools/xenstore/testsuite/tmp/.*$
 ^tools/xenstore/xen$
@@ -169,6 +171,7 @@
 ^tools/xentrace/tbctl$
 ^tools/xentrace/xenctx$
 ^tools/xentrace/xentrace$
+^tools/xm-test/ramdisk/buildroot
 ^xen/BLOG$
 ^xen/TAGS$
 ^xen/arch/x86/asm-offsets\.s$
diff -r e62c54ab862f -r 878a9891b056 Makefile
--- a/Makefile  Sat Nov 19 05:06:09 2005
+++ b/Makefile  Sat Nov 19 05:16:29 2005
@@ -167,6 +167,9 @@
        [ -d $(D)/etc/xen ] && mv -f $(D)/etc/xen $(D)/etc/xen.old-`date +%s` 
|| true
        rm -rf $(D)/etc/init.d/xend*
        rm -rf $(D)/etc/hotplug/xen-backend.agent
+       rm -f  $(D)/etc/udev/rules.d/xen-backend.rules
+       rm -f  $(D)/etc/udev/xen-backend.rules
+       rm -f  $(D)/etc/sysconfig/xendomains
        rm -rf $(D)/var/run/xen* $(D)/var/lib/xen*
        rm -rf $(D)/boot/*xen*
        rm -rf $(D)/lib/modules/*xen*
@@ -179,7 +182,8 @@
        rm -rf $(D)/usr/$(LIBDIR)/libxenctrl* $(D)/usr/$(LIBDIR)/libxenguest*
        rm -rf $(D)/usr/$(LIBDIR)/libxenstore*
        rm -rf $(D)/usr/$(LIBDIR)/python/xen $(D)/usr/$(LIBDIR)/xen 
-       rm -rf $(D)/usr/$(LIBDIR)/xen/bin
+       rm -rf $(D)/usr/$(LIBDIR)/xen/
+       rm -rf $(D)/usr/lib/xen/
        rm -rf $(D)/usr/sbin/xen* $(D)/usr/sbin/netfix $(D)/usr/sbin/xm
        rm -rf $(D)/usr/share/doc/xen
        rm -rf $(D)/usr/share/xen
diff -r e62c54ab862f -r 878a9891b056 buildconfigs/Rules.mk
--- a/buildconfigs/Rules.mk     Sat Nov 19 05:06:09 2005
+++ b/buildconfigs/Rules.mk     Sat Nov 19 05:16:29 2005
@@ -84,7 +84,7 @@
        rm -rf $(@D)
        cp -al $(<D) $(@D)
        if [ -d patches/$* ] ; then \
-           for i in patches/$*/*.patch ; do ( cd $(@D) ; patch -p1 <../$$i || 
exit 1 ) ; done ; \
+           for i in patches/$*/*.patch ; do patch -d $(@D) -p1 <$$i || exit 1 
; done ; \
        fi
        touch $@ # update timestamp to avoid rebuild
 endif
diff -r e62c54ab862f -r 878a9891b056 docs/man/xm.pod.1
--- a/docs/man/xm.pod.1 Sat Nov 19 05:06:09 2005
+++ b/docs/man/xm.pod.1 Sat Nov 19 05:16:29 2005
@@ -8,122 +8,385 @@
 
 =head1 DESCRIPTION
 
-The B<xm> program is the main interface for managing Xen guest domains. The 
program can be used to create, pause, and shutdown domains. It can also be used 
to list current domains, enable or pin VCPUs, and attach or detach virtual 
block devices. The B<xm> program relies upon B<xend>. The daemon must be 
running in order for the program to work.
-
-Domain name <DomName> can be substituted in the subcommands for Domain id 
<DomId>.
+The B<xm> program is the main interface for managing Xen guest
+domains. The program can be used to create, pause, and shutdown
+domains. It can also be used to list current domains, enable or pin
+VCPUs, and attach or detach virtual block devices.
+
+The basic structure of every xm command is almost always:
+
+  xm <subcommand> <domain-id> [OPTIONS]
+
+Where I<subcommand> is one of the sub commands listed below, I<domain-id>
+is the numeric domain id, or the domain name (which will be internally
+translated to domain id), and I<OPTIONS> are sub command specific
+options.  There are a few exceptions to this rule in the cases where
+the sub command in question acts on all domains, the entire machine,
+or directly on the xen hypervisor.  Those exceptions will be clear for
+each of those sub commands.
+
+=head1 NOTES
+
+All B<xm> opperations rely upon the Xen control daemon, aka B<xend>.
+For any xm commands to run xend must also be running.  For this reason
+you should start xend as a service when your system first boots using
+xen.
+
+Most B<xm> commands require root privledges to run due to the
+communications channels used to talk to the hypervisor.  Running as
+non root will return an error.
+
+Most B<xm> commands act asynchronously, so just because the B<xm>
+command returned, doesn't mean the action is complete.  This is
+important, as many operations on domains, like create and shutdown,
+can take considerable time (30 seconds or more) to bring the machine
+into a fully compliant state.  If you want to know when one of these
+actions has finished you must poll through xm list periodically.
 
 =head1 DOMAIN SUBCOMMANDS
 
-=over 4
-
-=item I<console> <DomId>
-
-Attach to domain DomId's console.
-
-=item I<create> <CfgFile>
-
-Create a domain based on B<xmdomain.cfg> configuration file.
-
-=item I<destroy> <DomId>
-
-Terminate domain DomId immediately.
-
-=item I<domid> <DomName>
-
-Converts a domain name to a domain id.
-
-=item I<domname> <DomId>
-
-Converts a domain id to a domain name.
-
-=item I<help> [--long]
-
-Displays command's help message. The long option prints out the complete set 
of B<xm> subcommands.
-
-=item I<list> [DomId, ...]
-
-List information about domains.
-
-=item I<mem-max> <DomId> <Mem>
-
-Set domain maximum memory limit to Mem. Mem is in Megabytes. This is the upper 
memory mark for how much memory a domain can have.
-
-=item I<mem-set> <DomId> <Mem>
-
-Set domain's memory, in Megabytes. Mem must be less than or equal to the 
maximum memory for the domain.
-
-=item I<migrate> <DomId> <Host> [Options]
-
-Migrate a domain to another Host machine. B<Xend> must be running on other 
host machine and there must be sufficient resources as well.
-
-=over 4
-
-Additional Options:
-
-    -l, --live                    Use live migration.
-    -r, --resource <Mbit value>   Set resource level.
-
-=back
-
-=item I<pause> <DomId>
-
-Pause a domain's execution.
-
-=item I<reboot> [Options] <DomId>
-
-Reboot a domain.
-
-=over 4
-
-Additional Options:
-
-    -a, --all        reboot all domains.
-    -w, --wait       Wait for shutdown to complete.
-
-=back
-
-=item I<restore> <File>
-
-Create a domain from saved state File.
-
-=item I<save> <DomId> <File>
-
-Save domain state to File. Saves domain configuration to File as well.
-
-=item I<shutdown> [Options] <DomId>
-
-Shutdown a domain.
-
-=over 4
-
-Additional Options:
-
-    -a, --all        Shutdown all domains.
-    -H, --halt       Shutdown domain without reboot.
-    -R, --reboot     Shutdown and reboot domain.
-    -w, --wait       Wait for shutdown to complete.
-
-=back
-
-=item I<sysrq> <DomId> <letter>
-
-Send a sysrq to a domain.
-
-=item I<unpause> <DomId>
-
-Unpause a paused domain.
-
-=item I<set-vcpus> <DomId> <VCPUs>
-
-Enable a specific number of VCPUs for a domain. Subcommand only enables or 
disables already configured VCPUs for domain.
-
-=item I<vpcu-list> [DomID]
-
-Lists VCPU information for a specific domain or all domains if DomID not given.
-
-=item I<vcpu-pin> <DomId> <VCPU> <CPUs>
-
-Sets VCPU to only run on specific CPUs.
+The following sub commands manipulate domains directly, as stated
+previously most commands take domain-id as the first parameter.
+
+=over 4
+
+=item B<console> I<domain-id>
+
+Attach to domain domain-id's console.  If you've set up your Domains to
+have a traditional log in console this will look much like a normal
+text log in screen.
+
+This uses the back end xenconsole service which currently only
+works for para-virtual domains.  
+
+The attached console will perform much like a standard serial console,
+so running curses based interfaces over the console B<is not
+advised>.  Vi tends to get very odd when using it over this interface.
+
+=item B<create> I<[-c]> I<configfile> I<[name=value]>..
+
+The create sub command requires a configfile and can optional take a
+series of name value pairs that add to or override variables defined
+in the config file.  See L<xmdomain.cfg> for full details of that file
+format, and possible options used in either the configfile or
+Name=Value combinations.
+
+Configfile can either be an absolute path to a file, or a relative
+path to a file located in /etc/xen.
+
+Create will return B<as soon> as the domain is started.  This B<does
+not> mean the guest OS in the domain has actually booted, or is
+available for input.
+
+B<OPTIONS>
+
+=over 4 
+
+=item B<-c>
+
+Attache console to the domain as soon as it has started.  This is
+useful for determining issues with crashing domains.
+
+=back
+
+B<EXAMPLES>
+
+=over 4
+
+=item I<with config file>
+
+  xm create Fedora4
+
+This creates a domain with the file /etc/xen/Fedora4, and returns as
+soon as it is run.
+
+=item I<without config file>
+ 
+  xm create /dev/null ramdisk=initrd.img \
+     kernel=/boot/vmlinuz-2.6.12.6-xenU \
+     name=ramdisk nics=0 vcpus=1 \
+     memory=64 root=/dev/ram0
+
+This creates the domain without using a config file (more specifically
+using /dev/null as an empty config file), kernel and ramdisk as
+specified, setting the name of the domain to "ramdisk", also disabling
+virtual networking.  (This example comes from the xm-test test suite.)
+
+=back
+
+=item B<destroy> I<domain-id>
+
+Immediately terminate the domain domain-id.  This doesn't give the domain
+OS any chance to react, and it the equivalent of ripping the power
+cord out on a physical machine.  In most cases you will want to use
+the B<shutdown> command instead.
+
+=item B<domid> I<domain-name>
+
+Converts a domain name to a domain id using xend's internal mapping.
+
+=item B<domname> I<domain-id>
+
+Converts a domain id to a domain name using xend's internal mapping.
+
+=item B<help> I<[--long]>
+
+Displays the short help message (i.e. common commands).
+
+The I<--long> option prints out the complete set of B<xm> subcommands,
+grouped by function.
+
+=item B<list> I<[--long]> I<[domain-id, ...]>
+
+Prints information about one or more domains.  If no domains are
+specified it prints out information about all domains.
+
+An example format for the list is as follows:
+
+    Name                         ID Mem(MiB) VCPUs State  Time(s)
+    Domain-0                      0       98     1 r-----  5068.6
+    Fedora3                     164      128     1 r-----     7.6
+    Fedora4                     165      128     1 ------     0.6
+    Mandrake2006                166      128     1 -b----     3.6
+    Mandrake10.2                167      128     1 ------     2.5
+    Suse9.2                     168      100     1 ------     1.8
+
+Name is the name of the domain.  ID the domain numeric id.  Mem is the
+size of the memory allocated to the domain.  VCPUS is the number of
+VCPUS allocated to domain.  State is the run state (see below).  Time
+is the total run time of the domain as accounted for by Xen.
+
+B<STATES>
+
+=over 4
+
+The State field lists 6 states for a Xen Domain, and which ones the
+current Domain is in.
+
+=item B<r - running>
+
+The domain is currently running on a CPU
+
+=item B<b - blocked>
+
+The domain is blocked, and not running or runable.  This can be caused
+because the domain is waiting on IO (a traditional wait state) or has
+gone to sleep because there was nothing else for it to do.
+
+=item B<p - paused>
+
+The domain has been paused, usually occurring through the administrator
+running B<xm pause>.  When in a paused state the domain will still
+consume allocated resources like memory, but will not be eligible for
+scheduling by the Xen hypervisor.
+
+=item B<s - shutdown>
+
+FIXME: Why would you ever see this state?
+
+=item B<c - crashed>
+
+The domain has crashed, which is always a violent ending.  Usually
+this state can only occur if the domain has been configured not to
+restart on crash.  See L<xmdomain.cfg> for more info.
+
+=item B<d - dying>
+
+The domain is in process of dying, but hasn't completely shutdown or
+crashed.
+
+FIXME: Is this right?
+
+=back
+
+B<LONG OUTPUT>
+
+=over 4
+
+If I<--long> is specified, the output for xm list is not the table
+view shown above, but instead is an S-Expression representing all
+information known about all domains asked for.  This is mostly only
+useful for external programs to parse the data.
+
+B<Note:> there is no stable guarantees on the format of this data.
+Use at your own risk.
+
+=back
+
+B<NOTES>
+
+=over 4
+
+The Time column is deceptive.  Virtual IO (network and block devices)
+used by Domains requires coordination by Domain0, which means that
+Domain0 is actually charged for much of the time that a DomainU is
+doing IO.  Use of this time value to determine relative utilizations
+by domains is thus very suspect, as a high IO workload may show as
+less utilized than a high CPU workload.  Consider yourself warned.
+
+=back
+
+=item B<mem-max> I<domain-id> I<mem>
+
+Specify the maximum amount of memory the Domain is able to use.  Mem
+is specified in megabytes. 
+
+The mem-max value may not correspond to the actual memory used in the
+Domain, as it may balloon down it's memory to give more back to the OS.
+
+=item B<mem-set> I<domain-id> I<mem>
+
+Set the domain's used memory using the balloon driver.  Because this
+operation requires cooperation from the domain operating system, there
+is no guarantee that it will succeed.
+
+B<Warning:> there is no good way to know in advance how small of a
+mem-set will make a domain unstable and cause it to crash.  Be very
+careful when using this command on running domains.
+
+=item B<migrate> I<domain-id> I<host> I<[options]>
+
+Migrate a domain to another Host machine. B<Xend> must be running on
+other host machine, it must be running the same version of xen, it
+must have the migration tcp port open and accepting connections from
+the source host, and there must be sufficient resources for the domain
+to run (memory, disk, etc).
+
+Migration is pretty complicated, and has many security implications,
+please read the Xen Users Guide to ensure you understand the
+ramifications and limitations on migration before attempting it in
+production.
+
+B<OPTIONS>
+
+=over 4
+
+=item B<-l, --live>
+
+Use live migration.  This will migrate the domain between hosts
+without shutting down the domain.  See the Xen Users Guide for more
+information.
+
+=item B<-r, --resource> I<Mbs>
+
+Set maximum Mbs allowed for migrating the domain.  This ensures that
+the network link is not saturated with migration traffic while
+attempting to do other useful work.
+
+=back
+
+=item B<pause> I<domain-id>
+
+Pause a domain.  When in a paused state the domain will still consume
+allocated resources such as memory, but will not be eligible for
+scheduling by the Xen hypervisor.
+
+=item B<reboot> I<[options]> I<domain-id>
+
+Reboot a domain.  This acts just as if the domain had the B<reboot>
+command run from the console.  The command returns as soon as it has
+executed the reboot action, which may be significantly before the
+domain actually reboots.
+
+The behavior of what happens to a domain when it reboots is set by the
+I<on_reboot> parameter of the xmdomain.cfg file when the domain was
+created.
+
+B<OPTIONS>
+
+=over 4
+
+=item B<-a, --all>
+
+Reboot all domains
+
+=item B<-w, --wait>
+
+Wait for reboot to complete before returning.  This may take a while,
+as all services in the domain will have to be shut down cleanly.
+
+=back
+
+=item B<restore> I<state-file>
+
+Build a domain from an B<xm save> state file.  See I<save> for more info.
+
+=item B<save> I<domain-id> I<state-file>
+
+Saves a running domain to a state file so that it can be restored
+later.  Once saved, the domain will no longer be running on the
+system, thus the memory allocated for the domain will be free for
+other domains to use.  B<xm restore> restores from this state file.
+
+This is roughly equivalent to doing a hibernate on a running computer,
+with all the same limitations.  Open network connections may be
+severed upon restore, as TCP timeouts may have expired.
+
+=item B<shutdown> I<[options]> I<domain-id>
+
+Gracefully shuts down a domain.  This coordinates with the domain OS
+to perform graceful shutdown, so there is no guaruntee that it will
+succeed, and may take a variable length of time depending on what
+services must be shutdown in the domain.  The command returns
+immediately after signally the domain unless that I<-w> flag is used.
+
+The behavior of what happens to a domain when it reboots is set by the
+I<on_shutdown> parameter of the xmdomain.cfg file when the domain was
+created.
+
+B<OPTIONS>
+
+=over 4
+
+=item B<-a> 
+
+Shutdown B<all> domains.  Often used when doing a complete shutdown of
+a Xen system.
+
+=item B<-w>
+
+Wait for the domain to complete shutdown before returning.
+
+=back
+
+=item B<sysrq> I<domain-id> I<letter>
+
+Send a I<Magic System Request> signal to the domain.  For more
+information on available magic sys req operations, see sysrq.txt in
+your Linux Kernel sources.
+
+=item B<unpause> I<domain-id>
+
+Moves a domain out of the paused state.  This will allow a previously
+paused domain to now be eligible for scheduling by the Xen hypervisor.
+
+=item B<set-vcpus> I<domain-id> I<vcpu-count>
+
+Enables the I<vcpu-count> virtual CPUs for the domain in question.
+Like mem-set, this command can only allocate up to the maximum virtual
+CPU count configured at boot for the domain.
+
+If the I<vcpu-count> is smaller than the current number of active
+VCPUs, the highest number VCPUs will be hotplug removed.  This may be
+important for pinning purposes.
+
+Attempting to set-vcpus to a number larger than the initially
+configured VCPU count is an error.  Trying to set-vcpus to < 1 will be
+quietly ignored.
+
+=item B<vpcu-list> I<[domain-id]>
+
+Lists VCPU information for a specific domain.  If no domain is
+specified, VCPU information for all domains will be provided.
+
+=item B<vcpu-pin> I<domain-id> I<vcpu> I<cpus>
+
+Pins the the VCPU to only run on the specific CPUs.  
+
+Normally VCPUs can float between available CPUs whenever Xen deems a
+different run state is appropriate.  Pinning can be used to restrict
+this, by ensuring certain VCPUs can only run on certain physical
+CPUs.
 
 =back
 
@@ -131,124 +394,395 @@
 
 =over 4
 
-=item I<dmesg> [OPTION]
-
-Read or clear Xen's message buffer. The buffer contains Xen boot, warning, and 
error messages.
-
-=over 4
-
-Additional Option:
-
-    -c, --clear        Clears Xen's message buffer.
-
-=back
-
-=item I<info>
-
-Get information about Xen host.
-
-=item I<log>
-
-Print B<xend> log.
-
-=item I<top>
-
-Monitor system and domains in real-time.
+=item B<dmesg> I<[-c]>
+
+Reads the Xen message buffer, similar to dmesg on a Linux system.  The
+buffer contains informational, warning, and error messages created
+during Xen's boot process.  If you are having problems with Xen, this
+is one of the first places to look as part of problem determination.
+
+B<OPTIONS>
+
+=over 4
+
+=item B<-c, --clear>
+
+Clears Xen's message buffer.
+
+=back
+
+=item B<info>
+
+Print information about the Xen host in I<name : value> format.  When
+reporting a Xen bug, please provide this information as part of the
+bug report.
+
+Sample xen domain info looks as follows (lines wrapped manually to
+make the man page more readable):
+
+ system                 : Linux
+ host                   : talon
+ release                : 2.6.12.6-xen0
+ version                : #1 Mon Nov 14 14:26:26 EST 2005
+ machine                : i686
+ nr_cpus                : 2
+ nr_nodes               : 1
+ sockets_per_node       : 2
+ cores_per_socket       : 1
+ threads_per_core       : 1
+ cpu_mhz                : 696
+ hw_caps                : 0383fbff:00000000:00000000:00000040
+ memory                 : 767
+ free_memory            : 37
+ xen_major              : 3
+ xen_minor              : 0
+ xen_extra              : -devel
+ xen_caps               : xen-3.0-x86_32
+ xen_params             : virt_start=0xfc000000
+ xen_changeset          : Mon Nov 14 18:13:38 2005 +0100 
+                          7793:090e44133d40
+ cc_compiler            : gcc version 3.4.3 (Mandrakelinux 
+                          10.2 3.4.3-7mdk)
+ cc_compile_by          : sdague
+ cc_compile_domain      : (none)
+ cc_compile_date        : Mon Nov 14 14:16:48 EST 2005
+
+B<FIELDS>
+
+=over 4
+
+Not all fields will be explained here, but some of the less obvious
+ones deserve explanation:
+
+=item I<hw_caps>
+
+A vector showing what hardware capabilities are supported by your
+processor.  This is equivalent to, though more cryptic, the flags
+field in /proc/cpuinfo on a normal Linux machine.
+
+=item I<free_memory>
+
+Available memory (in MB) not allocated to Xen, or any other Domains.
+
+=item I<xen_caps>
+
+The xen version, architecture.  Architecture values can be one of:
+x86_32, x86_32p (i.e. PAE enabled), x86_64, ia64.
+
+=item I<xen_changeset>
+
+The xen mercurial changeset id.  Very useful for determining exactly
+what version of code your Xen system was built from.
+
+=back
+
+=item B<log>
+
+Print out the B<xend> log.  This log file can be found in
+/var/log/xend.log.
+
+=item B<top>
+
+Executes the xentop command, which provides real time monitoring of
+domains.  Xentop is a curses interface, and reasonably self
+explanatory.
 
 =back
 
 =head1 SCHEDULER SUBCOMMANDS
 
-=over 4
-
-=item I<sched-bvt> <Parameters>
-
-Set Borrowed Virtual Time (BVT) scheduler parameters. There are five 
parameters, which are given in order below.
-
-=over 4
-
-Parameters:
-
-    mcuadv - Minimum Charging Unit (MCU) advance.
-    warpback - Warp back time allowed.
-    warpvalue - Warp value.
-    warpl - Warp maximum limit.
-    warpu - Unwarped minimum limit.
+Xen ships with a number of domain schedulers, which can be set at boot
+time with the I<sched=> parameter on the Xen command line.  By
+default I<sedf> is used for scheduling.
+
+FIXME: we really need a scheduler expert to write up this section.
+
+=over 4
+
+=item B<sched-bvt> I<mcuadv> I<warpback> I<warpvalue> I<warpl> I<warpu>
+
+Performs runtime adjustments to the default parameters for the
+Borrowed Virtual Time (BVT) scheduler.  For full information on the
+BVT concept, please consult the base paper listed in the B<SEE ALSO>
+section.
+
+Set Borrowed Virtual Time (BVT) scheduler parameters. There are five
+required parameters, which are given in order below.
+
+FIXME: what units are all the BVT params in?
+
+B<PARAMETERS>
+
+=over 4
+
+=item I<mcuadv>
+
+The MCU (Minimum Charging Unit) advance determines the proportional
+share of the CPU that a domain receives. It is set inversely
+proportionally to a domain's sharing weight.
+
+=item I<warpback>
+
+The amount of `virtual time' the domain is allowed to warp backwards.
+
+=item I<warpvalue>
+
+Warp value (FIXME: what does this really mean?)
+
+=item I<warpl>
+
+The warp limit is the maximum time a domain can run warped for.
+
+=item I<warpu>
+
+The unwarp requirement is the minimum time a domain must run unwarped
+for before it can warp again.
 
 =back 
 
-=item I<sched-bvt-ctxallow> <Allow>
-
-Sets the BVT scheduler's context switch allowance. Allow is the minimum time 
slice allowed to run before being pre-empted.
-
-=item I<sched-sedf> <Parameters>
-
-Set simple sEDF scheduler parameters. Use the following parametersin order.
-
-=over 4
-
-Parameters:
-
-    period - in nanoseconds
-    slice - in nanoseconds
-    latency-hint - scaled period if domain is doing heavy I/O
-    extratime - flag for allowing domain to run in extra time.
-    weight - another way of setting cpu slice.
-
-=back
+=item B<sched-bvt-ctxallow> I<allow>
+
+Sets the BVT scheduler's context switch allowance. 
+
+The context switch allowance is similar to the ``quantum'' in
+traditional schedulers. It is the minimum time that a scheduled domain
+will be allowed to run before being preempted.
+
+=item B<sched-sedf> I<period> I<slice> I<latency-hint> I<extratime> I<weight>
+
+Set Simple EDF (Earliest Deadline First) scheduler parameters.  This
+scheduler provides weighted CPU sharing in an intuitive way and uses
+realtime-algorithms to ensure time guarantees.  For more information
+see docs/misc/sedf_scheduler_mini-HOWTO.txt in the Xen distribution.
+
+B<PARAMETERS>
+
+=over 4
+
+=item I<period>
+
+The normal EDF scheduling usage in nanosecs
+
+=item I<slice>
+
+The normal EDF scheduling usage in nanosecs
+
+FIXME: these are lame, should explain more.
+
+=item I<latency-hint>
+
+Scaled period if domain is doing heavy I/O.
+
+=item I<extratime>
+
+Flag for allowing domain to run in extra time.
+
+=item I<weight>
+
+Another way of setting cpu slice.
+
+=back
+
+B<EXAMPLES>
+
+I<normal EDF (20ms/5ms):>
+
+    xm sched-sedf <dom-id> 20000000 5000000 0 0 0
+  
+I<best-effort domains (i.e. non-realtime):>
+
+    xm sched-sedf <dom-id> 20000000 0 0 1 0
+ 
+I<normal EDF (20ms/5ms) + share of extra-time:>
+  
+    xm sched-sedf <dom-id> 20000000 5000000 0 1 0
+
+I<4 domains with weights 2:3:4:2>
+
+    xm sched-sedf <d1> 0 0 0 0 2
+    xm sched-sedf <d2> 0 0 0 0 3
+    xm sched-sedf <d3> 0 0 0 0 4
+    xm sched-sedf <d4> 0 0 0 0 2
+  
+I<1 fully-specified (10ms/3ms) domain, 3 other domains share available
+rest in 2:7:3 ratio:>
+
+    xm sched-sedf <d1> 10000000 3000000 0 0 0   
+    xm sched-sedf <d2> 0 0 0 0 2   
+    xm sched-sedf <d3> 0 0 0 0 7
+    xm sched-sedf <d4> 0 0 0 0 3
 
 =back
 
 =head1 VIRTUAL DEVICE COMMANDS
 
-=over 4
-
-=item I<block-attach <DomId> <BackDev> <FrontDev> <Mode> [BackDomId]
-
-Create a new virtual block device.
-
-=item I<block-detach> <DomId> <DevId>
-
-Destroy a domain's virtual block device. DevId may either be a device ID or 
the device name as mounted in the guest.
-
-=item I<block-list> <DomId>
-
-List virtual block devices for a domain.
-
-=item I<network-limit> <DomId> <Vif> <Credit> <Period>
-
-Limit the transmission rate of a virtual network interface.
-
-=item I<network-list> <DomId>
-
-List virtual network interfaces for a domain.
+Most virtual devices can be added and removed while guests are
+running.  The effect to the guest OS is much the same as any hotplug
+event.
+
+=head2 BLOCK DEVICES
+
+=over 4
+
+=item B<block-attach> I<domain-id> I<be-dev> I<fe-dev> I<mode> I<[bedomain-id]>
+
+Create a new virtual block device.  This will trigger a hotplug event
+for the guest.
+
+B<OPTIONS>
+
+=over 4
+
+=item I<domain-id>
+
+The domain id of the guest domain that the device will be attached to.
+
+=item I<be-dev>
+
+The device in the backend domain (usually domain 0) to be exported.
+This can be specified as a physical partition (phy:sda7) or as a file
+mounted as loopback (file://path/to/loop.iso).
+
+=item I<fe-dev>
+
+How the device should be presented to the guest domain.  It can be
+specified as either a symbolic name, such as /dev/hdc, for common
+devices, or by device id, such as 0x1400 (/dev/hdc device id in hex).
+
+=item I<mode>
+
+The access mode for the device from the guest domain.  Supported modes
+are I<rw> (read/write) or I<ro> (read-only).
+
+=item I<bedomain-id>
+
+The back end domain hosting the device.  This defaults to domain 0.
+
+=back
+
+B<EXAMPLES>
+
+=over 4
+
+=item I<Mount an ISO as a Disk>
+
+xm block-attach guestdomain file://path/to/dsl-2.0RC2.iso /dev/hdc ro
+
+This will mount the dsl iso as /dev/hdc in the guestdomain as a read
+only device.  This will probably not be detected as a cdrom by the
+guest, but mounting /dev/hdc manually will work.
+
+=back
+
+=item B<block-detach> I<domain-id> I<devid>
+
+Destroy a domain's virtual block device. devid B<must> be the device
+id given to the device by domain 0.  You will need to run I<xm
+block-list> to determine that number.
+
+FIXME: this is currently B<broken>.  Even though a block device is
+removed from domU, it appears to still be allocated in the domain 0.
+
+=item B<block-list> I<domain-id>
+
+List virtual block devices for a domain.  The returned output is
+sexpression formatted.
+
+=head2 NETWORK DEVICES
+
+=item B<network-attach> I<domain-id> I<[script=scriptname]> I<[ip=ipaddr]>
+I<[mac=macaddr]> I<[bridge=bridge-name]> I<[backend=bedomain-id]>
+
+Creates a new network device in the domain specified by domain-id.  It
+takes the following optional options:
+
+B<OPTIONS>
+
+=over 4
+
+=item I<script=scriptname>
+
+Use the specified script name to bring up the network.  Defaults to
+the default setting in xend-config.sxp for I<vif-script>.
+
+=item I<ip=ipaddr>
+
+Passes the specified IP Address to the adapter on creation.  
+
+FIXME: this currently appears to be B<broken>.  I'm not sure under what
+circumstances this should actually work.
+
+=item I<mac=macaddr>
+
+The MAC address that the domain will see on its ethernet device.  If
+the device is not specified it will be randomly generated with the
+00:16:3e vendor id prefix.
+
+=item I<bridge=bridge-name>
+
+The name of the bridge to attach the vif to, in case you have more
+than one.  This defaults to 
+
+=item I<backend=bedomain-id>
+
+The backend domain id.  By default this is domain 0.
+
+=back
+
+=item B<network-detach> I<domain-id> I<devid>
+
+Removes the network device from the domain specified by I<domain-id>.
+I<devid> is the virtual interface device number within the domain
+(i.e. the 3 in vif22.3).
+
+FIXME: this is currently B<broken>.  Network devices aren't completely
+removed from domain 0.
+
+=item B<network-list> I<domain-id>
+
+List virtual network interfaces for a domain.  The returned output is
+sexpression formatted.
 
 =back
 
 =head1 VNET COMMANDS
 
-=over 4
-
-=item I<vnet-list> [-l|--long]
+The Virtual Network interfaces for Xen.
+
+FIXME: This needs a lot more explaination, or it needs to be ripped
+out entirely.
+
+=over 4
+
+=item B<vnet-list> I<[-l|--long]>
 
 List vnets.
 
-=item I<vnet-create> <config>
+=item B<vnet-create> I<config>
 
 Create a vnet from a config file.
 
-=item I<vnet-delete> <vnetid>
+=item B<vnet-delete> I<vnetid>
 
 Delete a vnet.
 
 =back
 
+=head1 EXAMPLES
+
 =head1 SEE ALSO
 
-B<xmdomain.cfg>(5)
+B<xmdomain.cfg>(5), B<xentop>(1)
+
+BVT scheduling paper: K.J. Duda and D.R. Cheriton. Borrowed Virtual
+Time (BVT) scheduling: supporting latency-sensitive threads in a
+general purpose scheduler. In proceedings of the 17th ACM SIGOPS
+Symposium on Operating Systems principles, volume 33(5) of ACM
+Operating Systems Review, pages 261-267
 
 =head1 AUTHOR
 
+  Sean Dague <sean at dague dot net>
   Daniel Stekloff <dsteklof at us dot ibm dot com>
 
 =head1 BUGS
diff -r e62c54ab862f -r 878a9891b056 docs/man/xmdomain.cfg.pod.5
--- a/docs/man/xmdomain.cfg.pod.5       Sat Nov 19 05:06:09 2005
+++ b/docs/man/xmdomain.cfg.pod.5       Sat Nov 19 05:16:29 2005
@@ -1,6 +1,6 @@
 =head1 NAME
 
-xmdomain.cfg - xm domain create config file format
+xmdomain.cfg - xm domain config file format
 
 =head1 SYNOPSIS
 
@@ -10,17 +10,22 @@
 
 =head1 DESCRIPTION
 
-The xm(1) program uses python executable config files to define
+The B<xm>(1) program uses python executable config files to define
 domains to create from scratch.  Each of these config files needs to
 contain a number of required options, and may specify many more.
 
-Domain configuration files live in /etc/xen by default, though the
-full path to the config file must be specified in the I<xm create>
-command, so they can exist anywhere in the filesystem.
-
-/etc/xen/auto is a special case however, as domain config files in
-that directory will be started automatically at system boot if the
-xendomain init script is enabled.
+Domain configuration files live in /etc/xen by default, if you store
+config files anywhere else the full path to the config file must be
+specified in the I<xm create> command.
+
+/etc/xen/auto is a special case.  Domain config files in that
+directory will be started automatically at system boot if the
+xendomain init script is enabled.  The contents of /etc/xen/auto
+should be symlinks to files in /etc/xen to allow I<xm create> to be
+used without full paths.
+
+Options are specified by I<name = value> statements in the
+xmdomain.cfg files.
 
 =head1 OPTIONS
 
@@ -29,50 +34,157 @@
 
 =over 4
 
-=item I<kernel>
-
-The kernel image used in the domain.
-
-=item I<ramdisk>
-
-The initial ramdisk to be used in the domain.  Default xen domU
-kernels do not usually need a ramdisk.
-
-=item I<memory>
-
-The amount of memory, in megabytes to allocate to the domain when it
+=item B<kernel>
+
+The kernel image for the domain.  The format of the parameter is the
+fully qualified path to the kernel image file,
+i.e. I</boot/vmlinuz-2.6.12-xenU>.
+
+
+=item B<ramdisk>
+
+The initial ramdisk for the domain.  The format of the parameter is
+the fully qualified path to the initrd, i.e. I</boot/initrd.gz>.  On
+many Linux distros you will not need a ramdisk if using the default
+xen kernel.
+
+=item B<memory>
+
+The amount of RAM, in megabytes, to allocate to the domain when it
 starts.  Allocating insufficient memory for a domain may produce
-extremely bizarre behavior.
-
-=item I<name>
-
-A unique name for the domain.  You can not create 2 domains with the
-same name.
-
-=item I<root>
-
-Root stanza for the domain (required for Linux domains).
-
-=item I<disk>
-
-An array of disk stanzas 
-
-=back
-
-A bare minimal config file example might be as follows:
-
-    kernel = "/boot/vmlinuz-2.6-xenU"
-    memory = 128
-    name = "MyLinux"      
-    root = "/dev/hda1 ro"
+extremely bizarre behavior.  If there isn't enough free memory left on
+the machine to fulfill this request, the domain will fail to start.
+
+Xen does not support overcommit of memory, so the total memory of all
+guests (+ 64 MB needed for Xen) must be less than or equal to the
+physical RAM in the machine.
+
+=item B<name>
+
+A unique name for the domain.  Attempting to create two domains with
+the same name will cause an error.
+
+=item B<root>
+
+Specifies the root device for the domain.  This is required for Linux
+domains, and possibly other OSes.
+
+=item B<nics>
+
+The number of network interfaces allocated to the domain on boot.  It
+defaults to 1.
+
+=item B<disk>
+
+An array of block device stanzas, in the form:
+
+    disk = [ "stanza1", "stanza2", ... ]
+
+Each stanza has 3 terms, seperated by commas,
+"backend-dev,frontend-dev,mode".
+
+=over 4
+
+=item I<backend-dev>
+
+The device in the backend domain that will be exported to the guest
+(frontend) domain.  Supported formats include:
+
+I<phy:device> - export the physical device listed.  The device can be
+in symbolic form, as in sda7, or as the hex major/minor number, as in
+0x301 (which is hda1).
+
+I<file://path/to/file> - export the file listed as a loopback device.
+This will take care of the loopback setup before exporting the device.
+
+=item I<frontend-dev>
+
+How the device should appear in the guest domain.  The device can be
+in symbolic form, as in sda7, or as the hex major/minor number, as in
+0x301 (which is hda1).
+
+=item I<mode>
+
+The access mode for the device.  There are currently 2 valid options,
+I<r> (read-only), I<w> (read/write).
+
+=back
+
+=item B<vif>
+
+An arrray of virtual interface stanzas in the form:
+
+    vif = [ "stanza1", "stanza2", ... ]
+
+Each stanza specifies a set of I<name = value> options separated by
+commas, in the form: "name1=value1, name2=value2, ..."
+
+B<OPTIONS>
+
+=over 4
+
+=item I<bridge>
+
+The network bridge to be used for this device.  This is especially
+needed if multiple bridges exist on the machine.
+
+=item I<mac>
+
+The MAC address for the virtual interface.  If mac is not specified,
+one will be randomly chosen by xen with the 00:16:3e vendor id prefix.
+
+=back
+
+=back
 
 =head1 ADDITIONAL OPTIONS
 
-=over 4
-
-=item I<builder>
-
-=back 
+The following options are also supported in the config file, though
+are far more rarely used.
+
+=over 4
+
+=item B<builder>
+
+Which builder should be used to construct the domain.  This defaults
+to the I<linux> if not specified, which is the builder for
+paravirtualized Linux domains.
+
+=item B<cpu>
+
+Specifies which CPU the domain should be started on, where 0 specifies
+the first cpu, 1 the second, and so on.  This defaults to -1, which
+means Xen is free to pick which CPU to start on.
+
+=item B<extra>
+
+Extra information to append to the end of the kernel parameter line.
+The format is a string, the contents of which can be anything that the
+kernel supports.  For instance:
+
+    extra = "4"
+
+Will cause the domain to boot to runlevel 4.
+
+=item B<nfs_server>
+
+The IP address of the NFS server to use as the root device for the
+domain.  In order to do this you'll need to specify I<root=/dev/nfs>,
+and specify I<nfs_root>.
+
+=item B<nfs_root>
+
+The directory on the NFS server to be used as the root filesystem.
+Specified as a fully qualified path, i.e. I</full/path/to/root/dir>.
+
+=item B<vcpus>
+
+The number of virtual cpus to allocate to the domain.  In order to use
+this the xen kernel must be compiled with SMP support.
+
+This defaults to 1, meaning running the domain as a UP.
+
+=back
 
 =head1 DOMAIN SHUTDOWN OPTIONS
 
@@ -81,17 +193,17 @@
 
 =over 4
 
-=item I<shutdown>
+=item B<on_shutdown>
 
 Triggered on either an I<xm shutdown> or graceful shutdown from inside
 the DomU.
 
-=item I<reboot>
+=item B<on_reboot>
 
 Triggered on either an I<xm reboot> or graceful reboot from inside the
 DomU.
 
-=item I<crash>
+=item B<on_crash>
 
 Triggered when a DomU goes to the crashed state for any reason.
 
@@ -101,23 +213,23 @@
 
 =over 4
 
-=item I<destroy>
+=item B<destroy>
 
 The domain will be cleaned up completely.  No attempt at respawning
 will occur.  This is what a typical shutdown would look like.
 
-=item I<restart>
+=item B<restart>
 
 The domain will be restarted with the same name as the old domain.
 This is what a typical reboot would look like.
 
-=item I<preserve>
+=item B<preserve>
 
 The domain will not be cleaned up at all.  This is often useful for
 crash state domains which ensures that enough evidence is to debug the
 real issue.
 
-=item I<rename-restart>
+=item B<rename-restart>
 
 The old domain will not be cleaned up, but will be renamed so a new
 domain can be restarted in it's place.  The old domain will be renamed with
@@ -127,6 +239,39 @@
 
 =back
 
+=head1 EXAMPLES
+
+The following are quick examples of ways that domains might be
+configured.  They should not be considered an exhaustive set.
+
+=over 4
+
+=item I<A Loopback File as Root>
+
+    kernel = "/boot/vmlinuz-2.6-xenU"
+    memory = 128
+    name = "MyLinux"      
+    root = "/dev/hda1 ro"
+    disk = [ "file:/var/xen/mylinux.img,hda1,w" ]
+
+This creates a domain called MyLinux with 128 MB of memory using a
+default xen kernel, and the file /var/xen/mylinux.img loopback mounted
+at hda1, which is the root filesystem.
+
+=item I<NFS Root>
+
+FIXME: write me
+
+=item I<LVM Root>
+
+FIXME: write me
+
+=item I<Two Networks>
+
+FIXME: write me
+
+=back
+
 =head1 SEE ALSO
 
 B<xm>(1)
diff -r e62c54ab862f -r 878a9891b056 docs/src/user.tex
--- a/docs/src/user.tex Sat Nov 19 05:06:09 2005
+++ b/docs/src/user.tex Sat Nov 19 05:16:29 2005
@@ -7,7 +7,6 @@
 \def\xend{{xend}\xspace}
 
 \latexhtml{\newcommand{\path}[1]{{\small {\tt 
#1}}}}{\newcommand{\path}[1]{{\tt #1}}}
-
 
 
 \begin{document}
@@ -21,23 +20,23 @@
 \vfill
 \vfill
 \begin{tabular}{l}
-{\Huge \bf Users' manual} \\[4mm]
-{\huge Xen v2.0 for x86} \\[80mm]
-
-{\Large Xen is Copyright (c) 2002-2004, The Xen Team} \\[3mm]
+{\Huge \bf Users' Manual} \\[4mm]
+{\huge Xen v3.0} \\[80mm]
+
+{\Large Xen is Copyright (c) 2002-2005, The Xen Team} \\[3mm]
 {\Large University of Cambridge, UK} \\[20mm]
 \end{tabular}
 \end{center}
 
-{\bf
-DISCLAIMER: This documentation is currently under active development
-and as such there may be mistakes and omissions --- watch out for
-these and please report any you find to the developer's mailing list.
-Contributions of material, suggestions and corrections are welcome.
-}
+{\bf DISCLAIMER: This documentation is currently under active
+  development and as such there may be mistakes and omissions ---
+  watch out for these and please report any you find to the
+  developers' mailing list.  Contributions of material, suggestions
+  and corrections are welcome.}
 
 \vfill
 \cleardoublepage
+
 
 % TABLE OF CONTENTS
 \pagestyle{plain}
@@ -45,6 +44,7 @@
 { \parskip 0pt plus 1pt
   \tableofcontents }
 \cleardoublepage
+
 
 % PREPARE FOR MAIN TEXT
 \pagenumbering{arabic}
@@ -68,7 +68,7 @@
 %% Chapter Installation moved to installation.tex
 \include{src/user/installation}
 
-%% Chapter Starting Additional Domains  moved to start_addl_dom.tex
+%% Chapter Starting Additional Domains moved to start_addl_dom.tex
 \include{src/user/start_addl_dom}
 
 %% Chapter Domain Management Tools moved to domain_mgmt.tex
@@ -86,6 +86,9 @@
 
 %% Chapter Domain Configuration moved to domain_configuration.tex
 \include{src/user/domain_configuration}
+
+%% Chapter Securing Xen
+\include{src/user/securing_xen}
 
 %% Chapter Build, Boot and Debug Options moved to build.tex
 \include{src/user/build}
@@ -99,25 +102,25 @@
 software (or the documentation) should be sent to the Xen developers'
 mailing list (address below).
 
+
 \section{Other Documentation}
 
 For developers interested in porting operating systems to Xen, the
-{\em Xen Interface Manual} is distributed in the \path{docs/}
-directory of the Xen source distribution.  
-
-%Various HOWTOs are available in \path{docs/HOWTOS} but this content is
-%being integrated into this manual.
+\emph{Xen Interface Manual} is distributed in the \path{docs/}
+directory of the Xen source distribution.
+
+% Various HOWTOs are available in \path{docs/HOWTOS} but this content
+% is being integrated into this manual.
 
 
 \section{Online References}
 
 The official Xen web site is found at:
-\begin{quote}
-{\tt http://www.cl.cam.ac.uk/netos/xen/}
+\begin{quote} {\tt http://www.cl.cam.ac.uk/netos/xen/}
 \end{quote}
 
-This contains links to the latest versions of all on-line 
-documentation (including the lateset version of the FAQ). 
+This contains links to the latest versions of all online
+documentation, including the latest version of the FAQ.
 
 
 \section{Mailing Lists}
@@ -126,17 +129,17 @@
 
 \begin{description}
 \item[xen-devel@xxxxxxxxxxxxxxxxxxx] Used for development
-discussions and bug reports.  Subscribe at: \\
-{\small {\tt http://lists.xensource.com/xen-devel}}
+  discussions and bug reports.  Subscribe at: \\
+  {\small {\tt http://lists.xensource.com/xen-devel}}
 \item[xen-users@xxxxxxxxxxxxxxxxxxx] Used for installation and usage
-discussions and requests for help.  Subscribe at: \\
-{\small {\tt http://lists.xensource.com/xen-users}}
+  discussions and requests for help.  Subscribe at: \\
+  {\small {\tt http://lists.xensource.com/xen-users}}
 \item[xen-announce@xxxxxxxxxxxxxxxxxxx] Used for announcements only.
-Subscribe at: \\
-{\small {\tt http://lists.xensource.com/xen-announce}}
-\item[xen-changelog@xxxxxxxxxxxxxxxxxxx]  Changelog feed
-from the unstable and 2.0 trees - developer oriented.  Subscribe at: \\
-{\small {\tt http://lists.xensource.com/xen-changelog}}
+  Subscribe at: \\
+  {\small {\tt http://lists.xensource.com/xen-announce}}
+\item[xen-changelog@xxxxxxxxxxxxxxxxxxx] Changelog feed
+  from the unstable and 2.0 trees - developer oriented.  Subscribe at: \\
+  {\small {\tt http://lists.xensource.com/xen-changelog}}
 \end{description}
 
 
@@ -149,9 +152,9 @@
 %% Chapter Installing Xen on Red Hat moved to redhat.tex
 \include{src/user/redhat}
 
-
 %% Chapter Glossary of Terms moved to glossary.tex
 \include{src/user/glossary}
+
 
 
 \end{document}
@@ -181,36 +184,35 @@
 %% # import xenctl.utils
 %% # help(xenctl.utils)
 
-%% You can use these modules to write your own custom scripts or you can
-%% customise the scripts supplied in the Xen distribution.
+%% You can use these modules to write your own custom scripts or you
+%% can customise the scripts supplied in the Xen distribution.
 
 
 
 % Explain about AGP GART
 
 
-%% If you're not intending to configure the new domain with an IP address
-%% on your LAN, then you'll probably want to use NAT. The
-%% 'xen_nat_enable' installs a few useful iptables rules into domain0 to
-%% enable NAT. [NB: We plan to support RSIP in future]
-
+%% If you're not intending to configure the new domain with an IP
+%% address on your LAN, then you'll probably want to use NAT. The
+%% 'xen_nat_enable' installs a few useful iptables rules into domain0
+%% to enable NAT. [NB: We plan to support RSIP in future]
 
 
 
 %% Installing the file systems from the CD
 %% =======================================
 
-%% If you haven't got an existing Linux installation onto which you can
-%% just drop down the Xen and Xenlinux images, then the file systems on
-%% the CD provide a quick way of doing an install. However, you would be
-%% better off in the long run doing a proper install of your preferred
-%% distro and installing Xen onto that, rather than just doing the hack
-%% described below:
-
-%% Choose one or two partitions, depending on whether you want a separate
-%% /usr or not. Make file systems on it/them e.g.: 
-%%   mkfs -t ext3 /dev/hda3
-%%   [or mkfs -t ext2 /dev/hda3 && tune2fs -j /dev/hda3 if using an old
+%% If you haven't got an existing Linux installation onto which you
+%% can just drop down the Xen and Xenlinux images, then the file
+%% systems on the CD provide a quick way of doing an install. However,
+%% you would be better off in the long run doing a proper install of
+%% your preferred distro and installing Xen onto that, rather than
+%% just doing the hack described below:
+
+%% Choose one or two partitions, depending on whether you want a
+%% separate /usr or not. Make file systems on it/them e.g.:
+%% mkfs -t ext3 /dev/hda3
+%% [or mkfs -t ext2 /dev/hda3 && tune2fs -j /dev/hda3 if using an old
 %% version of mkfs]
 
 %% Next, mount the file system(s) e.g.:
@@ -224,12 +226,14 @@
 %% configuration. Changing the password file (etc/shadow) is probably a
 %% good idea too.
 
-%% To install the usr file system, copy the file system from CD on /usr,
-%% though leaving out the "XenDemoCD" and "boot" directories:
-%%   cd /usr && cp -a X11R6 etc java libexec root src bin dict kerberos local 
sbin tmp doc include lib man share /mnt/usr
+%% To install the usr file system, copy the file system from CD on
+%% /usr, though leaving out the "XenDemoCD" and "boot" directories:
+%%   cd /usr && cp -a X11R6 etc java libexec root src bin dict kerberos
+%%    local sbin tmp doc include lib man share /mnt/usr
 
 %% If you intend to boot off these file systems (i.e. use them for
-%% domain 0), then you probably want to copy the /usr/boot directory on
-%% the cd over the top of the current symlink to /boot on your root
-%% filesystem (after deleting the current symlink) i.e.:
+%% domain 0), then you probably want to copy the /usr/boot
+%% directory on the cd over the top of the current symlink to /boot
+%% on your root filesystem (after deleting the current symlink)
+%% i.e.:
 %%   cd /mnt/root ; rm boot ; cp -a /usr/boot .
diff -r e62c54ab862f -r 878a9891b056 docs/src/user/installation.tex
--- a/docs/src/user/installation.tex    Sat Nov 19 05:06:09 2005
+++ b/docs/src/user/installation.tex    Sat Nov 19 05:16:29 2005
@@ -17,42 +17,37 @@
 required if you wish to build from source.
 \begin{itemize}
 \item A working Linux distribution using the GRUB bootloader and
-  running on a P6-class (or newer) CPU.
+  running on a P6-class or newer CPU\@.
 \item [$\dag$] The \path{iproute2} package.
 \item [$\dag$] The Linux bridge-utils\footnote{Available from {\tt
       http://bridge.sourceforge.net}} (e.g., \path{/sbin/brctl})
 \item [$\dag$] The Linux hotplug system\footnote{Available from {\tt
       http://linux-hotplug.sourceforge.net/}} (e.g., \path{/sbin/hotplug}
       and related scripts)
-\item [$\dag$] An installation of Twisted~v1.3 or
-  above\footnote{Available from {\tt http://www.twistedmatrix.com}}.
-  There may be a binary package available for your distribution;
-  alternatively it can be installed by running `{\sl make
-    install-twisted}' in the root of the Xen source tree.
 \item [$*$] Build tools (gcc v3.2.x or v3.3.x, binutils, GNU make).
-\item [$*$] Development installation of libcurl (e.g., libcurl-devel)
-\item [$*$] Development installation of zlib (e.g., zlib-dev).
-\item [$*$] Development installation of Python v2.2 or later (e.g.,
+\item [$*$] Development installation of libcurl (e.g.,\ libcurl-devel).
+\item [$*$] Development installation of zlib (e.g.,\ zlib-dev).
+\item [$*$] Development installation of Python v2.2 or later (e.g.,\ 
   python-dev).
 \item [$*$] \LaTeX\ and transfig are required to build the
   documentation.
 \end{itemize}
 
-Once you have satisfied the relevant prerequisites, you can now
-install either a binary or source distribution of Xen.
+Once you have satisfied these prerequisites, you can now install
+either a binary or source distribution of Xen.
 
 
 \section{Installing from Binary Tarball}
 
 Pre-built tarballs are available for download from the Xen download
-page
-\begin{quote} {\tt http://xen.sf.net}
+page:
+\begin{quote} {\tt http://www.xensource.com/downloads/}
 \end{quote}
 
 Once you've downloaded the tarball, simply unpack and install:
 \begin{verbatim}
-# tar zxvf xen-2.0-install.tgz
-# cd xen-2.0-install
+# tar zxvf xen-3.0-install.tgz
+# cd xen-3.0-install
 # sh ./install.sh
 \end{verbatim}
 
@@ -62,48 +57,29 @@
 
 \section{Installing from Source}
 
-This section describes how to obtain, build, and install Xen from
+This section describes how to obtain, build and install Xen from
 source.
 
 \subsection{Obtaining the Source}
 
-The Xen source tree is available as either a compressed source tar
-ball or as a clone of our master BitKeeper repository.
+The Xen source tree is available as either a compressed source tarball
+or as a clone of our master Mercurial repository.
 
 \begin{description}
 \item[Obtaining the Source Tarball]\mbox{} \\
-  Stable versions (and daily snapshots) of the Xen source tree are
-  available as compressed tarballs from the Xen download page
-  \begin{quote} {\tt http://xen.sf.net}
+  Stable versions and daily snapshots of the Xen source tree are
+  available from the Xen download page:
+  \begin{quote} {\tt \tt http://www.xensource.com/downloads/}
   \end{quote}
-
-\item[Using BitKeeper]\mbox{} \\
-  If you wish to install Xen from a clone of our latest BitKeeper
-  repository then you will need to install the BitKeeper tools.
-  Download instructions for BitKeeper can be obtained by filling out
-  the form at:
-  \begin{quote} {\tt http://www.bitmover.com/cgi-bin/download.cgi}
-\end{quote}
-The public master BK repository for the 2.0 release lives at:
-\begin{quote} {\tt bk://xen.bkbits.net/xen-2.0.bk}
-\end{quote} 
-You can use BitKeeper to download it and keep it updated with the
-latest features and fixes.
-
-Change to the directory in which you want to put the source code, then
-run:
-\begin{verbatim}
-# bk clone bk://xen.bkbits.net/xen-2.0.bk
-\end{verbatim}
-
-Under your current directory, a new directory named \path{xen-2.0.bk}
-has been created, which contains all the source code for Xen, the OS
-ports, and the control tools. You can update your repository with the
-latest changes at any time by running:
-\begin{verbatim}
-# cd xen-2.0.bk # to change into the local repository
-# bk pull       # to update the repository
-\end{verbatim}
+\item[Obtaining the source via Mercurial]\mbox{} \\
+  The source tree may also be obtained via the public Mercurial
+  repository hosted at:
+  \begin{quote}{\tt http://xenbits.xensource.com}.
+  \end{quote} See the instructions and the Getting Started Guide
+  referenced at:
+  \begin{quote}
+    {\tt http://www.xensource.com/downloads/}.
+  \end{quote}
 \end{description}
 
 % \section{The distribution}
@@ -124,7 +100,7 @@
 
 \subsection{Building from Source}
 
-The top-level Xen Makefile includes a target `world' that will do the
+The top-level Xen Makefile includes a target ``world'' that will do the
 following:
 
 \begin{itemize}
@@ -132,17 +108,17 @@
 \item Build the control tools, including \xend.
 \item Download (if necessary) and unpack the Linux 2.6 source code,
   and patch it for use with Xen.
-\item Build a Linux kernel to use in domain 0 and a smaller
+\item Build a Linux kernel to use in domain~0 and a smaller
   unprivileged kernel, which can optionally be used for unprivileged
   virtual machines.
 \end{itemize}
 
 After the build has completed you should have a top-level directory
-called \path{dist/} in which all resulting targets will be placed; of
-particular interest are the two kernels XenLinux kernel images, one
-with a `-xen0' extension which contains hardware device drivers and
-drivers for Xen's virtual devices, and one with a `-xenU' extension
-that just contains the virtual ones. These are found in
+called \path{dist/} in which all resulting targets will be placed. Of
+particular interest are the two XenLinux kernel images, one with a
+``-xen0'' extension which contains hardware device drivers and drivers
+for Xen's virtual devices, and one with a ``-xenU'' extension that
+just contains the virtual ones. These are found in
 \path{dist/install/boot/} along with the image for Xen itself and the
 configuration files used during the build.
 
@@ -150,17 +126,15 @@
 \begin{quote}
 \begin{verbatim}
 # make netbsd20
-\end{verbatim}
-\end{quote}
+\end{verbatim}\end{quote}
 NetBSD port is built using a snapshot of the netbsd-2-0 cvs branch.
-The snapshot is downloaded as part of the build process, if it is not
+The snapshot is downloaded as part of the build process if it is not
 yet present in the \path{NETBSD\_SRC\_PATH} search path.  The build
-process also downloads a toolchain which includes all the tools
+process also downloads a toolchain which includes all of the tools
 necessary to build the NetBSD kernel under Linux.
 
-To customize further the set of kernels built you need to edit the
-top-level Makefile. Look for the line:
-
+To customize the set of kernels built you need to edit the top-level
+Makefile. Look for the line:
 \begin{quote}
 \begin{verbatim}
 KERNELS ?= mk.linux-2.6-xen0 mk.linux-2.6-xenU
@@ -189,7 +163,6 @@
 %% After untaring the pristine kernel tree, the makefile uses the {\tt
 %%   mkbuildtree} script to add the Xen patches to the kernel.
 
-
 %% \framebox{\parbox{5in}{
 %%     {\bf Distro specific:} \\
 %%     {\it Gentoo} --- if not using udev (most installations,
@@ -201,7 +174,7 @@
 % If you have an SMP machine you may wish to give the {\tt '-j4'}
 % argument to make to get a parallel build.
 
-If you wish to build a customized XenLinux kernel (e.g. to support
+If you wish to build a customized XenLinux kernel (e.g.\ to support
 additional devices or enable distribution-required features), you can
 use the standard Linux configuration mechanisms, specifying that the
 architecture being built for is \path{xen}, e.g:
@@ -215,21 +188,21 @@
 \end{quote}
 
 You can also copy an existing Linux configuration (\path{.config})
-into \path{linux-2.6.11-xen0} and execute:
+into e.g.\ \path{linux-2.6.11-xen0} and execute:
 \begin{quote}
 \begin{verbatim}
 # make ARCH=xen oldconfig
 \end{verbatim}
 \end{quote}
 
-You may be prompted with some Xen-specific options; we advise
+You may be prompted with some Xen-specific options. We advise
 accepting the defaults for these options.
 
-Note that the only difference between the two types of Linux kernel
-that are built is the configuration file used for each.  The `U'
+Note that the only difference between the two types of Linux kernels
+that are built is the configuration file used for each.  The ``U''
 suffixed (unprivileged) versions don't contain any of the physical
 hardware device drivers, leading to a 30\% reduction in size; hence
-you may prefer these for your non-privileged domains.  The `0'
+you may prefer these for your non-privileged domains.  The ``0''
 suffixed privileged versions can be used to boot the system, as well
 as in driver domains and unprivileged domains.
 
@@ -259,10 +232,10 @@
 
 The \path{dist/install/boot} directory will also contain the config
 files used for building the XenLinux kernels, and also versions of Xen
-and XenLinux kernels that contain debug symbols (\path{xen-syms-2.0.6}
-and \path{vmlinux-syms-2.6.11.11-xen0}) which are essential for
-interpreting crash dumps.  Retain these files as the developers may
-wish to see them if you post on the mailing list.
+and XenLinux kernels that contain debug symbols such as
+(\path{xen-syms-2.0.6} and \path{vmlinux-syms-2.6.11.11-xen0}) which
+are essential for interpreting crash dumps.  Retain these files as the
+developers may wish to see them if you post on the mailing list.
 
 
 \section{Configuration}
@@ -280,23 +253,23 @@
 
 {\small
 \begin{verbatim}
-title Xen 2.0 / XenLinux 2.6
-  kernel /boot/xen-2.0.gz dom0_mem=131072
+title Xen 3.0 / XenLinux 2.6
+  kernel /boot/xen-3.0.gz dom0_mem=131072
   module /boot/vmlinuz-2.6-xen0 root=/dev/sda4 ro console=tty0
 \end{verbatim}
 }
 
 The kernel line tells GRUB where to find Xen itself and what boot
-parameters should be passed to it (in this case, setting domain 0's
+parameters should be passed to it (in this case, setting the domain~0
 memory allocation in kilobytes and the settings for the serial port).
 For more details on the various Xen boot parameters see
 Section~\ref{s:xboot}.
 
 The module line of the configuration describes the location of the
 XenLinux kernel that Xen should start and the parameters that should
-be passed to it (these are standard Linux parameters, identifying the
+be passed to it. Tthese are standard Linux parameters, identifying the
 root device and specifying it be initially mounted read only and
-instructing that console output be sent to the screen).  Some
+instructing that console output be sent to the screen. Some
 distributions such as SuSE do not require the \path{ro} parameter.
 
 %% \framebox{\parbox{5in}{
@@ -307,24 +280,21 @@
 
 
 If you want to use an initrd, just add another \path{module} line to
-the configuration, as usual:
-
+the configuration, like:
 {\small
 \begin{verbatim}
   module /boot/my_initrd.gz
 \end{verbatim}
 }
 
-As always when installing a new kernel, it is recommended that you do
-not delete existing menu options from \path{menu.lst} --- you may want
-to boot your old Linux kernel in future, particularly if you have
-problems.
+When installing a new kernel, it is recommended that you do not delete
+existing menu options from \path{menu.lst}, as you may wish to boot
+your old Linux kernel in future, particularly if you have problems.
 
 \subsection{Serial Console (optional)}
 
 %% kernel /boot/xen-2.0.gz dom0_mem=131072 com1=115200,8n1
 %% module /boot/vmlinuz-2.6-xen0 root=/dev/sda4 ro
-
 
 In order to configure Xen serial console output, it is necessary to
 add an boot option to your GRUB config; e.g.\ replace the above kernel
@@ -343,24 +313,23 @@
 achieve this append ``\path{console=ttyS0}'' to your module line.
 
 If you wish to be able to log in over the XenLinux serial console it
-is necessary to add a line into \path{/etc/inittab}, just as per
-regular Linux. Simply add the line:
+is necessary to add a line into \path{/etc/inittab}. Add the line:
 \begin{quote} {\small {\tt c:2345:respawn:/sbin/mingetty ttyS0}}
 \end{quote}
 
-and you should be able to log in. Note that to successfully log in as
-root over the serial line will require adding \path{ttyS0} to
-\path{/etc/securetty} in most modern distributions.
+and you should be able to log in. To successfully log in as root over
+the serial line will require adding \path{ttyS0} to
+\path{/etc/securetty} if it is not already there.
 
 \subsection{TLS Libraries}
 
 Users of the XenLinux 2.6 kernel should disable Thread Local Storage
-(e.g.\ by doing a \path{mv /lib/tls /lib/tls.disabled}) before
-attempting to run with a XenLinux kernel\footnote{If you boot without
+(TLS) (e.g.\ by doing a \path{mv /lib/tls /lib/tls.disabled}) before
+attempting to boot a XenLinux kernel\footnote{If you boot without
   first disabling TLS, you will get a warning message during the boot
   process. In this case, simply perform the rename after the machine
   is up and then run \texttt{/sbin/ldconfig} to make it take effect.}.
-You can always reenable it by restoring the directory to its original
+You can always reenable TLS by restoring the directory to its original
 location (i.e.\ \path{mv /lib/tls.disabled /lib/tls}).
 
 The reason for this is that the current TLS implementation uses
@@ -369,19 +338,19 @@
 performance substantially.
 
 We hope that this issue can be resolved by working with Linux
-distribution vendors to implement a minor backward-compatible change
+distributions to implement a minor backward-compatible change
 to the TLS library.
 
 
 \section{Booting Xen}
 
 It should now be possible to restart the system and use Xen.  Reboot
-as usual but choose the new Xen option when the Grub screen appears.
+and choose the new Xen option when the Grub screen appears.
 
 What follows should look much like a conventional Linux boot.  The
 first portion of the output comes from Xen itself, supplying low level
-information about itself and the machine it is running on.  The
-following portion of the output comes from XenLinux.
+information about itself and the underlying hardware.  The last
+portion of the output comes from XenLinux.
 
 You may see some errors during the XenLinux boot.  These are not
 necessarily anything to worry about --- they may result from kernel
@@ -389,5 +358,5 @@
 usually use.
 
 When the boot completes, you should be able to log into your system as
-usual.  If you are unable to log in to your system running Xen, you
-should still be able to reboot with your normal Linux kernel.
+usual.  If you are unable to log in, you should still be able to
+reboot with your normal Linux kernel.
diff -r e62c54ab862f -r 878a9891b056 docs/src/user/introduction.tex
--- a/docs/src/user/introduction.tex    Sat Nov 19 05:06:09 2005
+++ b/docs/src/user/introduction.tex    Sat Nov 19 05:16:29 2005
@@ -2,7 +2,7 @@
 
 
 Xen is a \emph{paravirtualising} virtual machine monitor (VMM), or
-`hypervisor', for the x86 processor architecture.  Xen can securely
+``hypervisor'', for the x86 processor architecture.  Xen can securely
 execute multiple virtual machines on a single physical system with
 close-to-native performance.  The virtual machine technology
 facilitates enterprise-grade functionality, including:
@@ -11,7 +11,7 @@
 \item Virtual machines with performance close to native hardware.
 \item Live migration of running virtual machines between physical
   hosts.
-\item Excellent hardware support (supports most Linux device drivers).
+\item Excellent hardware support. Supports most Linux device drivers.
 \item Sandboxed, re-startable device drivers.
 \end{itemize}
 
@@ -28,7 +28,7 @@
 space applications and libraries \emph{do not} require modification.
 
 Xen support is available for increasingly many operating systems:
-right now, Linux and NetBSD are available for Xen 2.0.
+right now, Linux and NetBSD are available for Xen 3.0.
 A FreeBSD port is undergoing testing and will be incorporated into the
 release soon. Other OS ports, including Plan 9, are in progress.  We
 hope that that arch-xen patches will be incorporated into the
@@ -43,14 +43,14 @@
 \item [Multiple OS configurations.] Run multiple operating systems
   simultaneously, for instance for compatibility or QA purposes.
 \item [Server consolidation.] Move multiple servers onto a single
-  physical host with performance and fault isolation provided at
+  physical host with performance and fault isolation provided at the
   virtual machine boundaries.
 \item [Cluster computing.] Management at VM granularity provides more
   flexibility than separately managing each physical host, but better
   control and isolation than single-system image solutions,
   particularly by using live migration for load balancing.
 \item [Hardware support for custom OSes.] Allow development of new
-  OSes while benefiting from the wide-ranging hardware support of
+  OSes while benefitting from the wide-ranging hardware support of
   existing OSes such as Linux.
 \end{description}
 
@@ -58,44 +58,44 @@
 \section{Structure of a Xen-Based System}
 
 A Xen system has multiple layers, the lowest and most privileged of
-which is Xen itself. 
+which is Xen itself.
 
-Xen in turn may host multiple \emph{guest} operating systems, each of
-which is executed within a secure virtual machine (in Xen terminology,
-a \emph{domain}). Domains are scheduled by Xen to make effective use
-of the available physical CPUs.  Each guest OS manages its own
-applications, which includes responsibility for scheduling each
-application within the time allotted to the VM by Xen.
+Xen may host multiple \emph{guest} operating systems, each of which is
+executed within a secure virtual machine. In Xen terminology, a
+\emph{domain}. Domains are scheduled by Xen to make effective use of
+the available physical CPUs.  Each guest OS manages its own
+applications. This management includes the responsibility of
+scheduling each application within the time allotted to the VM by Xen.
 
-The first domain, \emph{domain 0}, is created automatically when the
-system boots and has special management privileges. Domain 0 builds
+The first domain, \emph{domain~0}, is created automatically when the
+system boots and has special management privileges. Domain~0 builds
 other domains and manages their virtual devices. It also performs
 administrative tasks such as suspending, resuming and migrating other
 virtual machines.
 
-Within domain 0, a process called \emph{xend} runs to manage the
-system.  \Xend is responsible for managing virtual machines and
-providing access to their consoles.  Commands are issued to \xend over
-an HTTP interface, either from a command-line tool or from a web
+Within domain~0, a process called \emph{xend} runs to manage the
+system.  \Xend\ is responsible for managing virtual machines and
+providing access to their consoles.  Commands are issued to \xend\ 
+over an HTTP interface, either from a command-line tool or from a web
 browser.
 
 
 \section{Hardware Support}
 
 Xen currently runs only on the x86 architecture, requiring a `P6' or
-newer processor (e.g. Pentium Pro, Celeron, Pentium II, Pentium III,
-Pentium IV, Xeon, AMD Athlon, AMD Duron).  Multiprocessor machines are
-supported, and we also have basic support for HyperThreading (SMT),
+newer processor (e.g.\ Pentium Pro, Celeron, Pentium~II, Pentium~III,
+Pentium~IV, Xeon, AMD~Athlon, AMD~Duron).  Multiprocessor machines are
+supported, and there is basic support for HyperThreading (SMT),
 although this remains a topic for ongoing research. A port
-specifically for x86/64 is in progress, although Xen already runs on
-such systems in 32-bit legacy mode. In addition a port to the IA64
+specifically for x86/64 is in progress. Xen already runs on such
+systems in 32-bit legacy mode. In addition, a port to the IA64
 architecture is approaching completion. We hope to add other
 architectures such as PPC and ARM in due course.
 
 Xen can currently use up to 4GB of memory.  It is possible for x86
 machines to address up to 64GB of physical memory but there are no
-current plans to support these systems: The x86/64 port is the planned
-route to supporting larger memory sizes.
+plans to support these systems: The x86/64 port is the planned route
+to supporting larger memory sizes.
 
 Xen offloads most of the hardware support issues to the guest OS
 running in Domain~0.  Xen itself contains only the code required to
@@ -112,23 +112,22 @@
 
 Xen was originally developed by the Systems Research Group at the
 University of Cambridge Computer Laboratory as part of the XenoServers
-project, funded by the UK-EPSRC.
+project, funded by the UK-EPSRC\@.
 
-XenoServers aim to provide a `public infrastructure for global
-distributed computing', and Xen plays a key part in that, allowing us
-to efficiently partition a single machine to enable multiple
-independent clients to run their operating systems and applications in
-an environment providing protection, resource isolation and
-accounting.  The project web page contains further information along
-with pointers to papers and technical reports:
+XenoServers aim to provide a ``public infrastructure for global
+distributed computing''. Xen plays a key part in that, allowing one to
+efficiently partition a single machine to enable multiple independent
+clients to run their operating systems and applications in an
+environment. This environment provides protection, resource isolation
+and accounting.  The project web page contains further information
+along with pointers to papers and technical reports:
 \path{http://www.cl.cam.ac.uk/xeno}
 
-Xen has since grown into a fully-fledged project in its own right,
-enabling us to investigate interesting research issues regarding the
-best techniques for virtualising resources such as the CPU, memory,
-disk and network.  The project has been bolstered by support from
-Intel Research Cambridge, and HP Labs, who are now working closely
-with us.
+Xen has grown into a fully-fledged project in its own right, enabling
+us to investigate interesting research issues regarding the best
+techniques for virtualising resources such as the CPU, memory, disk
+and network.  The project has been bolstered by support from Intel
+Research Cambridge and HP Labs, who are now working closely with us.
 
 Xen was first described in a paper presented at SOSP in
 2003\footnote{\tt
@@ -137,7 +136,7 @@
 significantly matured and is now used in production scenarios on many
 sites.
 
-Xen 2.0 features greatly enhanced hardware support, configuration
+Xen 3.0 features greatly enhanced hardware support, configuration
 flexibility, usability and a larger complement of supported operating
 systems. This latest release takes Xen a step closer to becoming the
 definitive open source solution for virtualisation.
diff -r e62c54ab862f -r 878a9891b056 docs/src/user/start_addl_dom.tex
--- a/docs/src/user/start_addl_dom.tex  Sat Nov 19 05:06:09 2005
+++ b/docs/src/user/start_addl_dom.tex  Sat Nov 19 05:16:29 2005
@@ -40,8 +40,7 @@
 a starting point:
 \begin{itemize}
 \item \path{/etc/xen/xmexample1} is a simple template configuration
-  file for describing a single VM.
-
+  file for describing a single VM\@.
 \item \path{/etc/xen/xmexample2} file is a template description that
   is intended to be reused for multiple virtual machines.  Setting the
   value of the \path{vmid} variable on the \path{xm} command line
@@ -54,17 +53,17 @@
 \begin{quote}
 \begin{description}
 \item[kernel] Set this to the path of the kernel you compiled for use
-  with Xen (e.g.\ \path{kernel = `/boot/vmlinuz-2.6-xenU'})
+  with Xen (e.g.\ \path{kernel = ``/boot/vmlinuz-2.6-xenU''})
 \item[memory] Set this to the size of the domain's memory in megabytes
   (e.g.\ \path{memory = 64})
 \item[disk] Set the first entry in this list to calculate the offset
-  of the domain's root partition, based on the domain ID.  Set the
+  of the domain's root partition, based on the domain ID\@.  Set the
   second to the location of \path{/usr} if you are sharing it between
-  domains (e.g.\ \path{disk = [`phy:your\_hard\_drive\%d,sda1,w' \%
+  domains (e.g.\ \path{disk = ['phy:your\_hard\_drive\%d,sda1,w' \%
     (base\_partition\_number + vmid),
-    `phy:your\_usr\_partition,sda6,r' ]}
+    'phy:your\_usr\_partition,sda6,r' ]}
 \item[dhcp] Uncomment the dhcp variable, so that the domain will
-  receive its IP address from a DHCP server (e.g.\ \path{dhcp=`dhcp'})
+  receive its IP address from a DHCP server (e.g.\ \path{dhcp=``dhcp''})
 \end{description}
 \end{quote}
 
@@ -72,7 +71,7 @@
 the MAC address of the virtual ethernet interface yourself.  For
 example:
 \begin{quote}
-\verb_vif = [`mac=00:06:AA:F6:BB:B3']_
+\verb_vif = ['mac=00:06:AA:F6:BB:B3']_
 \end{quote}
 If you do not set this variable, \xend\ will automatically generate a
 random MAC address from an unused range.
@@ -116,6 +115,7 @@
   section of the project's SourceForge site (see
   \path{http://sf.net/projects/xen/}).
 \item Create a configuration file like the following:
+  \begin{quote}
 \begin{verbatim}
 kernel = "/boot/vmlinuz-2.6-xenU"
 memory = 64
@@ -124,11 +124,14 @@
 ip = "1.2.3.4"
 disk = ['file:/path/to/ttylinux/rootfs,sda1,w']
 root = "/dev/sda1 ro"
-\end{verbatim}
+\end{verbatim}    
+  \end{quote}
 \item Now start the domain and connect to its console:
+  \begin{quote}
 \begin{verbatim}
 xm create configfile -c
 \end{verbatim}
+  \end{quote}
 \item Login as root, password root.
 \end{enumerate}
 
diff -r e62c54ab862f -r 878a9891b056 install.sh
--- a/install.sh        Sat Nov 19 05:06:09 2005
+++ b/install.sh        Sat Nov 19 05:16:29 2005
@@ -27,7 +27,7 @@
 cp -fdRL $src/etc/init.d/* $dst/etc/init.d/
 echo "All done."
 
-if [ -x /sbin/udev ] && [ ! -z `udev -V` ] && [ `/sbin/udev -V` -ge 059 ]; then
+if [ -x /sbin/udev ] && [ ! -z `/sbin/udev -V` ] && [ `/sbin/udev -V` -ge 059 
]; then
   cp -f $src/etc/udev/rules.d/*.rules $dst/etc/udev/rules.d/
 else
   cp -f $src/etc/hotplug/*.agent $dst/etc/hotplug/
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/kernel/cpu/common.c
--- a/linux-2.6-xen-sparse/arch/xen/i386/kernel/cpu/common.c    Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/kernel/cpu/common.c    Sat Nov 19 
05:16:29 2005
@@ -572,7 +572,7 @@
             va < gdt_descr->address + gdt_descr->size;
             va += PAGE_SIZE, f++) {
                frames[f] = virt_to_mfn(va);
-               make_page_readonly((void *)va);
+               make_lowmem_page_readonly((void *)va);
        }
        if (HYPERVISOR_set_gdt(frames, gdt_descr->size / 8))
                BUG();
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/kernel/entry.S
--- a/linux-2.6-xen-sparse/arch/xen/i386/kernel/entry.S Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/kernel/entry.S Sat Nov 19 05:16:29 2005
@@ -81,7 +81,7 @@
 #define evtchn_upcall_pending          /* 0 */
 #define evtchn_upcall_mask             1
 
-#define sizeof_vcpu_shift              3
+#define sizeof_vcpu_shift              4
 
 #ifdef CONFIG_SMP
 #define preempt_disable(reg)   incl TI_preempt_count(reg)
@@ -813,35 +813,9 @@
        pushl $do_alignment_check
        jmp error_code
 
-# This handler is special, because it gets an extra value on its stack,
-# which is the linear faulting address.
-# fastcall register usage:  %eax = pt_regs, %edx = error code,
-#                          %ecx = fault address
 ENTRY(page_fault)
-       pushl %ds
-       pushl %eax
-       xorl %eax, %eax
-       pushl %ebp
-       pushl %edi
-       pushl %esi
-       pushl %edx
-       decl %eax                       /* eax = -1 */
-       pushl %ecx
-       pushl %ebx
-       cld
-       pushl %es
-#      UNWIND_ESPFIX_STACK
-       popl %edi
-       movl ES(%esp), %ecx             /* get the faulting address */
-       movl ORIG_EAX(%esp), %edx       /* get the error code */
-       movl %eax, ORIG_EAX(%esp)
-       movl %edi, ES(%esp)
-       movl $(__KERNEL_DS),%eax
-       movl %eax, %ds
-       movl %eax, %es
-       movl %esp,%eax                  /* pt_regs pointer */
-       call do_page_fault
-       jmp ret_from_exception
+       pushl $do_page_fault
+       jmp error_code
 
 #ifdef CONFIG_X86_MCE
 ENTRY(machine_check)
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/kernel/pci-dma.c
--- a/linux-2.6-xen-sparse/arch/xen/i386/kernel/pci-dma.c       Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/kernel/pci-dma.c       Sat Nov 19 
05:16:29 2005
@@ -15,6 +15,7 @@
 #include <asm/io.h>
 #include <asm-xen/balloon.h>
 #include <asm/tlbflush.h>
+#include <asm/swiotlb.h>
 
 struct dma_coherent_mem {
        void            *virt_base;
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/kernel/traps.c
--- a/linux-2.6-xen-sparse/arch/xen/i386/kernel/traps.c Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/kernel/traps.c Sat Nov 19 05:16:29 2005
@@ -650,7 +650,7 @@
 
 static inline void conditional_sti(struct pt_regs *regs)
 {
-       if ((uint8_t)(regs->xcs >> 16) == 0)
+       if (regs->eflags & (X86_EFLAGS_IF|VM_MASK))
                local_irq_enable();
 }
 
@@ -972,7 +972,7 @@
 
 
 /*
- * NB. All these are "trap gates" (i.e. events_mask isn't cleared) except
+ * NB. All these are "trap gates" (i.e. events_mask isn't set) except
  * for those that specify <dpl>|4 in the second field.
  */
 static trap_info_t trap_table[] = {
@@ -988,7 +988,7 @@
        { 11, 0, __KERNEL_CS, (unsigned long)segment_not_present        },
        { 12, 0, __KERNEL_CS, (unsigned long)stack_segment              },
        { 13, 0, __KERNEL_CS, (unsigned long)general_protection         },
-       { 14, 0, __KERNEL_CS, (unsigned long)page_fault                 },
+       { 14, 0|4, __KERNEL_CS, (unsigned long)page_fault               },
        { 15, 0, __KERNEL_CS, (unsigned long)fixup_4gb_segment          },
        { 16, 0, __KERNEL_CS, (unsigned long)coprocessor_error          },
        { 17, 0, __KERNEL_CS, (unsigned long)alignment_check            },
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/mm/fault.c
--- a/linux-2.6-xen-sparse/arch/xen/i386/mm/fault.c     Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/mm/fault.c     Sat Nov 19 05:16:29 2005
@@ -208,6 +208,7 @@
 static void dump_fault_path(unsigned long address)
 {
        unsigned long *p, page;
+       unsigned long mfn; 
 
        preempt_disable();
        page = __pa(per_cpu(cur_pgd, smp_processor_id()));
@@ -217,20 +218,22 @@
        p += (address >> 30) * 2;
        printk(KERN_ALERT "%08lx -> *pde = %08lx:%08lx\n", page, p[1], p[0]);
        if (p[0] & 1) {
-               page = p[0] & PAGE_MASK;
+               mfn  = (p[0] >> PAGE_SHIFT) | ((p[1] & 0x7) << 20); 
+               page = mfn_to_pfn(mfn) << PAGE_SHIFT; 
+               p  = (unsigned long *)__va(page);
                address &= 0x3fffffff;
-               page = machine_to_phys(page);
-               p  = (unsigned long *)__va(page);
                p += (address >> 21) * 2;
-               printk(KERN_ALERT "%08lx -> *pme = %08lx:%08lx\n", page, p[1], 
p[0]);
+               printk(KERN_ALERT "%08lx -> *pme = %08lx:%08lx\n", 
+                      page, p[1], p[0]);
 #ifndef CONFIG_HIGHPTE
                if (p[0] & 1) {
-                       page = p[0] & PAGE_MASK;
+                       mfn  = (p[0] >> PAGE_SHIFT) | ((p[1] & 0x7) << 20); 
+                       page = mfn_to_pfn(mfn) << PAGE_SHIFT; 
+                       p  = (unsigned long *) __va(page);
                        address &= 0x001fffff;
-                       page = machine_to_phys(page);
-                       p  = (unsigned long *) __va(page);
                        p += (address >> 12) * 2;
-                       printk(KERN_ALERT "%08lx -> *pte = %08lx:%08lx\n", 
page, p[1], p[0]);
+                       printk(KERN_ALERT "%08lx -> *pte = %08lx:%08lx\n",
+                              page, p[1], p[0]);
                }
 #endif
        }
@@ -279,14 +282,17 @@
  *     bit 1 == 0 means read, 1 means write
  *     bit 2 == 0 means kernel, 1 means user-mode
  */
-fastcall void do_page_fault(struct pt_regs *regs, unsigned long error_code,
-                             unsigned long address)
+fastcall void do_page_fault(struct pt_regs *regs, unsigned long error_code)
 {
        struct task_struct *tsk;
        struct mm_struct *mm;
        struct vm_area_struct * vma;
+       unsigned long address;
        int write;
        siginfo_t info;
+
+       address = HYPERVISOR_shared_info->vcpu_data[
+               smp_processor_id()].arch.cr2;
 
        /* Set the "privileged fault" bit to something sane. */
        error_code &= ~4;
@@ -297,11 +303,9 @@
        if (notify_die(DIE_PAGE_FAULT, "page fault", regs, error_code, 14,
                                        SIGSEGV) == NOTIFY_STOP)
                return;
-#if 0
        /* It's safe to allow irq's after cr2 has been saved */
        if (regs->eflags & (X86_EFLAGS_IF|VM_MASK))
                local_irq_enable();
-#endif
 
        tsk = current;
 
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/mm/hypervisor.c
--- a/linux-2.6-xen-sparse/arch/xen/i386/mm/hypervisor.c        Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/mm/hypervisor.c        Sat Nov 19 
05:16:29 2005
@@ -37,16 +37,10 @@
 #include <asm-xen/balloon.h>
 #include <asm-xen/xen-public/memory.h>
 #include <linux/module.h>
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 #include <linux/percpu.h>
 #include <asm/tlbflush.h>
-#endif
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
-#define pte_offset_kernel pte_offset
-#define pud_t pgd_t
-#define pud_offset(d, va) d
-#elif defined(CONFIG_X86_64)
+
+#ifdef CONFIG_X86_64
 #define pmd_val_ma(v) (v).pmd
 #else
 #ifdef CONFIG_X86_PAE
@@ -342,8 +336,8 @@
                mfn = pte_mfn(*pte);
                BUG_ON(HYPERVISOR_update_va_mapping(
                        vstart + (i*PAGE_SIZE), __pte_ma(0), 0));
-               phys_to_machine_mapping[(__pa(vstart)>>PAGE_SHIFT)+i] =
-                       INVALID_P2M_ENTRY;
+               set_phys_to_machine((__pa(vstart)>>PAGE_SHIFT)+i,
+                       INVALID_P2M_ENTRY);
                BUG_ON(HYPERVISOR_memory_op(
                        XENMEM_decrease_reservation, &reservation) != 1);
        }
@@ -361,7 +355,7 @@
                        vstart + (i*PAGE_SIZE),
                        pfn_pte_ma(mfn+i, PAGE_KERNEL), 0));
                xen_machphys_update(mfn+i, (__pa(vstart)>>PAGE_SHIFT)+i);
-               phys_to_machine_mapping[(__pa(vstart)>>PAGE_SHIFT)+i] = mfn+i;
+               set_phys_to_machine((__pa(vstart)>>PAGE_SHIFT)+i, mfn+i);
        }
 
        flush_tlb_all();
@@ -383,7 +377,7 @@
                        vstart + (i*PAGE_SIZE),
                        pfn_pte_ma(mfn, PAGE_KERNEL), 0));
                xen_machphys_update(mfn, (__pa(vstart)>>PAGE_SHIFT)+i);
-               phys_to_machine_mapping[(__pa(vstart)>>PAGE_SHIFT)+i] = mfn;
+               set_phys_to_machine((__pa(vstart)>>PAGE_SHIFT)+i, mfn);
        }
 
        flush_tlb_all();
@@ -422,8 +416,8 @@
                mfn = pte_mfn(*pte);
                BUG_ON(HYPERVISOR_update_va_mapping(
                        vstart + (i*PAGE_SIZE), __pte_ma(0), 0));
-               phys_to_machine_mapping[(__pa(vstart)>>PAGE_SHIFT)+i] =
-                       INVALID_P2M_ENTRY;
+               set_phys_to_machine((__pa(vstart)>>PAGE_SHIFT)+i,
+                       INVALID_P2M_ENTRY);
                BUG_ON(HYPERVISOR_memory_op(
                        XENMEM_decrease_reservation, &reservation) != 1);
        }
@@ -436,7 +430,7 @@
                        vstart + (i*PAGE_SIZE),
                        pfn_pte_ma(mfn, PAGE_KERNEL), 0));
                xen_machphys_update(mfn, (__pa(vstart)>>PAGE_SHIFT)+i);
-               phys_to_machine_mapping[(__pa(vstart)>>PAGE_SHIFT)+i] = mfn;
+               set_phys_to_machine((__pa(vstart)>>PAGE_SHIFT)+i, mfn);
        }
 
        flush_tlb_all();
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/mm/init.c
--- a/linux-2.6-xen-sparse/arch/xen/i386/mm/init.c      Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/mm/init.c      Sat Nov 19 05:16:29 2005
@@ -68,7 +68,7 @@
 
 #ifdef CONFIG_X86_PAE
        pmd_table = (pmd_t *) alloc_bootmem_low_pages(PAGE_SIZE);
-       make_page_readonly(pmd_table);
+       make_lowmem_page_readonly(pmd_table);
        set_pgd(pgd, __pgd(__pa(pmd_table) | _PAGE_PRESENT));
        pud = pud_offset(pgd, 0);
        if (pmd_table != pmd_offset(pud, 0)) 
@@ -89,7 +89,7 @@
 {
        if (pmd_none(*pmd)) {
                pte_t *page_table = (pte_t *) 
alloc_bootmem_low_pages(PAGE_SIZE);
-               make_page_readonly(page_table);
+               make_lowmem_page_readonly(page_table);
                set_pmd(pmd, __pmd(__pa(page_table) | _PAGE_TABLE));
                if (page_table != pte_offset_kernel(pmd, 0))
                        BUG();  
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/mm/ioremap.c
--- a/linux-2.6-xen-sparse/arch/xen/i386/mm/ioremap.c   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/mm/ioremap.c   Sat Nov 19 05:16:29 2005
@@ -136,21 +136,19 @@
 }
 EXPORT_SYMBOL(direct_kernel_remap_pfn_range);
 
-/* FIXME: This is horribly broken on PAE */ 
 static int lookup_pte_fn(
        pte_t *pte, struct page *pte_page, unsigned long addr, void *data)
 {
-       unsigned long *ptep = (unsigned long *)data;
+       uint64_t *ptep = (uint64_t *)data;
        if (ptep)
-               *ptep = (pfn_to_mfn(page_to_pfn(pte_page)) <<
-                        PAGE_SHIFT) |
-                       ((unsigned long)pte & ~PAGE_MASK);
+               *ptep = ((uint64_t)pfn_to_mfn(page_to_pfn(pte_page)) <<
+                        PAGE_SHIFT) | ((unsigned long)pte & ~PAGE_MASK);
        return 0;
 }
 
 int create_lookup_pte_addr(struct mm_struct *mm, 
                           unsigned long address,
-                          unsigned long *ptep)
+                          uint64_t *ptep)
 {
        return generic_page_range(mm, address, PAGE_SIZE, lookup_pte_fn, ptep);
 }
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/i386/mm/pgtable.c
--- a/linux-2.6-xen-sparse/arch/xen/i386/mm/pgtable.c   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/i386/mm/pgtable.c   Sat Nov 19 05:16:29 2005
@@ -199,7 +199,7 @@
 {
        pte_t *pte = (pte_t 
*)__get_free_page(GFP_KERNEL|__GFP_REPEAT|__GFP_ZERO);
        if (pte)
-               make_page_readonly(pte);
+               make_lowmem_page_readonly(pte);
        return pte;
 }
 
@@ -336,7 +336,7 @@
                spin_lock_irqsave(&pgd_lock, flags);
                memcpy(pmd, copy_pmd, PAGE_SIZE);
                spin_unlock_irqrestore(&pgd_lock, flags);
-               make_page_readonly(pmd);
+               make_lowmem_page_readonly(pmd);
                set_pgd(&pgd[USER_PTRS_PER_PGD], __pgd(1 + __pa(pmd)));
        }
 
@@ -367,12 +367,12 @@
        if (PTRS_PER_PMD > 1) {
                for (i = 0; i < USER_PTRS_PER_PGD; ++i) {
                        pmd_t *pmd = (void *)__va(pgd_val(pgd[i])-1);
-                       make_page_writable(pmd);
+                       make_lowmem_page_writable(pmd);
                        kmem_cache_free(pmd_cache, pmd);
                }
                if (!HAVE_SHARED_KERNEL_PMD) {
                        pmd_t *pmd = (void 
*)__va(pgd_val(pgd[USER_PTRS_PER_PGD])-1);
-                       make_page_writable(pmd);
+                       make_lowmem_page_writable(pmd);
                        memset(pmd, 0, PTRS_PER_PMD*sizeof(pmd_t));
                        kmem_cache_free(pmd_cache, pmd);
                }
@@ -382,52 +382,62 @@
 }
 
 #ifndef CONFIG_XEN_SHADOW_MODE
+asmlinkage int xprintk(const char *fmt, ...);
 void make_lowmem_page_readonly(void *va)
 {
        pte_t *pte = virt_to_ptep(va);
-       set_pte(pte, pte_wrprotect(*pte));
+       int rc = HYPERVISOR_update_va_mapping(
+               (unsigned long)va, pte_wrprotect(*pte), 0);
+       BUG_ON(rc);
 }
 
 void make_lowmem_page_writable(void *va)
 {
        pte_t *pte = virt_to_ptep(va);
-       set_pte(pte, pte_mkwrite(*pte));
+       int rc = HYPERVISOR_update_va_mapping(
+               (unsigned long)va, pte_mkwrite(*pte), 0);
+       BUG_ON(rc);
 }
 
 void make_page_readonly(void *va)
 {
        pte_t *pte = virt_to_ptep(va);
-       set_pte(pte, pte_wrprotect(*pte));
-       if ( (unsigned long)va >= (unsigned long)high_memory )
-       {
-               unsigned long phys;
-               phys = machine_to_phys(*(unsigned long *)pte & PAGE_MASK);
+       int rc = HYPERVISOR_update_va_mapping(
+               (unsigned long)va, pte_wrprotect(*pte), 0);
+       if (rc) /* fallback? */
+               xen_l1_entry_update(pte, pte_wrprotect(*pte));
+       if ((unsigned long)va >= (unsigned long)high_memory) {
+               unsigned long pfn = pte_pfn(*pte);
 #ifdef CONFIG_HIGHMEM
-               if ( (phys >> PAGE_SHIFT) < highstart_pfn )
+               if (pfn >= highstart_pfn)
+                       kmap_flush_unused(); /* flush stale writable kmaps */
+               else
 #endif
-                       make_lowmem_page_readonly(phys_to_virt(phys));
+                       make_lowmem_page_readonly(
+                               phys_to_virt(pfn << PAGE_SHIFT)); 
        }
 }
 
 void make_page_writable(void *va)
 {
        pte_t *pte = virt_to_ptep(va);
-       set_pte(pte, pte_mkwrite(*pte));
-       if ( (unsigned long)va >= (unsigned long)high_memory )
-       {
-               unsigned long phys;
-               phys = machine_to_phys(*(unsigned long *)pte & PAGE_MASK);
+       int rc = HYPERVISOR_update_va_mapping(
+               (unsigned long)va, pte_mkwrite(*pte), 0);
+       if (rc) /* fallback? */
+               xen_l1_entry_update(pte, pte_mkwrite(*pte));
+       if ((unsigned long)va >= (unsigned long)high_memory) {
+               unsigned long pfn = pte_pfn(*pte); 
 #ifdef CONFIG_HIGHMEM
-               if ( (phys >> PAGE_SHIFT) < highstart_pfn )
+               if (pfn < highstart_pfn)
 #endif
-                       make_lowmem_page_writable(phys_to_virt(phys));
+                       make_lowmem_page_writable(
+                               phys_to_virt(pfn << PAGE_SHIFT)); 
        }
 }
 
 void make_pages_readonly(void *va, unsigned int nr)
 {
-       while ( nr-- != 0 )
-       {
+       while (nr-- != 0) {
                make_page_readonly(va);
                va = (void *)((unsigned long)va + PAGE_SIZE);
        }
@@ -435,8 +445,7 @@
 
 void make_pages_writable(void *va, unsigned int nr)
 {
-       while ( nr-- != 0 )
-       {
+       while (nr-- != 0) {
                make_page_writable(va);
                va = (void *)((unsigned long)va + PAGE_SIZE);
        }
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/kernel/devmem.c
--- a/linux-2.6-xen-sparse/arch/xen/kernel/devmem.c     Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/kernel/devmem.c     Sat Nov 19 05:16:29 2005
@@ -79,7 +79,7 @@
 
        if ((v = ioremap(p, count)) == NULL)
                return -EFAULT;
-       if (copy_to_user(v, buf, count))
+       if (copy_from_user(v, buf, count))
                goto out;
 
        written = count;
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/kernel/evtchn.c
--- a/linux-2.6-xen-sparse/arch/xen/kernel/evtchn.c     Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/kernel/evtchn.c     Sat Nov 19 05:16:29 2005
@@ -121,11 +121,7 @@
 
 /* Upcall to generic IRQ layer. */
 #ifdef CONFIG_X86
-#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,9)
 extern fastcall unsigned int do_IRQ(struct pt_regs *regs);
-#else
-extern asmlinkage unsigned int do_IRQ(struct pt_regs *regs);
-#endif
 #if defined (__i386__)
 #define IRQ_REG orig_eax
 #elif defined (__x86_64__)
@@ -752,7 +748,7 @@
                irq_bindcount[dynirq_to_irq(i)] = 0;
 
                irq_desc[dynirq_to_irq(i)].status  = IRQ_DISABLED;
-               irq_desc[dynirq_to_irq(i)].action  = 0;
+               irq_desc[dynirq_to_irq(i)].action  = NULL;
                irq_desc[dynirq_to_irq(i)].depth   = 1;
                irq_desc[dynirq_to_irq(i)].handler = &dynirq_type;
        }
@@ -770,7 +766,7 @@
 #endif
 
                irq_desc[pirq_to_irq(i)].status  = IRQ_DISABLED;
-               irq_desc[pirq_to_irq(i)].action  = 0;
+               irq_desc[pirq_to_irq(i)].action  = NULL;
                irq_desc[pirq_to_irq(i)].depth   = 1;
                irq_desc[pirq_to_irq(i)].handler = &pirq_type;
        }
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/kernel/reboot.c
--- a/linux-2.6-xen-sparse/arch/xen/kernel/reboot.c     Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/kernel/reboot.c     Sat Nov 19 05:16:29 2005
@@ -15,6 +15,7 @@
 #include <asm-xen/xenbus.h>
 #include <linux/cpu.h>
 #include <linux/kthread.h>
+#include <asm-xen/xencons.h>
 
 #define SHUTDOWN_INVALID  -1
 #define SHUTDOWN_POWEROFF  0
@@ -29,7 +30,6 @@
 void machine_restart(char * __unused)
 {
        /* We really want to get pending console data out before we die. */
-       extern void xencons_force_flush(void);
        xencons_force_flush();
        HYPERVISOR_sched_op(SCHEDOP_shutdown, SHUTDOWN_reboot);
 }
@@ -42,7 +42,6 @@
 void machine_power_off(void)
 {
        /* We really want to get pending console data out before we die. */
-       extern void xencons_force_flush(void);
        xencons_force_flush();
        HYPERVISOR_sched_op(SCHEDOP_shutdown, SHUTDOWN_poweroff);
 }
@@ -84,8 +83,6 @@
        cpumask_t prev_online_cpus;
        int vcpu_prepare(int vcpu);
 #endif
-
-       extern void xencons_resume(void);
 
        int err = 0;
 
@@ -185,12 +182,20 @@
 
        xencons_resume();
 
+#ifdef CONFIG_SMP
+       for_each_cpu(i)
+               vcpu_prepare(i);
+
+#endif
+
+       /* 
+       ** Only resume xenbus /after/ we've prepared our VCPUs; otherwise
+       ** the VCPU hotplug callback can race with our vcpu_prepare
+       */
        xenbus_resume();
 
+
 #ifdef CONFIG_SMP
-       for_each_present_cpu(i)
-               vcpu_prepare(i);
-
  out_reenable_cpus:
        for_each_cpu_mask(i, prev_online_cpus) {
                j = cpu_up(i);
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/kernel/skbuff.c
--- a/linux-2.6-xen-sparse/arch/xen/kernel/skbuff.c     Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/kernel/skbuff.c     Sat Nov 19 05:16:29 2005
@@ -17,7 +17,7 @@
 /* Referenced in netback.c. */
 /*static*/ kmem_cache_t *skbuff_cachep;
 
-#define MAX_SKBUFF_ORDER 2
+#define MAX_SKBUFF_ORDER 4
 static kmem_cache_t *skbuff_order_cachep[MAX_SKBUFF_ORDER + 1];
 
 static struct {
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/kernel/smpboot.c
--- a/linux-2.6-xen-sparse/arch/xen/kernel/smpboot.c    Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/kernel/smpboot.c    Sat Nov 19 05:16:29 2005
@@ -277,6 +277,18 @@
 
 #ifdef CONFIG_HOTPLUG_CPU
 
+/*
+ * Initialize cpu_present_map late to skip SMP boot code in init/main.c.
+ * But do it early enough to catch critical for_each_present_cpu() loops
+ * in i386-specific code.
+ */
+static int __init initialize_cpu_present_map(void)
+{
+       cpu_present_map = cpu_possible_map;
+       return 0;
+}
+core_initcall(initialize_cpu_present_map);
+
 static void vcpu_hotplug(unsigned int cpu)
 {
        int err;
@@ -293,7 +305,6 @@
        }
 
        if (strcmp(state, "online") == 0) {
-               cpu_set(cpu, cpu_present_map);
                (void)cpu_up(cpu);
        } else if (strcmp(state, "offline") == 0) {
                (void)cpu_down(cpu);
@@ -344,7 +355,7 @@
        return 0;
 }
 
-subsys_initcall(setup_vcpu_hotplug_event);
+arch_initcall(setup_vcpu_hotplug_event);
 
 int __cpu_disable(void)
 {
@@ -399,7 +410,8 @@
 
        xen_smp_intr_init(cpu);
        cpu_set(cpu, cpu_online_map);
-       HYPERVISOR_vcpu_op(VCPUOP_up, cpu, NULL);
+       if (HYPERVISOR_vcpu_op(VCPUOP_up, cpu, NULL) != 0)
+               BUG();
 
        return 0;
 }
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/kernel/xen_proc.c
--- a/linux-2.6-xen-sparse/arch/xen/kernel/xen_proc.c   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/kernel/xen_proc.c   Sat Nov 19 05:16:29 2005
@@ -1,6 +1,7 @@
 
 #include <linux/config.h>
 #include <linux/proc_fs.h>
+#include <asm-xen/xen_proc.h>
 
 static struct proc_dir_entry *xen_base;
 
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/x86_64/kernel/entry.S
--- a/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/entry.S       Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/entry.S       Sat Nov 19 
05:16:29 2005
@@ -874,42 +874,8 @@
        ret
        CFI_ENDPROC
 
-
- /*
- * Copy error_entry because of the different stack frame
- */                        
 ENTRY(page_fault)
-        movq (%rsp),%rcx
-        movq 8(%rsp),%r11
-        addq $0x10,%rsp         # now %rsp points to %cr2
-        pushq %rax
-        leaq do_page_fault(%rip),%rax
-       cld     
-       subq  $13*8,%rsp
-       movq %rdx,12*8(%rsp)    # save %rdx
-       movq 13*8(%rsp),%rdx    # load rax
-       movq %rcx,11*8(%rsp)
-       movq %rdx,10*8(%rsp)    # store rax
-        movq %rsi,13*8(%rsp)    # now save %rsi
-        movq 14*8(%rsp),%rdx    # load %cr2, 3rd argument
-       movq %r8, 9*8(%rsp)
-       movq %r9, 8*8(%rsp)
-       movq %r10,7*8(%rsp)
-       movq %r11,6*8(%rsp)
-       movq %rbx,5*8(%rsp) 
-       movq %rbp,4*8(%rsp) 
-       movq %r12,3*8(%rsp) 
-       movq %r13,2*8(%rsp) 
-       movq %r14,1*8(%rsp) 
-       movq %r15,(%rsp)
-#if 0        
-       cmpl $__KERNEL_CS,CS(%rsp)
-       je  error_kernelspace
-#endif
-        /*
-         * 1st and 2nd arguments are set by error_call_handler
-         */
-        jmp error_call_handler
+       errorentry do_page_fault
 
 ENTRY(coprocessor_error)
        zeroentry do_coprocessor_error
@@ -948,24 +914,15 @@
 paranoid_exit:
        testl %ebx,%ebx                         /* swapgs needed? */
        jnz paranoid_restore
+       testl $3,CS(%rsp)
+       jnz   paranoid_userspace
 paranoid_swapgs:       
-/*     swapgs */
+       swapgs
 paranoid_restore:      
        RESTORE_ALL 8
-/*     iretq */
+       iretq
 paranoid_userspace:    
        GET_THREAD_INFO(%rcx)
-#      movl threadinfo_flags(%rcx),%edx
-#      testl $_TIF_NEED_RESCHED,%edx
-#      jnz paranoid_resched
-#      testl $(_TIF_SIGPENDING|_TIF_NOTIFY_RESUME|_TIF_SINGLESTEP),%edx
-#      jnz paranoid_signal
-#      jmp paranoid_swapgs
-#paranoid_resched:             
-#/*    sti */
-#      call schedule
-#      jmp paranoid_exit
-#paranoid_signal:              
        movl threadinfo_flags(%rcx),%ebx
        andl $_TIF_WORK_MASK,%ebx
        jz paranoid_swapgs
@@ -975,13 +932,10 @@
        testl $_TIF_NEED_RESCHED,%ebx
        jnz paranoid_schedule
        movl %ebx,%edx                  /* arg3: thread flags */
-/*     sti */
-#      xorl %esi,%esi /* oldset */
-#      movq %rsp,%rdi /* &pt_regs */
+       sti
        xorl %esi,%esi                  /* arg2: oldset */
        movq %rsp,%rdi                  /* arg1: &pt_regs */
        call do_notify_resume
-#      jmp paranoid_exit
        cli
        jmp paranoid_userspace
 paranoid_schedule:
@@ -1057,4 +1011,3 @@
 ENTRY(call_debug)
        zeroentry do_call_debug
 
-
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/x86_64/kernel/setup.c
--- a/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/setup.c       Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/setup.c       Sat Nov 19 
05:16:29 2005
@@ -770,9 +770,9 @@
                pfn_to_mfn_frame_list_list = alloc_bootmem(PAGE_SIZE);
                HYPERVISOR_shared_info->arch.pfn_to_mfn_frame_list_list =
                  virt_to_mfn(pfn_to_mfn_frame_list_list);
-              
+
                fpp = PAGE_SIZE/sizeof(unsigned long);
-               for ( i=0, j=0, k=-1; i< max_pfn; i+=fpp, j++ )
+               for ( i=0, j=0, k=-1; i< end_pfn; i+=fpp, j++ )
                {
                        if ( (j % fpp) == 0 )
                        {
@@ -786,8 +786,11 @@
                        pfn_to_mfn_frame_list[k][j] = 
                                virt_to_mfn(&phys_to_machine_mapping[i]);
                }
-               HYPERVISOR_shared_info->arch.max_pfn = max_pfn;
-       }
+               HYPERVISOR_shared_info->arch.max_pfn = end_pfn;
+
+       }
+
+
 
        if ( ! (xen_start_info->flags & SIF_INITDOMAIN))
        {
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/x86_64/kernel/traps.c
--- a/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/traps.c       Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/traps.c       Sat Nov 19 
05:16:29 2005
@@ -905,30 +905,33 @@
 }
 
 
+/*
+ * NB. All these are "interrupt gates" (i.e. events_mask is set) because we
+ * specify <dpl>|4 in the second field.
+ */
 static trap_info_t trap_table[] = {
-        {  0, 0, (__KERNEL_CS|0x3), (unsigned long)divide_error               
},
-        {  1, 0, (__KERNEL_CS|0x3), (unsigned long)debug                      
},
-        {  3, 3, (__KERNEL_CS|0x3), (unsigned long)int3                       
},
-        {  4, 3, (__KERNEL_CS|0x3), (unsigned long)overflow                   
},
-        {  5, 3, (__KERNEL_CS|0x3), (unsigned long)bounds                     
},
-        {  6, 0, (__KERNEL_CS|0x3), (unsigned long)invalid_op                 
},
-        {  7, 0, (__KERNEL_CS|0x3), (unsigned long)device_not_available       
},
-        {  9, 0, (__KERNEL_CS|0x3), (unsigned 
long)coprocessor_segment_overrun},
-        { 10, 0, (__KERNEL_CS|0x3), (unsigned long)invalid_TSS                
},
-        { 11, 0, (__KERNEL_CS|0x3), (unsigned long)segment_not_present        
},
-        { 12, 0, (__KERNEL_CS|0x3), (unsigned long)stack_segment              
},
-        { 13, 0, (__KERNEL_CS|0x3), (unsigned long)general_protection         
},
-        { 14, 0, (__KERNEL_CS|0x3), (unsigned long)page_fault                 
},
-        { 15, 0, (__KERNEL_CS|0x3), (unsigned long)spurious_interrupt_bug     
},
-        { 16, 0, (__KERNEL_CS|0x3), (unsigned long)coprocessor_error          
},
-        { 17, 0, (__KERNEL_CS|0x3), (unsigned long)alignment_check            
},
+        {  0, 0|4, (__KERNEL_CS|0x3), (unsigned long)divide_error              
 },
+        {  1, 0|4, (__KERNEL_CS|0x3), (unsigned long)debug                     
 },
+        {  3, 3|4, (__KERNEL_CS|0x3), (unsigned long)int3                      
 },
+        {  4, 3|4, (__KERNEL_CS|0x3), (unsigned long)overflow                  
 },
+        {  5, 3|4, (__KERNEL_CS|0x3), (unsigned long)bounds                    
 },
+        {  6, 0|4, (__KERNEL_CS|0x3), (unsigned long)invalid_op                
 },
+        {  7, 0|4, (__KERNEL_CS|0x3), (unsigned long)device_not_available      
 },
+        {  9, 0|4, (__KERNEL_CS|0x3), (unsigned 
long)coprocessor_segment_overrun},
+        { 10, 0|4, (__KERNEL_CS|0x3), (unsigned long)invalid_TSS               
 },
+        { 11, 0|4, (__KERNEL_CS|0x3), (unsigned long)segment_not_present       
 },
+        { 12, 0|4, (__KERNEL_CS|0x3), (unsigned long)stack_segment             
 },
+        { 13, 0|4, (__KERNEL_CS|0x3), (unsigned long)general_protection        
 },
+        { 14, 0|4, (__KERNEL_CS|0x3), (unsigned long)page_fault                
 },
+        { 15, 0|4, (__KERNEL_CS|0x3), (unsigned long)spurious_interrupt_bug    
 },
+        { 16, 0|4, (__KERNEL_CS|0x3), (unsigned long)coprocessor_error         
 },
+        { 17, 0|4, (__KERNEL_CS|0x3), (unsigned long)alignment_check           
 },
 #ifdef CONFIG_X86_MCE
-        { 18, 0, (__KERNEL_CS|0x3), (unsigned long)machine_check              
},
-#endif
-        { 19, 0, (__KERNEL_CS|0x3), (unsigned long)simd_coprocessor_error     
},
-        { SYSCALL_VECTOR, 3, (__KERNEL_CS|0x3), (unsigned long)system_call   },
+        { 18, 0|4, (__KERNEL_CS|0x3), (unsigned long)machine_check             
 },
+#endif
+        { 19, 0|4, (__KERNEL_CS|0x3), (unsigned long)simd_coprocessor_error    
 },
 #ifdef CONFIG_IA32_EMULATION
-       { IA32_SYSCALL_VECTOR, 3, (__KERNEL_CS|0x3), (unsigned 
long)ia32_syscall},
+       { IA32_SYSCALL_VECTOR, 3|4, (__KERNEL_CS|0x3), (unsigned 
long)ia32_syscall},
 #endif
         {  0, 0,           0, 0                                              }
 };
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/x86_64/kernel/x8664_ksyms.c
--- a/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/x8664_ksyms.c Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/x8664_ksyms.c Sat Nov 19 
05:16:29 2005
@@ -128,8 +128,10 @@
 
 EXPORT_SYMBOL(rtc_lock);
 
-/* EXPORT_SYMBOL_GPL(set_nmi_callback);
-   EXPORT_SYMBOL_GPL(unset_nmi_callback); */
+#ifdef CONFIG_X86_LOCAL_APIC
+EXPORT_SYMBOL_GPL(set_nmi_callback);
+EXPORT_SYMBOL_GPL(unset_nmi_callback);
+#endif
 
 /* Export string functions. We normally rely on gcc builtin for most of these,
    but gcc sometimes decides not to inline them. */    
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/x86_64/kernel/xen_entry.S
--- a/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/xen_entry.S   Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/x86_64/kernel/xen_entry.S   Sat Nov 19 
05:16:29 2005
@@ -5,7 +5,7 @@
 #define evtchn_upcall_pending          0
 #define evtchn_upcall_mask             1
 
-#define sizeof_vcpu_shift              4
+#define sizeof_vcpu_shift              5
 
 #ifdef CONFIG_SMP
 //#define preempt_disable(reg) incl threadinfo_preempt_count(reg)
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/x86_64/mm/fault.c
--- a/linux-2.6-xen-sparse/arch/xen/x86_64/mm/fault.c   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/x86_64/mm/fault.c   Sat Nov 19 05:16:29 2005
@@ -318,12 +318,12 @@
  *     bit 2 == 0 means kernel, 1 means user-mode
  *      bit 3 == 1 means fault was an instruction fetch
  */
-asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long error_code,
-       unsigned long address)
+asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long error_code)
 {
        struct task_struct *tsk;
        struct mm_struct *mm;
        struct vm_area_struct * vma;
+       unsigned long address;
        const struct exception_table_entry *fixup;
        int write;
        siginfo_t info;
@@ -342,6 +342,11 @@
                }
        }
 #endif
+
+       /* get the address */
+       address = HYPERVISOR_shared_info->vcpu_data[
+               smp_processor_id()].arch.cr2;
+
        if (notify_die(DIE_PAGE_FAULT, "page fault", regs, error_code, 14,
                                        SIGSEGV) == NOTIFY_STOP)
                return;
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/arch/xen/x86_64/mm/init.c
--- a/linux-2.6-xen-sparse/arch/xen/x86_64/mm/init.c    Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/arch/xen/x86_64/mm/init.c    Sat Nov 19 05:16:29 2005
@@ -55,11 +55,9 @@
 DEFINE_PER_CPU(struct mmu_gather, mmu_gathers);
 extern unsigned long start_pfn;
 
-static int init_mapping_done;
-
 /*
  * Use this until direct mapping is established, i.e. before __va() is 
- * avaialble in init_memory_mapping().
+ * available in init_memory_mapping().
  */
 
 #define addr_to_page(addr, page)                               \
@@ -68,91 +66,65 @@
        (((mfn_to_pfn((addr) >> PAGE_SHIFT)) << PAGE_SHIFT) +   \
        __START_KERNEL_map)))
 
-static void __make_page_readonly(unsigned long va)
-{
-       unsigned long addr;
+static void early_make_page_readonly(void *va)
+{
+       unsigned long addr, _va = (unsigned long)va;
        pte_t pte, *ptep;
        unsigned long *page = (unsigned long *) init_level4_pgt;
 
-       addr = (unsigned long) page[pgd_index(va)];
+       addr = (unsigned long) page[pgd_index(_va)];
        addr_to_page(addr, page);
 
-       addr = page[pud_index(va)];
+       addr = page[pud_index(_va)];
        addr_to_page(addr, page);
 
-       addr = page[pmd_index(va)];
+       addr = page[pmd_index(_va)];
        addr_to_page(addr, page);
 
-       ptep = (pte_t *) &page[pte_index(va)];
-       pte.pte = (ptep->pte & ~_PAGE_RW);
-       xen_l1_entry_update(ptep, pte);
-       __flush_tlb_one(addr);
-}
-
-static void __make_page_writable(unsigned long va)
-{
-       unsigned long addr;
-       pte_t pte, *ptep;
-       unsigned long *page = (unsigned long *) init_level4_pgt;
-
-       addr = (unsigned long) page[pgd_index(va)];
-       addr_to_page(addr, page);
-
-       addr = page[pud_index(va)];
-       addr_to_page(addr, page);
- 
-       addr = page[pmd_index(va)];
-       addr_to_page(addr, page);
-
-       ptep = (pte_t *) &page[pte_index(va)];
-       pte.pte = (ptep->pte | _PAGE_RW);
-       xen_l1_entry_update(ptep, pte);
-       __flush_tlb_one(addr);
-}
-
-
-/*
- * Assume the translation is already established.
- */
+       ptep = (pte_t *) &page[pte_index(_va)];
+
+       pte.pte = ptep->pte & ~_PAGE_RW;
+       if (HYPERVISOR_update_va_mapping(_va, pte, 0))
+               BUG();
+}
+
 void make_page_readonly(void *va)
 {
-       pgd_t* pgd; pud_t *pud; pmd_t* pmd; pte_t pte, *ptep;
+       pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t pte, *ptep;
        unsigned long addr = (unsigned long) va;
 
-       if (!init_mapping_done) {
-               __make_page_readonly(addr);
-               return;
-       }
-  
        pgd = pgd_offset_k(addr);
        pud = pud_offset(pgd, addr);
        pmd = pmd_offset(pud, addr);
        ptep = pte_offset_kernel(pmd, addr);
-       pte.pte = (ptep->pte & ~_PAGE_RW);
-       xen_l1_entry_update(ptep, pte);
-       __flush_tlb_one(addr);
+
+       pte.pte = ptep->pte & ~_PAGE_RW;
+       if (HYPERVISOR_update_va_mapping(addr, pte, 0))
+               xen_l1_entry_update(ptep, pte); /* fallback */
+
+       if ((addr >= VMALLOC_START) && (addr < VMALLOC_END))
+               make_page_readonly(__va(pte_pfn(pte) << PAGE_SHIFT));
 }
 
 void make_page_writable(void *va)
 {
-       pgd_t* pgd; pud_t *pud; pmd_t* pmd; pte_t pte, *ptep;
+       pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t pte, *ptep;
        unsigned long addr = (unsigned long) va;
-
-       if (!init_mapping_done) {
-               __make_page_writable(addr);
-               return;
-       }
 
        pgd = pgd_offset_k(addr);
        pud = pud_offset(pgd, addr);
        pmd = pmd_offset(pud, addr);
        ptep = pte_offset_kernel(pmd, addr);
-       pte.pte = (ptep->pte | _PAGE_RW);
-       xen_l1_entry_update(ptep, pte);
-       __flush_tlb_one(addr);
-}
-
-void make_pages_readonly(void* va, unsigned nr)
+
+       pte.pte = ptep->pte | _PAGE_RW;
+       if (HYPERVISOR_update_va_mapping(addr, pte, 0))
+               xen_l1_entry_update(ptep, pte); /* fallback */
+
+       if ((addr >= VMALLOC_START) && (addr < VMALLOC_END))
+               make_page_writable(__va(pte_pfn(pte) << PAGE_SHIFT));
+}
+
+void make_pages_readonly(void *va, unsigned nr)
 {
        while (nr-- != 0) {
                make_page_readonly(va);
@@ -160,7 +132,7 @@
        }
 }
 
-void make_pages_writable(void* va, unsigned nr)
+void make_pages_writable(void *va, unsigned nr)
 {
        while (nr-- != 0) {
                make_page_writable(va);
@@ -457,7 +429,7 @@
                } 
 
                pmd = alloc_static_page(&pmd_phys);
-                make_page_readonly(pmd);
+                early_make_page_readonly(pmd);
                 xen_pmd_pin(pmd_phys);
                set_pud(pud, __pud(pmd_phys | _KERNPG_TABLE));
 
@@ -487,7 +459,7 @@
                                 __set_pte(pte, __pte(paddr | _KERNPG_TABLE));
                         }
                         pte = pte_save;
-                        make_page_readonly(pte);  
+                        early_make_page_readonly(pte);  
                         xen_pte_pin(pte_phys);
                        set_pmd(pmd, __pmd(pte_phys | _KERNPG_TABLE));
                }
@@ -536,11 +508,11 @@
                      _KERNPG_TABLE | _PAGE_USER);
         memcpy((void *)level2_kernel_pgt, page, PAGE_SIZE);
 
-       make_page_readonly(init_level4_pgt);
-       make_page_readonly(init_level4_user_pgt);
-       make_page_readonly(level3_kernel_pgt);
-       make_page_readonly(level3_user_pgt);
-       make_page_readonly(level2_kernel_pgt);
+       early_make_page_readonly(init_level4_pgt);
+       early_make_page_readonly(init_level4_user_pgt);
+       early_make_page_readonly(level3_kernel_pgt);
+       early_make_page_readonly(level3_user_pgt);
+       early_make_page_readonly(level2_kernel_pgt);
 
        xen_pgd_pin(__pa_symbol(init_level4_pgt));
        xen_pgd_pin(__pa_symbol(init_level4_user_pgt));
@@ -578,7 +550,7 @@
                pmd = (pmd_t *)&page[pmd_index(va)];
                if (pmd_none(*pmd)) {
                        pte_page = alloc_static_page(&phys);
-                       make_page_readonly(pte_page);
+                       early_make_page_readonly(pte_page);
                        xen_pte_pin(phys);
                        set_pmd(pmd, __pmd(phys | _KERNPG_TABLE | _PAGE_USER));
                } else {
@@ -625,7 +597,7 @@
        for (; start < end; start = next) {
                unsigned long pud_phys; 
                pud_t *pud = alloc_static_page(&pud_phys);
-               make_page_readonly(pud);
+               early_make_page_readonly(pud);
                xen_pud_pin(pud_phys);
                next = start + PGDIR_SIZE;
                if (next > end) 
@@ -640,7 +612,6 @@
        BUG_ON(start_pfn != (table_start + (tables_space >> PAGE_SHIFT)));
 
        __flush_tlb_all();
-       init_mapping_done = 1;
 }
 
 extern struct x8664_pda cpu_pda[NR_CPUS];
diff -r e62c54ab862f -r 878a9891b056 linux-2.6-xen-sparse/drivers/acpi/tables.c
--- a/linux-2.6-xen-sparse/drivers/acpi/tables.c        Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/acpi/tables.c        Sat Nov 19 05:16:29 2005
@@ -565,7 +565,7 @@
  * 
  * result: sdt_entry[] is initialized
  */
-#if CONFIG_XEN
+#if defined(CONFIG_XEN_X86) || defined(CONFIG_XEN_X86_64)
 #define acpi_rsdp_phys_to_va(rsdp_phys) (__fix_to_virt(FIX_ACPI_RSDP_PAGE) + \
                                           (rsdp_phys & ~PAGE_MASK))
 #else
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/char/tpm/tpm_xen.c
--- a/linux-2.6-xen-sparse/drivers/char/tpm/tpm_xen.c   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/char/tpm/tpm_xen.c   Sat Nov 19 05:16:29 2005
@@ -97,9 +97,7 @@
 transmission_set_buffer(struct transmission *t,
                         unsigned char *buffer, unsigned int len)
 {
-       if (NULL != t->request) {
-               kfree(t->request);
-       }
+       kfree(t->request);
        t->request = kmalloc(len, GFP_KERNEL);
        if (t->request) {
                memcpy(t->request,
@@ -113,12 +111,8 @@
 static inline void
 transmission_free(struct transmission *t)
 {
-       if (t->request) {
-               kfree(t->request);
-       }
-       if (t->rcv_buffer) {
-               kfree(t->rcv_buffer);
-       }
+       kfree(t->request);
+       kfree(t->rcv_buffer);
        kfree(t);
 }
 
@@ -444,7 +438,7 @@
        &dev_attr_pcrs.attr,
        &dev_attr_caps.attr,
        &dev_attr_cancel.attr,
-       0,
+       NULL,
 };
 
 static struct attribute_group xen_attr_grp = { .attrs = xen_attrs };
diff -r e62c54ab862f -r 878a9891b056 linux-2.6-xen-sparse/drivers/xen/Makefile
--- a/linux-2.6-xen-sparse/drivers/xen/Makefile Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/Makefile Sat Nov 19 05:16:29 2005
@@ -1,4 +1,5 @@
 
+obj-y  += net_driver_util.o
 obj-y  += util.o
 
 obj-y  += console/
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/balloon/balloon.c
--- a/linux-2.6-xen-sparse/drivers/xen/balloon/balloon.c        Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/balloon/balloon.c        Sat Nov 19 
05:16:29 2005
@@ -91,7 +91,6 @@
 static DECLARE_WORK(balloon_worker, balloon_process, NULL);
 static struct timer_list balloon_timer;
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 /* Use the private and mapping fields of struct page as a list. */
 #define PAGE_TO_LIST(p) ((struct list_head *)&p->private)
 #define LIST_TO_PAGE(l)                                \
@@ -102,19 +101,6 @@
                p->mapping = NULL;              \
                p->private = 0;                 \
        } while(0)
-#else
-/* There's a dedicated list field in struct page we can use.    */
-#define PAGE_TO_LIST(p) ( &p->list )
-#define LIST_TO_PAGE(l) ( list_entry(l, struct page, list) )
-#define UNLIST_PAGE(p)  ( list_del(&p->list) )
-#define pte_offset_kernel pte_offset
-#define pud_t pgd_t
-#define pud_offset(d, va) d
-#define pud_none(d) 0
-#define pud_bad(d) 0
-#define subsys_initcall(_fn) __initcall(_fn)
-#define pfn_to_page(_pfn) (mem_map + (_pfn))
-#endif
 
 #define IPRINTK(fmt, args...) \
        printk(KERN_INFO "xen_mem: " fmt, ##args)
@@ -210,7 +196,7 @@
                BUG_ON(phys_to_machine_mapping[pfn] != INVALID_P2M_ENTRY);
 
                /* Update P->M and M->P tables. */
-               phys_to_machine_mapping[pfn] = mfn_list[i];
+               set_phys_to_machine(pfn, mfn_list[i]);
                xen_machphys_update(mfn_list[i], pfn);
             
                /* Link back into the page tables if not highmem. */
@@ -295,7 +281,7 @@
        /* No more mappings: invalidate P2M and add to balloon. */
        for (i = 0; i < nr_pages; i++) {
                pfn = mfn_to_pfn(mfn_list[i]);
-               phys_to_machine_mapping[pfn] = INVALID_P2M_ENTRY;
+               set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
                balloon_append(pfn_to_page(pfn));
        }
 
@@ -381,9 +367,9 @@
     
 }
 
-int balloon_init_watcher(struct notifier_block *notifier,
-                         unsigned long event,
-                         void *data)
+static int balloon_init_watcher(struct notifier_block *notifier,
+                                unsigned long event,
+                                void *data)
 {
        int err;
 
@@ -515,8 +501,7 @@
                .domid        = DOMID_SELF
        };
        set_pte_at(&init_mm, addr, pte, __pte_ma(0));
-       phys_to_machine_mapping[__pa(addr) >> PAGE_SHIFT] =
-               INVALID_P2M_ENTRY;
+       set_phys_to_machine(__pa(addr) >> PAGE_SHIFT, INVALID_P2M_ENTRY);
        ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation, &reservation);
        BUG_ON(ret != 1);
        return 0;
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/blkback/blkback.c
--- a/linux-2.6-xen-sparse/drivers/xen/blkback/blkback.c        Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/blkback/blkback.c        Sat Nov 19 
05:16:29 2005
@@ -386,9 +386,9 @@
 #ifdef __ia64__
                        MMAP_VADDR(pending_idx,i) = gnttab_map_vaddr(map[i]);
 #else
-                       phys_to_machine_mapping[__pa(MMAP_VADDR(
-                               pending_idx, i)) >> PAGE_SHIFT] =
-                               FOREIGN_FRAME(map[i].dev_bus_addr>>PAGE_SHIFT);
+                       set_phys_to_machine(__pa(MMAP_VADDR(
+                               pending_idx, i)) >> PAGE_SHIFT,
+                               FOREIGN_FRAME(map[i].dev_bus_addr>>PAGE_SHIFT));
 #endif
                        fas        = req->frame_and_sects[i];
                        seg[i].buf = map[i].dev_bus_addr | 
@@ -543,7 +543,7 @@
        spin_lock_init(&blkio_schedule_list_lock);
        INIT_LIST_HEAD(&blkio_schedule_list);
 
-       ret = kernel_thread(blkio_schedule, 0, CLONE_FS | CLONE_FILES);
+       ret = kernel_thread(blkio_schedule, NULL, CLONE_FS | CLONE_FILES);
        BUG_ON(ret < 0);
 
        blkif_xenbus_init();
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/blkback/xenbus.c
--- a/linux-2.6-xen-sparse/drivers/xen/blkback/xenbus.c Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/blkback/xenbus.c Sat Nov 19 05:16:29 2005
@@ -1,5 +1,6 @@
 /*  Xenbus code for blkif backend
     Copyright (C) 2005 Rusty Russell <rusty@xxxxxxxxxxxxxxx>
+    Copyright (C) 2005 XenSource Ltd
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
@@ -15,161 +16,142 @@
     along with this program; if not, write to the Free Software
     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
+
+
 #include <stdarg.h>
 #include <linux/module.h>
 #include <asm-xen/xenbus.h>
 #include "common.h"
 
+
+#if 0
+#undef DPRINTK
+#define DPRINTK(fmt, args...) \
+    printk("blkback/xenbus (%s:%d) " fmt ".\n", __FUNCTION__, __LINE__, ##args)
+#endif
+
+
 struct backend_info
 {
        struct xenbus_device *dev;
-
-       /* our communications channel */
        blkif_t *blkif;
-
-       long int frontend_id;
+       struct xenbus_watch backend_watch;
+
        long int pdev;
        long int readonly;
-
-       /* watch back end for changes */
-       struct xenbus_watch backend_watch;
-
-       /* watch front end for changes */
-       struct xenbus_watch watch;
-       char *frontpath;
 };
 
+
+static void maybe_connect(struct backend_info *);
+static void connect(struct backend_info *);
+static int connect_ring(struct backend_info *);
+static void backend_changed(struct xenbus_watch *, const char **,
+                           unsigned int);
+
+
 static int blkback_remove(struct xenbus_device *dev)
 {
        struct backend_info *be = dev->data;
 
-       if (be->watch.node)
-               unregister_xenbus_watch(&be->watch);
-       unregister_xenbus_watch(&be->backend_watch);
-       if (be->blkif)
+       DPRINTK("");
+
+       if (be->backend_watch.node) {
+               unregister_xenbus_watch(&be->backend_watch);
+               kfree(be->backend_watch.node);
+               be->backend_watch.node = NULL;
+       }
+       if (be->blkif) {
                blkif_put(be->blkif);
-       if (be->frontpath)
-               kfree(be->frontpath);
+               be->blkif = NULL;
+       }
        kfree(be);
+       dev->data = NULL;
        return 0;
 }
 
-/* Front end tells us frame. */
-static void frontend_changed(struct xenbus_watch *watch,
-                            const char **vec, unsigned int len)
-{
-       unsigned long ring_ref;
-       unsigned int evtchn;
-       int err;
-       struct xenbus_transaction *xbt;
-       struct backend_info *be
-               = container_of(watch, struct backend_info, watch);
-
-       /* If other end is gone, delete ourself. */
-       if (vec && !xenbus_exists(NULL, be->frontpath, "")) {
-               device_unregister(&be->dev->dev);
-               return;
-       }
-       if (be->blkif == NULL || be->blkif->status == CONNECTED)
-               return;
-
-       err = xenbus_gather(NULL, be->frontpath, "ring-ref", "%lu", &ring_ref,
-                           "event-channel", "%u", &evtchn, NULL);
-       if (err) {
-               xenbus_dev_error(be->dev, err,
-                                "reading %s/ring-ref and event-channel",
-                                be->frontpath);
-               return;
-       }
-
-       /* Map the shared frame, irq etc. */
-       err = blkif_map(be->blkif, ring_ref, evtchn);
-       if (err) {
-               xenbus_dev_error(be->dev, err,
-                                "mapping ring-ref %lu port %u",
-                                ring_ref, evtchn);
-               return;
-       }
-       /* XXX From here on should 'blkif_unmap' on error. */
-
-again:
-       /* Supply the information about the device the frontend needs */
-       xbt = xenbus_transaction_start();
-       if (IS_ERR(xbt)) {
-               xenbus_dev_error(be->dev, err, "starting transaction");
-               return;
-       }
-
-       err = xenbus_printf(xbt, be->dev->nodename, "sectors", "%lu",
-                           vbd_size(&be->blkif->vbd));
-       if (err) {
-               xenbus_dev_error(be->dev, err, "writing %s/sectors",
-                                be->dev->nodename);
-               goto abort;
-       }
-
-       /* FIXME: use a typename instead */
-       err = xenbus_printf(xbt, be->dev->nodename, "info", "%u",
-                           vbd_info(&be->blkif->vbd));
-       if (err) {
-               xenbus_dev_error(be->dev, err, "writing %s/info",
-                                be->dev->nodename);
-               goto abort;
-       }
-       err = xenbus_printf(xbt, be->dev->nodename, "sector-size", "%lu",
-                           vbd_secsize(&be->blkif->vbd));
-       if (err) {
-               xenbus_dev_error(be->dev, err, "writing %s/sector-size",
-                                be->dev->nodename);
-               goto abort;
-       }
-
-       err = xenbus_transaction_end(xbt, 0);
-       if (err == -EAGAIN)
-               goto again;
-       if (err) {
-               xenbus_dev_error(be->dev, err, "ending transaction",
-                                ring_ref, evtchn);
-               goto abort;
-       }
-
-       xenbus_dev_ok(be->dev);
-
-       return;
-
- abort:
-       xenbus_transaction_end(xbt, 1);
-}
-
-/* 
-   Setup supplies physical device.  
-   We provide event channel and device details to front end.
-   Frontend supplies shared frame and event channel.
+
+/**
+ * Entry point to this code when a new device is created.  Allocate the basic
+ * structures, and watch the store waiting for the hotplug scripts to tell us
+ * the device's physical-device.  Switch to InitWait.
+ */
+static int blkback_probe(struct xenbus_device *dev,
+                        const struct xenbus_device_id *id)
+{
+       int err;
+       struct backend_info *be = kmalloc(sizeof(struct backend_info),
+                                         GFP_KERNEL);
+       if (!be) {
+               xenbus_dev_fatal(dev, -ENOMEM,
+                                "allocating backend structure");
+               return -ENOMEM;
+       }
+       memset(be, 0, sizeof(*be));
+
+       be->dev = dev;
+       dev->data = be;
+
+       be->blkif = alloc_blkif(dev->otherend_id);
+       if (IS_ERR(be->blkif)) {
+               err = PTR_ERR(be->blkif);
+               be->blkif = NULL;
+               xenbus_dev_fatal(dev, err, "creating block interface");
+               goto fail;
+       }
+
+       err = xenbus_watch_path2(dev, dev->nodename, "physical-device",
+                                &be->backend_watch, backend_changed);
+       if (err)
+               goto fail;
+
+       err = xenbus_switch_state(dev, NULL, XenbusStateInitWait);
+       if (err)
+               goto fail;
+
+       return 0;
+
+fail:
+       DPRINTK("failed");
+       blkback_remove(dev);
+       return err;
+}
+
+
+/**
+ * Callback received when the hotplug scripts have placed the physical-device
+ * node.  Read it and the read-only node, and create a vbd.  If the frontend
+ * is ready, connect.
  */
 static void backend_changed(struct xenbus_watch *watch,
                            const char **vec, unsigned int len)
 {
        int err;
        char *p;
-       long int handle, pdev;
+       long pdev;
        struct backend_info *be
                = container_of(watch, struct backend_info, backend_watch);
        struct xenbus_device *dev = be->dev;
 
+       DPRINTK("");
+
        err = xenbus_scanf(NULL, dev->nodename,
                           "physical-device", "%li", &pdev);
-       if (XENBUS_EXIST_ERR(err))
+       if (XENBUS_EXIST_ERR(err)) {
+               /* Since this watch will fire once immediately after it is
+                  registered, we expect this.  Ignore it, and wait for the
+                  hotplug scripts. */
                return;
-       if (err < 0) {
-               xenbus_dev_error(dev, err, "reading physical-device");
+       }
+       if (err != 1) {
+               xenbus_dev_fatal(dev, err, "reading physical-device");
                return;
        }
        if (be->pdev && be->pdev != pdev) {
                printk(KERN_WARNING
-                      "changing physical-device not supported\n");
+                      "blkback: changing physical-device (from %ld to %ld) "
+                      "not supported.\n", be->pdev, pdev);
                return;
        }
-       be->pdev = pdev;
 
        /* If there's a read-only node, we're read only. */
        p = xenbus_read(NULL, dev->nodename, "read-only", NULL);
@@ -178,112 +160,181 @@
                kfree(p);
        }
 
-       if (be->blkif == NULL) {
+       if (be->pdev == 0L) {
                /* Front end dir is a number, which is used as the handle. */
-               p = strrchr(be->frontpath, '/') + 1;
+
+               long handle;
+
+               p = strrchr(dev->otherend, '/') + 1;
                handle = simple_strtoul(p, NULL, 0);
 
-               be->blkif = alloc_blkif(be->frontend_id);
-               if (IS_ERR(be->blkif)) {
-                       err = PTR_ERR(be->blkif);
-                       be->blkif = NULL;
-                       xenbus_dev_error(dev, err,
-                                        "creating block interface");
-                       return;
-               }
+               be->pdev = pdev;
 
                err = vbd_create(be->blkif, handle, be->pdev, be->readonly);
                if (err) {
-                       blkif_put(be->blkif);
-                       be->blkif = NULL;
-                       xenbus_dev_error(dev, err,
+                       be->pdev = 0L;
+                       xenbus_dev_fatal(dev, err,
                                         "creating vbd structure");
                        return;
                }
 
-               /* Pass in NULL node to skip exist test. */
-               frontend_changed(&be->watch, NULL, 0);
-       }
-}
-
-static int blkback_probe(struct xenbus_device *dev,
-                        const struct xenbus_device_id *id)
-{
-       struct backend_info *be;
-       char *frontend;
-       int err;
-
-       be = kmalloc(sizeof(*be), GFP_KERNEL);
-       if (!be) {
-               xenbus_dev_error(dev, -ENOMEM,
-                                "allocating backend structure");
-               return -ENOMEM;
-       }
-       memset(be, 0, sizeof(*be));
-
-       frontend = NULL;
-       err = xenbus_gather(NULL, dev->nodename,
-                           "frontend-id", "%li", &be->frontend_id,
-                           "frontend", NULL, &frontend,
-                           NULL);
-       if (XENBUS_EXIST_ERR(err))
-               goto free_be;
-       if (err < 0) {
-               xenbus_dev_error(dev, err,
-                                "reading %s/frontend or frontend-id",
+               maybe_connect(be);
+       }
+}
+
+
+/**
+ * Callback received when the frontend's state changes.
+ */
+static void frontend_changed(struct xenbus_device *dev,
+                            XenbusState frontend_state)
+{
+       struct backend_info *be = dev->data;
+       int err;
+
+       DPRINTK("");
+
+       switch (frontend_state) {
+       case XenbusStateInitialising:
+       case XenbusStateConnected:
+               break;
+
+       case XenbusStateInitialised:
+               err = connect_ring(be);
+               if (err) {
+                       return;
+               }
+               maybe_connect(be);
+               break;
+
+       case XenbusStateClosing:
+               xenbus_switch_state(dev, NULL, XenbusStateClosing);
+               break;
+
+       case XenbusStateClosed:
+               device_unregister(&dev->dev);
+               break;
+
+       case XenbusStateUnknown:
+       case XenbusStateInitWait:
+       default:
+               xenbus_dev_fatal(dev, -EINVAL, "saw state %d at frontend",
+                                frontend_state);
+               break;
+       }
+}
+
+
+/* ** Connection ** */
+
+
+static void maybe_connect(struct backend_info *be)
+{
+       if (be->pdev != 0L && be->blkif->status == CONNECTED) {
+               connect(be);
+       }
+}
+
+
+/**
+ * Write the physical details regarding the block device to the store, and
+ * switch to Connected state.
+ */
+static void connect(struct backend_info *be)
+{
+       struct xenbus_transaction *xbt;
+       int err;
+       struct xenbus_device *dev = be->dev;
+
+       DPRINTK("%s", dev->otherend);
+
+       /* Supply the information about the device the frontend needs */
+again:
+       xbt = xenbus_transaction_start();
+
+       if (IS_ERR(xbt)) {
+               err = PTR_ERR(xbt);
+               xenbus_dev_fatal(dev, err, "starting transaction");
+               return;
+       }
+
+       err = xenbus_printf(xbt, dev->nodename, "sectors", "%lu",
+                           vbd_size(&be->blkif->vbd));
+       if (err) {
+               xenbus_dev_fatal(dev, err, "writing %s/sectors",
                                 dev->nodename);
-               goto free_be;
-       }
-       if (strlen(frontend) == 0 || !xenbus_exists(NULL, frontend, "")) {
-               /* If we can't get a frontend path and a frontend-id,
-                * then our bus-id is no longer valid and we need to
-                * destroy the backend device.
-                */
-               err = -ENOENT;
-               goto free_be;
-       }
-
-       be->dev = dev;
-       be->backend_watch.node = dev->nodename;
-       be->backend_watch.callback = backend_changed;
-       /* Will implicitly call backend_changed once. */
-       err = register_xenbus_watch(&be->backend_watch);
-       if (err) {
-               be->backend_watch.node = NULL;
-               xenbus_dev_error(dev, err,
-                                "adding backend watch on %s",
+               goto abort;
+       }
+
+       /* FIXME: use a typename instead */
+       err = xenbus_printf(xbt, dev->nodename, "info", "%u",
+                           vbd_info(&be->blkif->vbd));
+       if (err) {
+               xenbus_dev_fatal(dev, err, "writing %s/info",
                                 dev->nodename);
-               goto free_be;
-       }
-
-       be->frontpath = frontend;
-       be->watch.node = be->frontpath;
-       be->watch.callback = frontend_changed;
-       err = register_xenbus_watch(&be->watch);
-       if (err) {
-               be->watch.node = NULL;
-               xenbus_dev_error(dev, err,
-                                "adding frontend watch on %s",
-                                be->frontpath);
-               goto free_be;
-       }
-
-       dev->data = be;
+               goto abort;
+       }
+       err = xenbus_printf(xbt, dev->nodename, "sector-size", "%lu",
+                           vbd_secsize(&be->blkif->vbd));
+       if (err) {
+               xenbus_dev_fatal(dev, err, "writing %s/sector-size",
+                                dev->nodename);
+               goto abort;
+       }
+
+       err = xenbus_switch_state(dev, xbt, XenbusStateConnected);
+       if (err)
+               goto abort;
+
+       err = xenbus_transaction_end(xbt, 0);
+       if (err == -EAGAIN)
+               goto again;
+       if (err)
+               xenbus_dev_fatal(dev, err, "ending transaction");
+       return;
+ abort:
+       xenbus_transaction_end(xbt, 1);
+}
+
+
+static int connect_ring(struct backend_info *be)
+{
+       struct xenbus_device *dev = be->dev;
+       unsigned long ring_ref;
+       unsigned int evtchn;
+       int err;
+
+       DPRINTK("%s", dev->otherend);
+
+       err = xenbus_gather(NULL, dev->otherend, "ring-ref", "%lu", &ring_ref,
+                           "event-channel", "%u", &evtchn, NULL);
+       if (err) {
+               xenbus_dev_fatal(dev, err,
+                                "reading %s/ring-ref and event-channel",
+                                dev->otherend);
+               return err;
+       }
+
+       /* Map the shared frame, irq etc. */
+       err = blkif_map(be->blkif, ring_ref, evtchn);
+       if (err) {
+               xenbus_dev_fatal(dev, err, "mapping ring-ref %lu port %u",
+                                ring_ref, evtchn);
+               return err;
+       }
+
        return 0;
-
- free_be:
-       if (be->backend_watch.node)
-               unregister_xenbus_watch(&be->backend_watch);
-       if (frontend)
-               kfree(frontend);
-       kfree(be);
-       return err;
-}
+}
+
+
+/* ** Driver Registration ** */
+
 
 static struct xenbus_device_id blkback_ids[] = {
        { "vbd" },
        { "" }
 };
+
 
 static struct xenbus_driver blkback = {
        .name = "vbd",
@@ -291,12 +342,15 @@
        .ids = blkback_ids,
        .probe = blkback_probe,
        .remove = blkback_remove,
+       .otherend_changed = frontend_changed
 };
 
+
 void blkif_xenbus_init(void)
 {
        xenbus_register_backend(&blkback);
 }
+
 
 /*
  * Local variables:
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/blkfront/blkfront.c
--- a/linux-2.6-xen-sparse/drivers/xen/blkfront/blkfront.c      Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/blkfront/blkfront.c      Sat Nov 19 
05:16:29 2005
@@ -8,6 +8,7 @@
  * Copyright (c) 2004, Christian Limpach
  * Copyright (c) 2004, Andrew Warfield
  * Copyright (c) 2005, Christopher Clark
+ * Copyright (c) 2005, XenSource Ltd
  * 
  * This file may be distributed separately from the Linux kernel, or
  * incorporated into other software packages, subject to the following license:
@@ -31,6 +32,7 @@
  * IN THE SOFTWARE.
  */
 
+
 #if 1
 #define ASSERT(p)                                                         \
        if (!(p)) { printk("Assertion '%s' failed, line %d, file %s", #p , \
@@ -38,6 +40,7 @@
 #else
 #define ASSERT(_p)
 #endif
+
 
 #include <linux/version.h>
 #include "block.h"
@@ -51,16 +54,315 @@
 #include <asm-xen/gnttab.h>
 #include <asm/hypervisor.h>
 
+
 #define BLKIF_STATE_DISCONNECTED 0
 #define BLKIF_STATE_CONNECTED    1
+#define BLKIF_STATE_SUSPENDED    2
 
 #define MAXIMUM_OUTSTANDING_BLOCK_REQS \
     (BLKIF_MAX_SEGMENTS_PER_REQUEST * BLKIF_RING_SIZE)
 #define GRANT_INVALID_REF      0
 
-static void kick_pending_request_queues(struct blkfront_info *info);
-
-static void blkif_completion(struct blk_shadow *s);
+
+static void connect(struct blkfront_info *);
+static void blkfront_closing(struct xenbus_device *);
+static int blkfront_remove(struct xenbus_device *);
+static int talk_to_backend(struct xenbus_device *, struct blkfront_info *);
+static int setup_blkring(struct xenbus_device *, struct blkfront_info *);
+
+static void kick_pending_request_queues(struct blkfront_info *);
+
+static irqreturn_t blkif_int(int irq, void *dev_id, struct pt_regs *ptregs);
+static void blkif_restart_queue(void *arg);
+static void blkif_recover(struct blkfront_info *);
+static void blkif_completion(struct blk_shadow *);
+static void blkif_free(struct blkfront_info *, int);
+
+
+/**
+ * Entry point to this code when a new device is created.  Allocate the basic
+ * structures and the ring buffer for communication with the backend, and
+ * inform the backend of the appropriate details for those.  Switch to
+ * Initialised state.
+ */
+static int blkfront_probe(struct xenbus_device *dev,
+                         const struct xenbus_device_id *id)
+{
+       int err, vdevice, i;
+       struct blkfront_info *info;
+
+       /* FIXME: Use dynamic device id if this is not set. */
+       err = xenbus_scanf(NULL, dev->nodename,
+                          "virtual-device", "%i", &vdevice);
+       if (err != 1) {
+               xenbus_dev_fatal(dev, err, "reading virtual-device");
+               return err;
+       }
+
+       info = kmalloc(sizeof(*info), GFP_KERNEL);
+       if (!info) {
+               xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
+               return -ENOMEM;
+       }
+       info->xbdev = dev;
+       info->vdevice = vdevice;
+       info->connected = BLKIF_STATE_DISCONNECTED;
+       info->mi = NULL;
+       info->gd = NULL;
+       INIT_WORK(&info->work, blkif_restart_queue, (void *)info);
+
+       info->shadow_free = 0;
+       memset(info->shadow, 0, sizeof(info->shadow));
+       for (i = 0; i < BLK_RING_SIZE; i++)
+               info->shadow[i].req.id = i+1;
+       info->shadow[BLK_RING_SIZE-1].req.id = 0x0fffffff;
+
+       /* Front end dir is a number, which is used as the id. */
+       info->handle = simple_strtoul(strrchr(dev->nodename,'/')+1, NULL, 0);
+       dev->data = info;
+
+       err = talk_to_backend(dev, info);
+       if (err) {
+               kfree(info);
+               dev->data = NULL;
+               return err;
+       }
+
+       return 0;
+}
+
+
+/**
+ * We are reconnecting to the backend, due to a suspend/resume, or a backend
+ * driver restart.  We tear down our blkif structure and recreate it, but
+ * leave the device-layer structures intact so that this is transparent to the
+ * rest of the kernel.
+ */
+static int blkfront_resume(struct xenbus_device *dev)
+{
+       struct blkfront_info *info = dev->data;
+       int err;
+
+       DPRINTK("blkfront_resume: %s\n", dev->nodename);
+
+       blkif_free(info, 1);
+
+       err = talk_to_backend(dev, info);
+       if (!err)
+               blkif_recover(info);
+
+       return err;
+}
+
+
+/* Common code used when first setting up, and when resuming. */
+static int talk_to_backend(struct xenbus_device *dev,
+                          struct blkfront_info *info)
+{
+       const char *message = NULL;
+       struct xenbus_transaction *xbt;
+       int err;
+
+       /* Create shared ring, alloc event channel. */
+       err = setup_blkring(dev, info);
+       if (err)
+               goto out;
+
+again:
+       xbt = xenbus_transaction_start();
+       if (IS_ERR(xbt)) {
+               xenbus_dev_fatal(dev, err, "starting transaction");
+               goto destroy_blkring;
+       }
+
+       err = xenbus_printf(xbt, dev->nodename,
+                           "ring-ref","%u", info->ring_ref);
+       if (err) {
+               message = "writing ring-ref";
+               goto abort_transaction;
+       }
+       err = xenbus_printf(xbt, dev->nodename,
+                           "event-channel", "%u", info->evtchn);
+       if (err) {
+               message = "writing event-channel";
+               goto abort_transaction;
+       }
+
+       err = xenbus_switch_state(dev, xbt, XenbusStateInitialised);
+       if (err) {
+               goto abort_transaction;
+       }
+
+       err = xenbus_transaction_end(xbt, 0);
+       if (err) {
+               if (err == -EAGAIN)
+                       goto again;
+               xenbus_dev_fatal(dev, err, "completing transaction");
+               goto destroy_blkring;
+       }
+
+       return 0;
+
+ abort_transaction:
+       xenbus_transaction_end(xbt, 1);
+       if (message)
+               xenbus_dev_fatal(dev, err, "%s", message);
+ destroy_blkring:
+       blkif_free(info, 0);
+ out:
+       return err;
+}
+
+
+static int setup_blkring(struct xenbus_device *dev,
+                        struct blkfront_info *info)
+{
+       blkif_sring_t *sring;
+       int err;
+
+       info->ring_ref = GRANT_INVALID_REF;
+
+       sring = (blkif_sring_t *)__get_free_page(GFP_KERNEL);
+       if (!sring) {
+               xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
+               return -ENOMEM;
+       }
+       SHARED_RING_INIT(sring);
+       FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
+
+       err = xenbus_grant_ring(dev, virt_to_mfn(info->ring.sring));
+       if (err < 0) {
+               free_page((unsigned long)sring);
+               info->ring.sring = NULL;
+               goto fail;
+       }
+       info->ring_ref = err;
+
+       err = xenbus_alloc_evtchn(dev, &info->evtchn);
+       if (err)
+               goto fail;
+
+       err = bind_evtchn_to_irqhandler(
+               info->evtchn, blkif_int, SA_SAMPLE_RANDOM, "blkif", info);
+       if (err <= 0) {
+               xenbus_dev_fatal(dev, err,
+                                "bind_evtchn_to_irqhandler failed");
+               goto fail;
+       }
+       info->irq = err;
+
+       return 0;
+fail:
+       blkif_free(info, 0);
+       return err;
+}
+
+
+/**
+ * Callback received when the backend's state changes.
+ */
+static void backend_changed(struct xenbus_device *dev,
+                           XenbusState backend_state)
+{
+       struct blkfront_info *info = dev->data;
+
+       DPRINTK("blkfront:backend_changed.\n");
+
+       switch (backend_state) {
+       case XenbusStateUnknown:
+       case XenbusStateInitialising:
+       case XenbusStateInitWait:
+       case XenbusStateInitialised:
+       case XenbusStateClosed:
+               break;
+
+       case XenbusStateConnected:
+               connect(info);
+               break;
+
+       case XenbusStateClosing:
+               blkfront_closing(dev);
+               break;
+       }
+}
+
+
+/* ** Connection ** */
+
+
+static void connect(struct blkfront_info *info)
+{
+       unsigned long sectors, sector_size;
+       unsigned int binfo;
+       int err;
+
+        if( (info->connected == BLKIF_STATE_CONNECTED) || 
+           (info->connected == BLKIF_STATE_SUSPENDED) ) 
+               return;
+
+       DPRINTK("blkfront.c:connect:%s.\n", info->xbdev->otherend);
+
+       err = xenbus_gather(NULL, info->xbdev->otherend,
+                           "sectors", "%lu", &sectors,
+                           "info", "%u", &binfo,
+                           "sector-size", "%lu", &sector_size,
+                           NULL);
+       if (err) {
+               xenbus_dev_fatal(info->xbdev, err,
+                                "reading backend fields at %s",
+                                info->xbdev->otherend);
+               return;
+       }
+       
+        info->connected = BLKIF_STATE_CONNECTED;
+        xlvbd_add(sectors, info->vdevice, binfo, sector_size, info);
+       
+       err = xenbus_switch_state(info->xbdev, NULL, XenbusStateConnected);
+       if (err)
+               return;
+       
+       /* Kick pending requests. */
+       spin_lock_irq(&blkif_io_lock);
+       kick_pending_request_queues(info);
+       spin_unlock_irq(&blkif_io_lock);
+}
+
+
+/**
+ * Handle the change of state of the backend to Closing.  We must delete our
+ * device-layer structures now, to ensure that writes are flushed through to
+ * the backend.  Once is this done, we can switch to Closed in
+ * acknowledgement.
+ */
+static void blkfront_closing(struct xenbus_device *dev)
+{
+       struct blkfront_info *info = dev->data;
+
+       DPRINTK("blkfront_closing: %s removed\n", dev->nodename);
+
+       if (info->mi) {
+               DPRINTK("Calling xlvbd_del\n");
+               xlvbd_del(info);
+               info->mi = NULL;
+       }
+
+       xenbus_switch_state(dev, NULL, XenbusStateClosed);
+}
+
+
+static int blkfront_remove(struct xenbus_device *dev)
+{
+       struct blkfront_info *info = dev->data;
+
+       DPRINTK("blkfront_remove: %s removed\n", dev->nodename);
+
+       blkif_free(info, 0);
+
+       kfree(info);
+
+       return 0;
+}
+
 
 static inline int GET_ID_FROM_FREELIST(
        struct blkfront_info *info)
@@ -214,7 +516,7 @@
 
                        gnttab_grant_foreign_access_ref(
                                ref,
-                               info->backend_id,
+                               info->xbdev->otherend_id,
                                buffer_mfn,
                                rq_data_dir(req) );
 
@@ -268,6 +570,7 @@
                        req, req->cmd, req->sector, req->current_nr_sectors,
                        req->nr_sectors, req->buffer,
                        rq_data_dir(req) ? "write" : "read");
+
 
                blkdev_dequeue_request(req);
                if (blkif_queue_request(req)) {
@@ -343,11 +646,12 @@
        return IRQ_HANDLED;
 }
 
-static void blkif_free(struct blkfront_info *info)
+static void blkif_free(struct blkfront_info *info, int suspend)
 {
        /* Prevent new requests being issued until we fix things up. */
        spin_lock_irq(&blkif_io_lock);
-       info->connected = BLKIF_STATE_DISCONNECTED;
+       info->connected = suspend ? 
+               BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED; 
        spin_unlock_irq(&blkif_io_lock);
 
        /* Free resources associated with old device channel. */
@@ -360,6 +664,15 @@
        if (info->irq)
                unbind_from_irqhandler(info->irq, info); 
        info->evtchn = info->irq = 0;
+
+}
+
+static void blkif_completion(struct blk_shadow *s)
+{
+       int i;
+       for (i = 0; i < s->req.nr_segments; i++)
+               gnttab_end_foreign_access(
+                       blkif_gref_from_fas(s->req.frame_and_sects[i]), 0, 0UL);
 }
 
 static void blkif_recover(struct blkfront_info *info)
@@ -370,7 +683,7 @@
        int j;
 
        /* Stage 1: Make a safe copy of the shadow state. */
-       copy = (struct blk_shadow *)kmalloc(sizeof(info->shadow), GFP_KERNEL);
+       copy = kmalloc(sizeof(info->shadow), GFP_KERNEL);
        BUG_ON(copy == NULL);
        memcpy(copy, info->shadow, sizeof(info->shadow));
 
@@ -400,7 +713,7 @@
                for (j = 0; j < req->nr_segments; j++)
                        gnttab_grant_foreign_access_ref(
                                blkif_gref_from_fas(req->frame_and_sects[j]),
-                               info->backend_id,
+                               info->xbdev->otherend_id,
                                pfn_to_mfn(info->shadow[req->id].frame[j]),
                                rq_data_dir(
                                        (struct request *)
@@ -422,21 +735,8 @@
        info->connected = BLKIF_STATE_CONNECTED;
 }
 
-static void blkif_connect(struct blkfront_info *info, u16 evtchn)
-{
-       int err = 0;
-
-       info->evtchn = evtchn;
-
-       err = bind_evtchn_to_irqhandler(
-               info->evtchn, blkif_int, SA_SAMPLE_RANDOM, "blkif", info);
-       if (err <= 0) {
-               WPRINTK("bind_evtchn_to_irqhandler failed (err=%d)\n", err);
-               return;
-       }
-
-       info->irq = err;
-}
+
+/* ** Driver Registration ** */
 
 
 static struct xenbus_device_id blkfront_ids[] = {
@@ -444,279 +744,6 @@
        { "" }
 };
 
-static void watch_for_status(struct xenbus_watch *watch,
-                            const char **vec, unsigned int len)
-{
-       struct blkfront_info *info;
-       unsigned int binfo;
-       unsigned long sectors, sector_size;
-       int err;
-       const char *node;
-
-       node = vec[XS_WATCH_PATH];
-
-       info = container_of(watch, struct blkfront_info, watch);
-       node += strlen(watch->node);
-
-       /* FIXME: clean up when error on the other end. */
-       if ((info->connected == BLKIF_STATE_CONNECTED) || info->mi)
-               return;
-
-       err = xenbus_gather(NULL, watch->node,
-                           "sectors", "%lu", &sectors,
-                           "info", "%u", &binfo,
-                           "sector-size", "%lu", &sector_size,
-                           NULL);
-       if (err) {
-               xenbus_dev_error(info->xbdev, err,
-                                "reading backend fields at %s", watch->node);
-               return;
-       }
-
-       info->connected = BLKIF_STATE_CONNECTED;
-       xlvbd_add(sectors, info->vdevice, binfo, sector_size, info);
-
-       xenbus_dev_ok(info->xbdev);
-
-       /* Kick pending requests. */
-       spin_lock_irq(&blkif_io_lock);
-       kick_pending_request_queues(info);
-       spin_unlock_irq(&blkif_io_lock);
-}
-
-static int setup_blkring(struct xenbus_device *dev, struct blkfront_info *info)
-{
-       blkif_sring_t *sring;
-       int err;
-       evtchn_op_t op = {
-               .cmd = EVTCHNOP_alloc_unbound,
-               .u.alloc_unbound.dom = DOMID_SELF,
-               .u.alloc_unbound.remote_dom = info->backend_id };
-
-       info->ring_ref = GRANT_INVALID_REF;
-
-       sring = (void *)__get_free_page(GFP_KERNEL);
-       if (!sring) {
-               xenbus_dev_error(dev, -ENOMEM, "allocating shared ring");
-               return -ENOMEM;
-       }
-       SHARED_RING_INIT(sring);
-       FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
-
-       err = gnttab_grant_foreign_access(info->backend_id,
-                                         virt_to_mfn(info->ring.sring), 0);
-       if (err == -ENOSPC) {
-               free_page((unsigned long)info->ring.sring);
-               info->ring.sring = 0;
-               xenbus_dev_error(dev, err, "granting access to ring page");
-               return err;
-       }
-       info->ring_ref = err;
-
-       err = HYPERVISOR_event_channel_op(&op);
-       if (err) {
-               gnttab_end_foreign_access(info->ring_ref, 0,
-                                         (unsigned long)info->ring.sring);
-               info->ring_ref = GRANT_INVALID_REF;
-               info->ring.sring = NULL;
-               xenbus_dev_error(dev, err, "allocating event channel");
-               return err;
-       }
-
-       blkif_connect(info, op.u.alloc_unbound.port);
-
-       return 0;
-}
-
-/* Common code used when first setting up, and when resuming. */
-static int talk_to_backend(struct xenbus_device *dev,
-                          struct blkfront_info *info)
-{
-       char *backend;
-       const char *message;
-       struct xenbus_transaction *xbt;
-       int err;
-
-       backend = NULL;
-       err = xenbus_gather(NULL, dev->nodename,
-                           "backend-id", "%i", &info->backend_id,
-                           "backend", NULL, &backend,
-                           NULL);
-       if (XENBUS_EXIST_ERR(err))
-               goto out;
-       if (backend && strlen(backend) == 0) {
-               err = -ENOENT;
-               goto out;
-       }
-       if (err < 0) {
-               xenbus_dev_error(dev, err, "reading %s/backend or backend-id",
-                                dev->nodename);
-               goto out;
-       }
-
-       /* Create shared ring, alloc event channel. */
-       err = setup_blkring(dev, info);
-       if (err) {
-               xenbus_dev_error(dev, err, "setting up block ring");
-               goto out;
-       }
-
-again:
-       xbt = xenbus_transaction_start();
-       if (IS_ERR(xbt)) {
-               xenbus_dev_error(dev, err, "starting transaction");
-               goto destroy_blkring;
-       }
-
-       err = xenbus_printf(xbt, dev->nodename,
-                           "ring-ref","%u", info->ring_ref);
-       if (err) {
-               message = "writing ring-ref";
-               goto abort_transaction;
-       }
-       err = xenbus_printf(xbt, dev->nodename,
-                           "event-channel", "%u", info->evtchn);
-       if (err) {
-               message = "writing event-channel";
-               goto abort_transaction;
-       }
-
-       err = xenbus_transaction_end(xbt, 0);
-       if (err) {
-               if (err == -EAGAIN)
-                       goto again;
-               xenbus_dev_error(dev, err, "completing transaction");
-               goto destroy_blkring;
-       }
-
-       info->watch.node = backend;
-       info->watch.callback = watch_for_status;
-       err = register_xenbus_watch(&info->watch);
-       if (err) {
-               message = "registering watch on backend";
-               goto destroy_blkring;
-       }
-
-       info->backend = backend;
-
-       return 0;
-
- abort_transaction:
-       xenbus_transaction_end(xbt, 1);
-       xenbus_dev_error(dev, err, "%s", message);
- destroy_blkring:
-       blkif_free(info);
- out:
-       if (backend)
-               kfree(backend);
-       return err;
-}
-
-/* Setup supplies the backend dir, virtual device.
-
-   We place an event channel and shared frame entries.
-   We watch backend to wait if it's ok. */
-static int blkfront_probe(struct xenbus_device *dev,
-                         const struct xenbus_device_id *id)
-{
-       int err, vdevice, i;
-       struct blkfront_info *info;
-
-       /* FIXME: Use dynamic device id if this is not set. */
-       err = xenbus_scanf(NULL, dev->nodename,
-                          "virtual-device", "%i", &vdevice);
-       if (XENBUS_EXIST_ERR(err))
-               return err;
-       if (err < 0) {
-               xenbus_dev_error(dev, err, "reading virtual-device");
-               return err;
-       }
-
-       info = kmalloc(sizeof(*info), GFP_KERNEL);
-       if (!info) {
-               xenbus_dev_error(dev, err, "allocating info structure");
-               return err;
-       }
-       info->xbdev = dev;
-       info->vdevice = vdevice;
-       info->connected = BLKIF_STATE_DISCONNECTED;
-       info->mi = NULL;
-       info->gd = NULL;
-       INIT_WORK(&info->work, blkif_restart_queue, (void *)info);
-
-       info->shadow_free = 0;
-       memset(info->shadow, 0, sizeof(info->shadow));
-       for (i = 0; i < BLK_RING_SIZE; i++)
-               info->shadow[i].req.id = i+1;
-       info->shadow[BLK_RING_SIZE-1].req.id = 0x0fffffff;
-
-       /* Front end dir is a number, which is used as the id. */
-       info->handle = simple_strtoul(strrchr(dev->nodename,'/')+1, NULL, 0);
-       dev->data = info;
-
-       err = talk_to_backend(dev, info);
-       if (err) {
-               kfree(info);
-               dev->data = NULL;
-               return err;
-       }
-
-       {
-               unsigned int len = max(XS_WATCH_PATH, XS_WATCH_TOKEN) + 1;
-               const char *vec[len];
-
-               vec[XS_WATCH_PATH] = info->watch.node;
-               vec[XS_WATCH_TOKEN] = NULL;
-
-               /* Call once in case entries already there. */
-               watch_for_status(&info->watch, vec, len);
-       }
-
-       return 0;
-}
-
-static int blkfront_remove(struct xenbus_device *dev)
-{
-       struct blkfront_info *info = dev->data;
-
-       if (info->backend)
-               unregister_xenbus_watch(&info->watch);
-
-       if (info->mi)
-               xlvbd_del(info);
-
-       blkif_free(info);
-
-       kfree(info->backend);
-       kfree(info);
-
-       return 0;
-}
-
-static int blkfront_suspend(struct xenbus_device *dev)
-{
-       struct blkfront_info *info = dev->data;
-
-       unregister_xenbus_watch(&info->watch);
-       kfree(info->backend);
-       info->backend = NULL;
-
-       return 0;
-}
-
-static int blkfront_resume(struct xenbus_device *dev)
-{
-       struct blkfront_info *info = dev->data;
-       int err;
-
-       blkif_free(info);
-
-       err = talk_to_backend(dev, info);
-       if (!err)
-               blkif_recover(info);
-
-       return err;
-}
 
 static struct xenbus_driver blkfront = {
        .name = "vbd",
@@ -725,27 +752,28 @@
        .probe = blkfront_probe,
        .remove = blkfront_remove,
        .resume = blkfront_resume,
-       .suspend = blkfront_suspend,
+       .otherend_changed = backend_changed,
 };
+
 
 static int __init xlblk_init(void)
 {
        if (xen_init() < 0)
                return -ENODEV;
 
-       xenbus_register_driver(&blkfront);
-       return 0;
-}
-
+       return xenbus_register_frontend(&blkfront);
+}
 module_init(xlblk_init);
 
-static void blkif_completion(struct blk_shadow *s)
-{
-       int i;
-       for (i = 0; i < s->req.nr_segments; i++)
-               gnttab_end_foreign_access(
-                       blkif_gref_from_fas(s->req.frame_and_sects[i]), 0, 0UL);
-}
+
+static void xlblk_exit(void)
+{
+       return xenbus_unregister_driver(&blkfront);
+}
+module_exit(xlblk_exit);
+
+MODULE_LICENSE("BSD");
+
 
 /*
  * Local variables:
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/blkfront/block.h
--- a/linux-2.6-xen-sparse/drivers/xen/blkfront/block.h Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/blkfront/block.h Sat Nov 19 05:16:29 2005
@@ -113,15 +113,11 @@
 struct blkfront_info
 {
        struct xenbus_device *xbdev;
-       /* We watch the backend */
-       struct xenbus_watch watch;
        dev_t dev;
        struct gendisk *gd;
        int vdevice;
        blkif_vdev_t handle;
        int connected;
-       char *backend;
-       int backend_id;
        int ring_ref;
        blkif_front_ring_t ring;
        unsigned int evtchn, irq;
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/blktap/blktap.c
--- a/linux-2.6-xen-sparse/drivers/xen/blktap/blktap.c  Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/blktap/blktap.c  Sat Nov 19 05:16:29 2005
@@ -412,7 +412,7 @@
        struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST*2];
        unsigned int i, op = 0;
        struct grant_handle_pair *handle;
-       unsigned long ptep;
+       uint64_t ptep;
        int ret;
 
        for ( i = 0; i < nr_pages; i++)
@@ -427,9 +427,9 @@
                op++;
 
                if (create_lookup_pte_addr(
-                       blktap_vma->vm_mm,
-                       MMAP_VADDR(user_vstart, idx, i), 
-                       &ptep) !=0) {
+                           blktap_vma->vm_mm,
+                           MMAP_VADDR(user_vstart, idx, i), 
+                           &ptep) !=0) {
                        DPRINTK("Couldn't get a pte addr!\n");
                        return;
                }
@@ -705,7 +705,7 @@
 
                unsigned long uvaddr;
                unsigned long kvaddr;
-               unsigned long ptep;
+               uint64_t ptep;
 
                uvaddr = MMAP_VADDR(user_vstart, pending_idx, i);
                kvaddr = MMAP_VADDR(mmap_vstart, pending_idx, i);
@@ -777,8 +777,8 @@
                /* Set the necessary mappings in p2m and in the VM_FOREIGN 
                 * vm_area_struct to allow user vaddr -> struct page lookups
                 * to work.  This is needed for direct IO to foreign pages. */
-               phys_to_machine_mapping[__pa(kvaddr) >> PAGE_SHIFT] =
-                       FOREIGN_FRAME(map[i].dev_bus_addr >> PAGE_SHIFT);
+               set_phys_to_machine(__pa(kvaddr) >> PAGE_SHIFT,
+                               FOREIGN_FRAME(map[i].dev_bus_addr >> 
PAGE_SHIFT));
 
                offset = (uvaddr - blktap_vma->vm_start) >> PAGE_SHIFT;
                ((struct page **)blktap_vma->vm_private_data)[offset] =
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/blktap/xenbus.c
--- a/linux-2.6-xen-sparse/drivers/xen/blktap/xenbus.c  Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/blktap/xenbus.c  Sat Nov 19 05:16:29 2005
@@ -52,8 +52,7 @@
        unregister_xenbus_watch(&be->backend_watch);
        if (be->blkif)
                blkif_put(be->blkif);
-       if (be->frontpath)
-               kfree(be->frontpath);
+       kfree(be->frontpath);
        kfree(be);
        return 0;
 }
@@ -201,8 +200,7 @@
  free_be:
        if (be->backend_watch.node)
                unregister_xenbus_watch(&be->backend_watch);
-       if (frontend)
-               kfree(frontend);
+       kfree(frontend);
        kfree(be);
        return err;
 }
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/console/console.c
--- a/linux-2.6-xen-sparse/drivers/xen/console/console.c        Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/console/console.c        Sat Nov 19 
05:16:29 2005
@@ -53,6 +53,7 @@
 #include <asm-xen/xen-public/event_channel.h>
 #include <asm/hypervisor.h>
 #include <asm-xen/evtchn.h>
+#include <asm-xen/xencons.h>
 
 #include "xencons_ring.h"
 /*
@@ -127,12 +128,7 @@
 /* Common transmit-kick routine. */
 static void __xencons_tx_flush(void);
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 static struct tty_driver *xencons_driver;
-#else
-static struct tty_driver xencons_driver;
-#endif
-
 
 /******************** Kernel console driver ********************************/
 
@@ -169,18 +165,11 @@
        }
 }
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 static struct tty_driver *kcons_device(struct console *c, int *index)
 {
        *index = c->index;
        return xencons_driver;
 }
-#else
-static kdev_t kcons_device(struct console *c)
-{
-       return MKDEV(TTY_MAJOR, (xc_mode == XC_SERIAL) ? 64 : 1);
-}
-#endif
 
 static struct console kcons_info = {
        .device = kcons_device,
@@ -188,13 +177,8 @@
        .index  = -1,
 };
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 #define __RETCODE 0
 static int __init xen_console_init(void)
-#else
-#define __RETCODE
-void xen_console_init(void)
-#endif
 {
        if (xen_init() < 0)
                return __RETCODE;
@@ -203,10 +187,8 @@
                if (xc_mode == XC_DEFAULT)
                        xc_mode = XC_SERIAL;
                kcons_info.write = kcons_write_dom0;
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
                if (xc_mode == XC_SERIAL)
                        kcons_info.flags |= CON_ENABLED;
-#endif
        } else {
                if (xc_mode == XC_DEFAULT)
                        xc_mode = XC_TTY;
@@ -236,16 +218,10 @@
 
        return __RETCODE;
 }
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 console_initcall(xen_console_init);
-#endif
 
 /*** Useful function for console debugging -- goes straight to Xen. ***/
-#ifdef CONFIG_XEN_PRIVILEGED_GUEST
 asmlinkage int xprintk(const char *fmt, ...)
-#else
-asmlinkage int xprintk(const char *fmt, ...)
-#endif
 {
        va_list args;
        int printk_len;
@@ -286,15 +262,8 @@
 
 /******************** User-space console driver (/dev/console) ************/
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 #define DRV(_d)         (_d)
 #define TTY_INDEX(_tty) ((_tty)->index)
-#else
-static int xencons_refcount;
-static struct tty_struct *xencons_table[MAX_NR_CONSOLES];
-#define DRV(_d)         (&(_d))
-#define TTY_INDEX(_tty) (MINOR((_tty)->device) - xencons_driver.minor_start)
-#endif
 
 static struct termios *xencons_termios[MAX_NR_CONSOLES];
 static struct termios *xencons_termios_locked[MAX_NR_CONSOLES];
@@ -487,7 +456,6 @@
        return 1;
 }
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 static int xencons_write(
        struct tty_struct *tty,
        const unsigned char *buf,
@@ -512,42 +480,6 @@
 
        return i;
 }
-#else
-static int xencons_write(
-       struct tty_struct *tty, 
-       int from_user,
-       const u_char *buf, 
-       int count)
-{
-       int i;
-       unsigned long flags;
-
-       if (from_user && verify_area(VERIFY_READ, buf, count))
-               return -EINVAL;
-
-       if (TTY_INDEX(tty) != 0)
-               return count;
-
-       spin_lock_irqsave(&xencons_lock, flags);
-
-       for (i = 0; i < count; i++) {
-               char ch;
-               if (from_user)
-                       __get_user(ch, buf + i);
-               else
-                       ch = buf[i];
-               if (!__xencons_put_char(ch))
-                       break;
-       }
-
-       if (i != 0)
-               __xencons_tx_flush();
-
-       spin_unlock_irqrestore(&xencons_lock, flags);
-
-       return i;
-}
-#endif
 
 static void xencons_put_char(struct tty_struct *tty, u_char ch)
 {
@@ -632,7 +564,6 @@
        }
 }
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 static struct tty_operations xencons_ops = {
        .open = xencons_open,
        .close = xencons_close,
@@ -688,7 +619,6 @@
        .con_scrolldelta =      DUMMY,
 };
 #endif
-#endif
 
 static int __init xencons_init(void)
 {
@@ -702,19 +632,10 @@
 
        xencons_ring_init();
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
        xencons_driver = alloc_tty_driver((xc_mode == XC_SERIAL) ? 
                                          1 : MAX_NR_CONSOLES);
        if (xencons_driver == NULL)
                return -ENOMEM;
-#else
-       memset(&xencons_driver, 0, sizeof(struct tty_driver));
-       xencons_driver.magic       = TTY_DRIVER_MAGIC;
-       xencons_driver.refcount    = &xencons_refcount;
-       xencons_driver.table       = xencons_table;
-       xencons_driver.num         =
-               (xc_mode == XC_SERIAL) ? 1 : MAX_NR_CONSOLES;
-#endif
 
        DRV(xencons_driver)->major           = TTY_MAJOR;
        DRV(xencons_driver)->type            = TTY_DRIVER_TYPE_SERIAL;
@@ -738,37 +659,18 @@
                DRV(xencons_driver)->name_base   = xc_num;
        }
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
        tty_set_operations(xencons_driver, &xencons_ops);
-#else
-       xencons_driver.open            = xencons_open;
-       xencons_driver.close           = xencons_close;
-       xencons_driver.write           = xencons_write;
-       xencons_driver.write_room      = xencons_write_room;
-       xencons_driver.put_char        = xencons_put_char;
-       xencons_driver.flush_chars     = xencons_flush_chars;
-       xencons_driver.chars_in_buffer = xencons_chars_in_buffer;
-       xencons_driver.send_xchar      = xencons_send_xchar;
-       xencons_driver.flush_buffer    = xencons_flush_buffer;
-       xencons_driver.throttle        = xencons_throttle;
-       xencons_driver.unthrottle      = xencons_unthrottle;
-       xencons_driver.wait_until_sent = xencons_wait_until_sent;
-#endif
 
        if ((rc = tty_register_driver(DRV(xencons_driver))) != 0) {
                printk("WARNING: Failed to register Xen virtual "
                       "console driver as '%s%d'\n",
                       DRV(xencons_driver)->name, 
DRV(xencons_driver)->name_base);
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
                put_tty_driver(xencons_driver);
                xencons_driver = NULL;
-#endif
                return rc;
        }
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
        tty_register_device(xencons_driver, 0, NULL);
-#endif
 
        if (xen_start_info->flags & SIF_INITDOMAIN) {
                xencons_priv_irq = bind_virq_to_irqhandler(
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/console/xencons_ring.c
--- a/linux-2.6-xen-sparse/drivers/xen/console/xencons_ring.c   Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/console/xencons_ring.c   Sat Nov 19 
05:16:29 2005
@@ -30,6 +30,12 @@
        return mfn_to_virt(xen_start_info->console_mfn);
 }
 
+static inline void notify_daemon(void)
+{
+       /* Use evtchn: this is called early, before irq is set up. */
+       notify_remote_via_evtchn(xen_start_info->console_evtchn);
+}
+
 int xencons_ring_send(const char *data, unsigned len)
 {
        int sent = 0;
@@ -47,8 +53,7 @@
        wmb();
        intf->out_prod = prod;
 
-       /* Use evtchn: this is called early, before irq is set up. */
-       notify_remote_via_evtchn(xen_start_info->console_evtchn);
+       notify_daemon();
 
        return sent;
 }      
@@ -70,8 +75,10 @@
                                1, regs);
        }
 
-       wmb();
+       mb();
        intf->in_cons = cons;
+
+       notify_daemon();
 
        return IRQ_HANDLED;
 }
@@ -102,6 +109,9 @@
 
        xencons_irq = err;
 
+       /* In case we have in-flight data after save/restore... */
+       notify_daemon();
+
        return 0;
 }
 
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/evtchn/evtchn.c
--- a/linux-2.6-xen-sparse/drivers/xen/evtchn/evtchn.c  Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/evtchn/evtchn.c  Sat Nov 19 05:16:29 2005
@@ -436,9 +436,7 @@
        .minor        = EVTCHN_MINOR,
        .name         = "evtchn",
        .fops         = &evtchn_fops,
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
        .devfs_name   = "misc/evtchn",
-#endif
 };
 
 static int __init evtchn_init(void)
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/netback/loopback.c
--- a/linux-2.6-xen-sparse/drivers/xen/netback/loopback.c       Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/netback/loopback.c       Sat Nov 19 
05:16:29 2005
@@ -160,10 +160,8 @@
        return 0;
 
  fail:
-       if (dev1 != NULL)
-               kfree(dev1);
-       if (dev2 != NULL)
-               kfree(dev2);
+       kfree(dev1);
+       kfree(dev2);
        return err;
 }
 
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/netback/netback.c
--- a/linux-2.6-xen-sparse/drivers/xen/netback/netback.c        Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/netback/netback.c        Sat Nov 19 
05:16:29 2005
@@ -248,8 +248,7 @@
                 * Set the new P2M table entry before reassigning the old data
                 * page. Heed the comment in pgtable-2level.h:pte_page(). :-)
                 */
-               phys_to_machine_mapping[__pa(skb->data) >> PAGE_SHIFT] =
-                       new_mfn;
+               set_phys_to_machine(__pa(skb->data) >> PAGE_SHIFT, new_mfn);
 
                MULTI_update_va_mapping(mcl, vdata,
                                        pfn_pte_ma(new_mfn, PAGE_KERNEL), 0);
@@ -631,9 +630,9 @@
                                pending_idx;
                        continue;
                }
-               phys_to_machine_mapping[
-                       __pa(MMAP_VADDR(pending_idx)) >> PAGE_SHIFT] =
-                       FOREIGN_FRAME(mop->dev_bus_addr >> PAGE_SHIFT);
+               set_phys_to_machine(
+                       __pa(MMAP_VADDR(pending_idx)) >> PAGE_SHIFT,
+                       FOREIGN_FRAME(mop->dev_bus_addr >> PAGE_SHIFT));
                grant_tx_ref[pending_idx] = mop->handle;
 
                data_len = (txreq.size > PKT_PROT_LEN) ?
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/netback/xenbus.c
--- a/linux-2.6-xen-sparse/drivers/xen/netback/xenbus.c Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/netback/xenbus.c Sat Nov 19 05:16:29 2005
@@ -1,5 +1,6 @@
 /*  Xenbus code for netif backend
     Copyright (C) 2005 Rusty Russell <rusty@xxxxxxxxxxxxxxx>
+    Copyright (C) 2005 XenSource Ltd
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
@@ -15,160 +16,116 @@
     along with this program; if not, write to the Free Software
     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
+
+
 #include <stdarg.h>
 #include <linux/module.h>
 #include <asm-xen/xenbus.h>
+#include <asm-xen/net_driver_util.h>
 #include "common.h"
 
+
+#if 0
+#undef DPRINTK
+#define DPRINTK(fmt, args...) \
+    printk("netback/xenbus (%s:%d) " fmt ".\n", __FUNCTION__, __LINE__, ##args)
+#endif
+
+
 struct backend_info
 {
        struct xenbus_device *dev;
-
-       /* our communications channel */
        netif_t *netif;
-
-       long int frontend_id;
-
-       /* watch back end for changes */
        struct xenbus_watch backend_watch;
-
-       /* watch front end for changes */
-       struct xenbus_watch watch;
-       char *frontpath;
+       XenbusState frontend_state;
 };
 
+
+static int connect_rings(struct backend_info *);
+static void connect(struct backend_info *);
+static void maybe_connect(struct backend_info *);
+static void backend_changed(struct xenbus_watch *, const char **,
+                           unsigned int);
+
+
 static int netback_remove(struct xenbus_device *dev)
 {
        struct backend_info *be = dev->data;
 
-       if (be->watch.node)
-               unregister_xenbus_watch(&be->watch);
-       unregister_xenbus_watch(&be->backend_watch);
-       if (be->netif)
+       if (be->backend_watch.node) {
+               unregister_xenbus_watch(&be->backend_watch);
+               kfree(be->backend_watch.node);
+               be->backend_watch.node = NULL;
+       }
+       if (be->netif) {
                netif_disconnect(be->netif);
-       if (be->frontpath)
-               kfree(be->frontpath);
+               be->netif = NULL;
+       }
        kfree(be);
+       dev->data = NULL;
        return 0;
 }
 
-/* Front end tells us frame. */
-static void frontend_changed(struct xenbus_watch *watch, 
-                            const char **vec, unsigned int len)
-{
-       unsigned long tx_ring_ref, rx_ring_ref;
-       unsigned int evtchn;
+
+/**
+ * Entry point to this code when a new device is created.  Allocate the basic
+ * structures, and watch the store waiting for the hotplug scripts to tell us
+ * the device's handle.  Switch to InitWait.
+ */
+static int netback_probe(struct xenbus_device *dev,
+                        const struct xenbus_device_id *id)
+{
        int err;
-       struct backend_info *be
-               = container_of(watch, struct backend_info, watch);
-       char *mac, *e, *s;
-       int i;
-
-       /* If other end is gone, delete ourself. */
-       if (vec && !xenbus_exists(NULL, be->frontpath, "")) {
-               xenbus_rm(NULL, be->dev->nodename, "");
-               device_unregister(&be->dev->dev);
-               return;
-       }
-       if (be->netif == NULL || be->netif->status == CONNECTED)
-               return;
-
-       mac = xenbus_read(NULL, be->frontpath, "mac", NULL);
-       if (IS_ERR(mac)) {
-               err = PTR_ERR(mac);
-               xenbus_dev_error(be->dev, err, "reading %s/mac",
-                                be->dev->nodename);
-               return;
-       }
-       s = mac;
-       for (i = 0; i < ETH_ALEN; i++) {
-               be->netif->fe_dev_addr[i] = simple_strtoul(s, &e, 16);
-               if (s == e || (e[0] != ':' && e[0] != 0)) {
-                       kfree(mac);
-                       err = -ENOENT;
-                       xenbus_dev_error(be->dev, err, "parsing %s/mac",
-                                        be->dev->nodename);
-                       return;
-               }
-               s = &e[1];
-       }
-       kfree(mac);
-
-       err = xenbus_gather(NULL, be->frontpath,
-                           "tx-ring-ref", "%lu", &tx_ring_ref,
-                           "rx-ring-ref", "%lu", &rx_ring_ref,
-                           "event-channel", "%u", &evtchn, NULL);
+       struct backend_info *be = kmalloc(sizeof(struct backend_info),
+                                         GFP_KERNEL);
+       if (!be) {
+               xenbus_dev_fatal(dev, -ENOMEM,
+                                "allocating backend structure");
+               return -ENOMEM;
+       }
+       memset(be, 0, sizeof(*be));
+
+       be->dev = dev;
+       dev->data = be;
+
+       err = xenbus_watch_path2(dev, dev->nodename, "handle",
+                                &be->backend_watch, backend_changed);
+       if (err)
+               goto fail;
+
+       err = xenbus_switch_state(dev, NULL, XenbusStateInitWait);
        if (err) {
-               xenbus_dev_error(be->dev, err,
-                                "reading %s/ring-ref and event-channel",
-                                be->frontpath);
-               return;
-       }
-
-       /* Map the shared frame, irq etc. */
-       err = netif_map(be->netif, tx_ring_ref, rx_ring_ref, evtchn);
-       if (err) {
-               xenbus_dev_error(be->dev, err,
-                                "mapping shared-frames %lu/%lu port %u",
-                                tx_ring_ref, rx_ring_ref, evtchn);
-               return;
-       }
-
-       xenbus_dev_ok(be->dev);
-
-       return;
-}
-
-/* 
-   Setup supplies physical device.  
-   We provide event channel and device details to front end.
-   Frontend supplies shared frame and event channel.
- */
-static void backend_changed(struct xenbus_watch *watch,
-                           const char **vec, unsigned int len)
-{
-       int err;
-       long int handle;
-       struct backend_info *be
-               = container_of(watch, struct backend_info, backend_watch);
-       struct xenbus_device *dev = be->dev;
-       u8 be_mac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };
-
-       err = xenbus_scanf(NULL, dev->nodename, "handle", "%li", &handle);
-       if (XENBUS_EXIST_ERR(err))
-               return;
-       if (err < 0) {
-               xenbus_dev_error(dev, err, "reading handle");
-               return;
-       }
-
-       if (be->netif == NULL) {
-               be->netif = alloc_netif(be->frontend_id, handle, be_mac);
-               if (IS_ERR(be->netif)) {
-                       err = PTR_ERR(be->netif);
-                       be->netif = NULL;
-                       xenbus_dev_error(dev, err, "creating interface");
-                       return;
-               }
-
-               kobject_hotplug(&dev->dev.kobj, KOBJ_ONLINE);
-
-               /* Pass in NULL node to skip exist test. */
-               frontend_changed(&be->watch, NULL, 0);
-       }
-}
-
+               goto fail;
+       }
+
+       return 0;
+
+fail:
+       DPRINTK("failed");
+       netback_remove(dev);
+       return err;
+}
+
+
+/**
+ * Handle the creation of the hotplug script environment.  We add the script
+ * and vif variables to the environment, for the benefit of the vif-* hotplug
+ * scripts.
+ */
 static int netback_hotplug(struct xenbus_device *xdev, char **envp,
                           int num_envp, char *buffer, int buffer_size)
 {
        struct backend_info *be = xdev->data;
        netif_t *netif = be->netif;
        int i = 0, length = 0;
-
-       char *val = xenbus_read(NULL, xdev->nodename, "script", NULL);
+       char *val;
+
+       DPRINTK("netback_hotplug");
+
+       val = xenbus_read(NULL, xdev->nodename, "script", NULL);
        if (IS_ERR(val)) {
                int err = PTR_ERR(val);
-               xenbus_dev_error(xdev, err, "reading script");
+               xenbus_dev_fatal(xdev, err, "reading script");
                return err;
        }
        else {
@@ -187,82 +144,161 @@
        return 0;
 }
 
-static int netback_probe(struct xenbus_device *dev,
-                        const struct xenbus_device_id *id)
-{
-       struct backend_info *be;
-       char *frontend;
+
+/**
+ * Callback received when the hotplug scripts have placed the handle node.
+ * Read it, and create a netif structure.  If the frontend is ready, connect.
+ */
+static void backend_changed(struct xenbus_watch *watch,
+                           const char **vec, unsigned int len)
+{
        int err;
-
-       be = kmalloc(sizeof(*be), GFP_KERNEL);
-       if (!be) {
-               xenbus_dev_error(dev, -ENOMEM, "allocating backend structure");
-               return -ENOMEM;
-       }
-       memset(be, 0, sizeof(*be));
-
-       frontend = NULL;
-       err = xenbus_gather(NULL, dev->nodename,
-                           "frontend-id", "%li", &be->frontend_id,
-                           "frontend", NULL, &frontend,
-                           NULL);
-       if (XENBUS_EXIST_ERR(err))
-               goto free_be;
-       if (err < 0) {
-               xenbus_dev_error(dev, err,
-                                "reading %s/frontend or frontend-id",
-                                dev->nodename);
-               goto free_be;
-       }
-       if (strlen(frontend) == 0 || !xenbus_exists(NULL, frontend, "")) {
-               /* If we can't get a frontend path and a frontend-id,
-                * then our bus-id is no longer valid and we need to
-                * destroy the backend device.
-                */
-               err = -ENOENT;
-               goto free_be;
-       }
-
-       be->dev = dev;
-       be->backend_watch.node = dev->nodename;
-       be->backend_watch.callback = backend_changed;
-       /* Registration implicitly calls backend_changed. */
-       err = register_xenbus_watch(&be->backend_watch);
+       long handle;
+       struct backend_info *be
+               = container_of(watch, struct backend_info, backend_watch);
+       struct xenbus_device *dev = be->dev;
+
+       DPRINTK("");
+
+       err = xenbus_scanf(NULL, dev->nodename, "handle", "%li", &handle);
+       if (XENBUS_EXIST_ERR(err)) {
+               /* Since this watch will fire once immediately after it is
+                  registered, we expect this.  Ignore it, and wait for the
+                  hotplug scripts. */
+               return;
+       }
+       if (err != 1) {
+               xenbus_dev_fatal(dev, err, "reading handle");
+               return;
+       }
+
+       if (be->netif == NULL) {
+               u8 be_mac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };
+
+               be->netif = alloc_netif(dev->otherend_id, handle, be_mac);
+               if (IS_ERR(be->netif)) {
+                       err = PTR_ERR(be->netif);
+                       be->netif = NULL;
+                       xenbus_dev_fatal(dev, err, "creating interface");
+                       return;
+               }
+
+               kobject_hotplug(&dev->dev.kobj, KOBJ_ONLINE);
+
+               maybe_connect(be);
+       }
+}
+
+
+/**
+ * Callback received when the frontend's state changes.
+ */
+static void frontend_changed(struct xenbus_device *dev,
+                            XenbusState frontend_state)
+{
+       struct backend_info *be = dev->data;
+
+       DPRINTK("");
+
+       be->frontend_state = frontend_state;
+
+       switch (frontend_state) {
+       case XenbusStateInitialising:
+       case XenbusStateInitialised:
+               break;
+
+       case XenbusStateConnected:
+               maybe_connect(be);
+               break;
+
+       case XenbusStateClosing:
+               xenbus_switch_state(dev, NULL, XenbusStateClosing);
+               break;
+
+       case XenbusStateClosed:
+               device_unregister(&be->dev->dev);
+               break;
+
+       case XenbusStateUnknown:
+       case XenbusStateInitWait:
+       default:
+               xenbus_dev_fatal(be->dev, -EINVAL, "saw state %d at frontend",
+                                frontend_state);
+               break;
+       }
+}
+
+
+/* ** Connection ** */
+
+
+static void maybe_connect(struct backend_info *be)
+{
+       if (be->netif != NULL && be->frontend_state == XenbusStateConnected) {
+               connect(be);
+       }
+}
+
+
+static void connect(struct backend_info *be)
+{
+       int err;
+       struct xenbus_device *dev = be->dev;
+
+       err = connect_rings(be);
+       if (err)
+               return;
+
+       err = xen_net_read_mac(dev, be->netif->fe_dev_addr);
        if (err) {
-               be->backend_watch.node = NULL;
-               xenbus_dev_error(dev, err, "adding backend watch on %s",
-                                dev->nodename);
-               goto free_be;
-       }
-
-       be->frontpath = frontend;
-       be->watch.node = be->frontpath;
-       be->watch.callback = frontend_changed;
-       err = register_xenbus_watch(&be->watch);
+               xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
+               return;
+       }
+
+       xenbus_switch_state(dev, NULL, XenbusStateConnected);
+}
+
+
+static int connect_rings(struct backend_info *be)
+{
+       struct xenbus_device *dev = be->dev;
+       unsigned long tx_ring_ref, rx_ring_ref;
+       unsigned int evtchn;
+       int err;
+
+       DPRINTK("");
+
+       err = xenbus_gather(NULL, dev->otherend,
+                           "tx-ring-ref", "%lu", &tx_ring_ref,
+                           "rx-ring-ref", "%lu", &rx_ring_ref,
+                           "event-channel", "%u", &evtchn, NULL);
        if (err) {
-               be->watch.node = NULL;
-               xenbus_dev_error(dev, err,
-                                "adding frontend watch on %s",
-                                be->frontpath);
-               goto free_be;
-       }
-
-       dev->data = be;
+               xenbus_dev_fatal(dev, err,
+                                "reading %s/ring-ref and event-channel",
+                                dev->otherend);
+               return err;
+       }
+
+       /* Map the shared frame, irq etc. */
+       err = netif_map(be->netif, tx_ring_ref, rx_ring_ref, evtchn);
+       if (err) {
+               xenbus_dev_fatal(dev, err,
+                                "mapping shared-frames %lu/%lu port %u",
+                                tx_ring_ref, rx_ring_ref, evtchn);
+               return err;
+       }
        return 0;
-
- free_be:
-       if (be->backend_watch.node)
-               unregister_xenbus_watch(&be->backend_watch);
-       if (frontend)
-               kfree(frontend);
-       kfree(be);
-       return err;
-}
+}
+
+
+/* ** Driver Registration ** */
+
 
 static struct xenbus_device_id netback_ids[] = {
        { "vif" },
        { "" }
 };
+
 
 static struct xenbus_driver netback = {
        .name = "vif",
@@ -271,12 +307,15 @@
        .probe = netback_probe,
        .remove = netback_remove,
        .hotplug = netback_hotplug,
+       .otherend_changed = frontend_changed,
 };
 
+
 void netif_xenbus_init(void)
 {
        xenbus_register_backend(&netback);
 }
+
 
 /*
  * Local variables:
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/netfront/netfront.c
--- a/linux-2.6-xen-sparse/drivers/xen/netfront/netfront.c      Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/netfront/netfront.c      Sat Nov 19 
05:16:29 2005
@@ -2,6 +2,7 @@
  * Virtual network driver for conversing with remote driver backends.
  * 
  * Copyright (c) 2002-2005, K A Fraser
+ * Copyright (c) 2005, XenSource Ltd
  * 
  * This file may be distributed separately from the Linux kernel, or
  * incorporated into other software packages, subject to the following license:
@@ -56,6 +57,7 @@
 #include <asm/uaccess.h>
 #include <asm-xen/xen-public/grant_table.h>
 #include <asm-xen/gnttab.h>
+#include <asm-xen/net_driver_util.h>
 
 #define GRANT_INVALID_REF      0
 
@@ -87,13 +89,111 @@
 #define TX_TEST_IDX req_cons  /* conservative: not seen all our requests? */
 #endif
 
-
-static void network_tx_buf_gc(struct net_device *dev);
-static void network_alloc_rx_buffers(struct net_device *dev);
-
 static unsigned long rx_pfn_array[NETIF_RX_RING_SIZE];
 static multicall_entry_t rx_mcl[NETIF_RX_RING_SIZE+1];
 static mmu_update_t rx_mmu[NETIF_RX_RING_SIZE];
+
+struct netfront_info
+{
+       struct list_head list;
+       struct net_device *netdev;
+
+       struct net_device_stats stats;
+       NETIF_RING_IDX rx_resp_cons, tx_resp_cons;
+       unsigned int tx_full;
+    
+       netif_tx_interface_t *tx;
+       netif_rx_interface_t *rx;
+
+       spinlock_t   tx_lock;
+       spinlock_t   rx_lock;
+
+       unsigned int handle;
+       unsigned int evtchn, irq;
+
+       /* What is the status of our connection to the remote backend? */
+#define BEST_CLOSED       0
+#define BEST_DISCONNECTED 1
+#define BEST_CONNECTED    2
+       unsigned int backend_state;
+
+       /* Is this interface open or closed (down or up)? */
+#define UST_CLOSED        0
+#define UST_OPEN          1
+       unsigned int user_state;
+
+       /* Receive-ring batched refills. */
+#define RX_MIN_TARGET 8
+#define RX_MAX_TARGET NETIF_RX_RING_SIZE
+       int rx_min_target, rx_max_target, rx_target;
+       struct sk_buff_head rx_batch;
+
+       /*
+        * {tx,rx}_skbs store outstanding skbuffs. The first entry in each
+        * array is an index into a chain of free entries.
+        */
+       struct sk_buff *tx_skbs[NETIF_TX_RING_SIZE+1];
+       struct sk_buff *rx_skbs[NETIF_RX_RING_SIZE+1];
+
+       grant_ref_t gref_tx_head;
+       grant_ref_t grant_tx_ref[NETIF_TX_RING_SIZE + 1]; 
+       grant_ref_t gref_rx_head;
+       grant_ref_t grant_rx_ref[NETIF_TX_RING_SIZE + 1]; 
+
+       struct xenbus_device *xbdev;
+       int tx_ring_ref;
+       int rx_ring_ref;
+       u8 mac[ETH_ALEN];
+};
+
+/* Access macros for acquiring freeing slots in {tx,rx}_skbs[]. */
+#define ADD_ID_TO_FREELIST(_list, _id)                 \
+       (_list)[(_id)] = (_list)[0];                    \
+       (_list)[0]     = (void *)(unsigned long)(_id);
+#define GET_ID_FROM_FREELIST(_list)                            \
+       ({ unsigned long _id = (unsigned long)(_list)[0];       \
+          (_list)[0]  = (_list)[_id];                          \
+          (unsigned short)_id; })
+
+#ifdef DEBUG
+static char *be_state_name[] = {
+       [BEST_CLOSED]       = "closed",
+       [BEST_DISCONNECTED] = "disconnected",
+       [BEST_CONNECTED]    = "connected",
+};
+#endif
+
+#ifdef DEBUG
+#define DPRINTK(fmt, args...) \
+       printk(KERN_ALERT "netfront (%s:%d) " fmt, __FUNCTION__, __LINE__, 
##args)
+#else
+#define DPRINTK(fmt, args...) ((void)0)
+#endif
+#define IPRINTK(fmt, args...) \
+       printk(KERN_INFO "netfront: " fmt, ##args)
+#define WPRINTK(fmt, args...) \
+       printk(KERN_WARNING "netfront: " fmt, ##args)
+
+
+static int talk_to_backend(struct xenbus_device *, struct netfront_info *);
+static int setup_device(struct xenbus_device *, struct netfront_info *);
+static int create_netdev(int, struct xenbus_device *, struct net_device **);
+
+static void netfront_closing(struct xenbus_device *);
+
+static void end_access(int, void *);
+static void netif_disconnect_backend(struct netfront_info *);
+static void close_netdev(struct netfront_info *);
+static void netif_free(struct netfront_info *);
+
+static void show_device(struct netfront_info *);
+
+static void network_connect(struct net_device *);
+static void network_tx_buf_gc(struct net_device *);
+static void network_alloc_rx_buffers(struct net_device *);
+static int send_fake_arp(struct net_device *);
+
+static irqreturn_t netif_int(int irq, void *dev_id, struct pt_regs *ptregs);
 
 #ifdef CONFIG_PROC_FS
 static int xennet_proc_init(void);
@@ -105,92 +205,216 @@
 #define xennet_proc_delif(d) ((void)0)
 #endif
 
-#define netfront_info net_private
-struct net_private
-{
-       struct list_head list;
+
+/**
+ * Entry point to this code when a new device is created.  Allocate the basic
+ * structures and the ring buffers for communication with the backend, and
+ * inform the backend of the appropriate details for those.  Switch to
+ * Connected state.
+ */
+static int netfront_probe(struct xenbus_device *dev,
+                         const struct xenbus_device_id *id)
+{
+       int err;
        struct net_device *netdev;
-
-       struct net_device_stats stats;
-       NETIF_RING_IDX rx_resp_cons, tx_resp_cons;
-       unsigned int tx_full;
-    
-       netif_tx_interface_t *tx;
-       netif_rx_interface_t *rx;
-
-       spinlock_t   tx_lock;
-       spinlock_t   rx_lock;
-
+       struct netfront_info *info;
        unsigned int handle;
-       unsigned int evtchn, irq;
-
-       /* What is the status of our connection to the remote backend? */
-#define BEST_CLOSED       0
-#define BEST_DISCONNECTED 1
-#define BEST_CONNECTED    2
-       unsigned int backend_state;
-
-       /* Is this interface open or closed (down or up)? */
-#define UST_CLOSED        0
-#define UST_OPEN          1
-       unsigned int user_state;
-
-       /* Receive-ring batched refills. */
-#define RX_MIN_TARGET 8
-#define RX_MAX_TARGET NETIF_RX_RING_SIZE
-       int rx_min_target, rx_max_target, rx_target;
-       struct sk_buff_head rx_batch;
-
-       /*
-        * {tx,rx}_skbs store outstanding skbuffs. The first entry in each
-        * array is an index into a chain of free entries.
-        */
-       struct sk_buff *tx_skbs[NETIF_TX_RING_SIZE+1];
-       struct sk_buff *rx_skbs[NETIF_RX_RING_SIZE+1];
-
-       grant_ref_t gref_tx_head;
-       grant_ref_t grant_tx_ref[NETIF_TX_RING_SIZE + 1]; 
-       grant_ref_t gref_rx_head;
-       grant_ref_t grant_rx_ref[NETIF_TX_RING_SIZE + 1]; 
-
-       struct xenbus_device *xbdev;
-       char *backend;
-       int backend_id;
-       struct xenbus_watch watch;
-       int tx_ring_ref;
-       int rx_ring_ref;
-       u8 mac[ETH_ALEN];
-};
-
-/* Access macros for acquiring freeing slots in {tx,rx}_skbs[]. */
-#define ADD_ID_TO_FREELIST(_list, _id)                 \
-       (_list)[(_id)] = (_list)[0];                    \
-       (_list)[0]     = (void *)(unsigned long)(_id);
-#define GET_ID_FROM_FREELIST(_list)                            \
-       ({ unsigned long _id = (unsigned long)(_list)[0];       \
-          (_list)[0]  = (_list)[_id];                          \
-          (unsigned short)_id; })
-
-#ifdef DEBUG
-static char *be_state_name[] = {
-       [BEST_CLOSED]       = "closed",
-       [BEST_DISCONNECTED] = "disconnected",
-       [BEST_CONNECTED]    = "connected",
-};
-#endif
-
-#ifdef DEBUG
-#define DPRINTK(fmt, args...) \
-       printk(KERN_ALERT "xen_net (%s:%d) " fmt, __FUNCTION__, __LINE__, 
##args)
-#else
-#define DPRINTK(fmt, args...) ((void)0)
-#endif
-#define IPRINTK(fmt, args...) \
-       printk(KERN_INFO "xen_net: " fmt, ##args)
-#define WPRINTK(fmt, args...) \
-       printk(KERN_WARNING "xen_net: " fmt, ##args)
-
-static void netif_free(struct netfront_info *info);
+
+       err = xenbus_scanf(NULL, dev->nodename, "handle", "%u", &handle);
+       if (err != 1) {
+               xenbus_dev_fatal(dev, err, "reading handle");
+               return err;
+       }
+
+       err = create_netdev(handle, dev, &netdev);
+       if (err) {
+               xenbus_dev_fatal(dev, err, "creating netdev");
+               return err;
+       }
+
+       info = netdev_priv(netdev);
+       dev->data = info;
+
+       err = talk_to_backend(dev, info);
+       if (err) {
+               kfree(info);
+               dev->data = NULL;
+               return err;
+       }
+
+       return 0;
+}
+
+
+/**
+ * We are reconnecting to the backend, due to a suspend/resume, or a backend
+ * driver restart.  We tear down our netif structure and recreate it, but
+ * leave the device-layer structures intact so that this is transparent to the
+ * rest of the kernel.
+ */
+static int netfront_resume(struct xenbus_device *dev)
+{
+       struct netfront_info *info = dev->data;
+
+       DPRINTK("%s\n", dev->nodename);
+
+       netif_disconnect_backend(info);
+       return talk_to_backend(dev, info);
+}
+
+
+/* Common code used when first setting up, and when resuming. */
+static int talk_to_backend(struct xenbus_device *dev,
+                          struct netfront_info *info)
+{
+       const char *message;
+       struct xenbus_transaction *xbt;
+       int err;
+
+       err = xen_net_read_mac(dev, info->mac);
+       if (err) {
+               xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
+               goto out;
+       }
+
+       /* Create shared ring, alloc event channel. */
+       err = setup_device(dev, info);
+       if (err)
+               goto out;
+
+again:
+       xbt = xenbus_transaction_start();
+       if (IS_ERR(xbt)) {
+               xenbus_dev_fatal(dev, err, "starting transaction");
+               goto destroy_ring;
+       }
+
+       err = xenbus_printf(xbt, dev->nodename, "tx-ring-ref","%u",
+                           info->tx_ring_ref);
+       if (err) {
+               message = "writing tx ring-ref";
+               goto abort_transaction;
+       }
+       err = xenbus_printf(xbt, dev->nodename, "rx-ring-ref","%u",
+                           info->rx_ring_ref);
+       if (err) {
+               message = "writing rx ring-ref";
+               goto abort_transaction;
+       }
+       err = xenbus_printf(xbt, dev->nodename,
+                           "event-channel", "%u", info->evtchn);
+       if (err) {
+               message = "writing event-channel";
+               goto abort_transaction;
+       }
+
+       err = xenbus_printf(xbt, dev->nodename,
+                           "state", "%d", XenbusStateConnected);
+       if (err) {
+               message = "writing frontend XenbusStateConnected";
+               goto abort_transaction;
+       }
+
+       err = xenbus_transaction_end(xbt, 0);
+       if (err) {
+               if (err == -EAGAIN)
+                       goto again;
+               xenbus_dev_fatal(dev, err, "completing transaction");
+               goto destroy_ring;
+       }
+
+       return 0;
+
+ abort_transaction:
+       xenbus_transaction_end(xbt, 1);
+       xenbus_dev_fatal(dev, err, "%s", message);
+ destroy_ring:
+       netif_free(info);
+ out:
+       return err;
+}
+
+
+static int setup_device(struct xenbus_device *dev, struct netfront_info *info)
+{
+       int err;
+       struct net_device *netdev = info->netdev;
+
+       info->tx_ring_ref = GRANT_INVALID_REF;
+       info->rx_ring_ref = GRANT_INVALID_REF;
+       info->rx = NULL;
+       info->tx = NULL;
+       info->irq = 0;
+
+       info->tx = (netif_tx_interface_t *)__get_free_page(GFP_KERNEL);
+       if (!info->tx) {
+               err = -ENOMEM;
+               xenbus_dev_fatal(dev, err, "allocating tx ring page");
+               goto fail;
+       }
+       info->rx = (netif_rx_interface_t *)__get_free_page(GFP_KERNEL);
+       if (!info->rx) {
+               err = -ENOMEM;
+               xenbus_dev_fatal(dev, err, "allocating rx ring page");
+               goto fail;
+       }
+       memset(info->tx, 0, PAGE_SIZE);
+       memset(info->rx, 0, PAGE_SIZE);
+       info->backend_state = BEST_DISCONNECTED;
+
+       err = xenbus_grant_ring(dev, virt_to_mfn(info->tx));
+       if (err < 0)
+               goto fail;
+       info->tx_ring_ref = err;
+
+       err = xenbus_grant_ring(dev, virt_to_mfn(info->rx));
+       if (err < 0)
+               goto fail;
+       info->rx_ring_ref = err;
+
+       err = xenbus_alloc_evtchn(dev, &info->evtchn);
+       if (err)
+               goto fail;
+
+       memcpy(netdev->dev_addr, info->mac, ETH_ALEN);
+       network_connect(netdev);
+       info->irq = bind_evtchn_to_irqhandler(
+               info->evtchn, netif_int, SA_SAMPLE_RANDOM, netdev->name,
+               netdev);
+       (void)send_fake_arp(netdev);
+       show_device(info);
+
+       return 0;
+
+ fail:
+       netif_free(info);
+       return err;
+}
+
+
+/**
+ * Callback received when the backend's state changes.
+ */
+static void backend_changed(struct xenbus_device *dev,
+                           XenbusState backend_state)
+{
+       DPRINTK("\n");
+
+       switch (backend_state) {
+       case XenbusStateInitialising:
+       case XenbusStateInitWait:
+       case XenbusStateInitialised:
+       case XenbusStateConnected:
+       case XenbusStateUnknown:
+       case XenbusStateClosed:
+               break;
+
+       case XenbusStateClosing:
+               netfront_closing(dev);
+               break;
+       }
+}
+
 
 /** Send a packet on a net device to encourage switches to learn the
  * MAC. We send a fake ARP request.
@@ -220,9 +444,10 @@
        return dev_queue_xmit(skb);
 }
 
+
 static int network_open(struct net_device *dev)
 {
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
 
        memset(&np->stats, 0, sizeof(np->stats));
 
@@ -240,7 +465,7 @@
 {
        NETIF_RING_IDX i, prod;
        unsigned short id;
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        struct sk_buff *skb;
 
        if (np->backend_state != BEST_CONNECTED)
@@ -295,7 +520,7 @@
 static void network_alloc_rx_buffers(struct net_device *dev)
 {
        unsigned short id;
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        struct sk_buff *skb;
        int i, batch_target;
        NETIF_RING_IDX req_prod = np->rx->req_prod;
@@ -337,13 +562,13 @@
                ref = gnttab_claim_grant_reference(&np->gref_rx_head);
                BUG_ON((signed short)ref < 0);
                np->grant_rx_ref[id] = ref;
-               gnttab_grant_foreign_transfer_ref(ref, np->backend_id);
+               gnttab_grant_foreign_transfer_ref(ref,
+                                                 np->xbdev->otherend_id);
                np->rx->ring[MASK_NETIF_RX_IDX(req_prod + i)].req.gref = ref;
                rx_pfn_array[i] = virt_to_mfn(skb->head);
 
                /* Remove this page from map before passing back to Xen. */
-               phys_to_machine_mapping[__pa(skb->head) >> PAGE_SHIFT] 
-                       = INVALID_P2M_ENTRY;
+               set_phys_to_machine(__pa(skb->head) >> PAGE_SHIFT, 
INVALID_P2M_ENTRY);
 
                MULTI_update_va_mapping(rx_mcl+i, (unsigned long)skb->head,
                                        __pte(0), 0);
@@ -386,7 +611,7 @@
 static int network_start_xmit(struct sk_buff *skb, struct net_device *dev)
 {
        unsigned short id;
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        netif_tx_request_t *tx;
        NETIF_RING_IDX i;
        grant_ref_t ref;
@@ -430,7 +655,7 @@
        BUG_ON((signed short)ref < 0);
        mfn = virt_to_mfn(skb->data);
        gnttab_grant_foreign_access_ref(
-               ref, np->backend_id, mfn, GNTMAP_readonly);
+               ref, np->xbdev->otherend_id, mfn, GNTMAP_readonly);
        tx->gref = np->grant_tx_ref[id] = ref;
        tx->offset = (unsigned long)skb->data & ~PAGE_MASK;
        tx->size = skb->len;
@@ -467,7 +692,7 @@
 static irqreturn_t netif_int(int irq, void *dev_id, struct pt_regs *ptregs)
 {
        struct net_device *dev = dev_id;
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        unsigned long flags;
 
        spin_lock_irqsave(&np->tx_lock, flags);
@@ -484,7 +709,7 @@
 
 static int netif_poll(struct net_device *dev, int *pbudget)
 {
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        struct sk_buff *skb, *nskb;
        netif_rx_response_t *rx;
        NETIF_RING_IDX i, rp;
@@ -535,7 +760,7 @@
                if(ref == GRANT_INVALID_REF) { 
                        printk(KERN_WARNING "Bad rx grant reference %d "
                               "from dom %d.\n",
-                              ref, np->backend_id);
+                              ref, np->xbdev->otherend_id);
                        np->rx->ring[MASK_NETIF_RX_IDX(np->rx->req_prod)].
                                req.id = rx->id;
                        wmb();
@@ -570,7 +795,7 @@
                                        pfn_pte_ma(mfn, PAGE_KERNEL), 0);
                mcl++;
 
-               phys_to_machine_mapping[__pa(skb->head) >> PAGE_SHIFT] = mfn;
+               set_phys_to_machine(__pa(skb->head) >> PAGE_SHIFT, mfn);
 
                __skb_queue_tail(&rxq, skb);
        }
@@ -679,7 +904,7 @@
 
 static int network_close(struct net_device *dev)
 {
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        np->user_state = UST_CLOSED;
        netif_stop_queue(np->netdev);
        return 0;
@@ -688,13 +913,13 @@
 
 static struct net_device_stats *network_get_stats(struct net_device *dev)
 {
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        return &np->stats;
 }
 
 static void network_connect(struct net_device *dev)
 {
-       struct net_private *np;
+       struct netfront_info *np;
        int i, requeue_idx;
        netif_tx_request_t *tx;
        struct sk_buff *skb;
@@ -737,7 +962,7 @@
 
                tx->id = i;
                gnttab_grant_foreign_access_ref(
-                       np->grant_tx_ref[i], np->backend_id, 
+                       np->grant_tx_ref[i], np->xbdev->otherend_id, 
                        virt_to_mfn(np->tx_skbs[i]->data),
                        GNTMAP_readonly); 
                tx->gref = np->grant_tx_ref[i];
@@ -756,7 +981,7 @@
                if ((unsigned long)np->rx_skbs[i] < __PAGE_OFFSET)
                        continue;
                gnttab_grant_foreign_transfer_ref(
-                       np->grant_rx_ref[i], np->backend_id);
+                       np->grant_rx_ref[i], np->xbdev->otherend_id);
                np->rx->ring[requeue_idx].req.gref =
                        np->grant_rx_ref[i];
                np->rx->ring[requeue_idx].req.id = i;
@@ -783,7 +1008,7 @@
        spin_unlock_irq(&np->tx_lock);
 }
 
-static void show_device(struct net_private *np)
+static void show_device(struct netfront_info *np)
 {
 #ifdef DEBUG
        if (np) {
@@ -800,27 +1025,9 @@
 #endif
 }
 
-/*
- * Move the vif into connected state.
- * Sets the mac and event channel from the message.
- * Binds the irq to the event channel.
- */
-static void 
-connect_device(struct net_private *np, unsigned int evtchn)
-{
-       struct net_device *dev = np->netdev;
-       memcpy(dev->dev_addr, np->mac, ETH_ALEN);
-       np->evtchn = evtchn;
-       network_connect(dev);
-       np->irq = bind_evtchn_to_irqhandler(
-               np->evtchn, netif_int, SA_SAMPLE_RANDOM, dev->name, dev);
-       (void)send_fake_arp(dev);
-       show_device(np);
-}
-
 static void netif_uninit(struct net_device *dev)
 {
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        gnttab_free_grant_references(np->gref_tx_head);
        gnttab_free_grant_references(np->gref_rx_head);
 }
@@ -841,9 +1048,9 @@
 {
        int i, err = 0;
        struct net_device *netdev = NULL;
-       struct net_private *np = NULL;
-
-       if ((netdev = alloc_etherdev(sizeof(struct net_private))) == NULL) {
+       struct netfront_info *np = NULL;
+
+       if ((netdev = alloc_etherdev(sizeof(struct netfront_info))) == NULL) {
                printk(KERN_WARNING "%s> alloc_etherdev failed.\n",
                       __FUNCTION__);
                err = -ENOMEM;
@@ -918,7 +1125,7 @@
        np->netdev = netdev;
 
  exit:
-       if ((err != 0) && (netdev != NULL))
+       if (err != 0)
                kfree(netdev);
        else if (val != NULL)
                *val = netdev;
@@ -928,15 +1135,6 @@
        gnttab_free_grant_references(np->gref_tx_head);
        gnttab_free_grant_references(np->gref_rx_head);
        goto exit;
-}
-
-static int destroy_netdev(struct net_device *netdev)
-{
-#ifdef CONFIG_PROC_FS
-       xennet_proc_delif(netdev);
-#endif
-        unregister_netdev(netdev);
-       return 0;
 }
 
 /*
@@ -956,91 +1154,70 @@
        return NOTIFY_DONE;
 }
 
-static struct notifier_block notifier_inetdev = {
-       .notifier_call  = inetdev_notify,
-       .next           = NULL,
-       .priority       = 0
-};
-
-static struct xenbus_device_id netfront_ids[] = {
-       { "vif" },
-       { "" }
-};
-
-static void watch_for_status(struct xenbus_watch *watch,
-                            const char **vec, unsigned int len)
-{
-}
-
-static int setup_device(struct xenbus_device *dev, struct netfront_info *info)
-{
-       int err;
-       evtchn_op_t op = {
-               .cmd = EVTCHNOP_alloc_unbound,
-               .u.alloc_unbound.dom = DOMID_SELF,
-               .u.alloc_unbound.remote_dom = info->backend_id };
-
-       info->tx_ring_ref = GRANT_INVALID_REF;
-       info->rx_ring_ref = GRANT_INVALID_REF;
-       info->rx = NULL;
-       info->tx = NULL;
-       info->irq = 0;
-
-       info->tx = (netif_tx_interface_t *)__get_free_page(GFP_KERNEL);
-       if (info->tx == 0) {
-               err = -ENOMEM;
-               xenbus_dev_error(dev, err, "allocating tx ring page");
-               goto out;
-       }
-       info->rx = (netif_rx_interface_t *)__get_free_page(GFP_KERNEL);
-       if (info->rx == 0) {
-               err = -ENOMEM;
-               xenbus_dev_error(dev, err, "allocating rx ring page");
-               goto out;
-       }
-       memset(info->tx, 0, PAGE_SIZE);
-       memset(info->rx, 0, PAGE_SIZE);
-       info->backend_state = BEST_DISCONNECTED;
-
-       err = gnttab_grant_foreign_access(info->backend_id,
-                                         virt_to_mfn(info->tx), 0);
-       if (err < 0) {
-               xenbus_dev_error(dev, err, "granting access to tx ring page");
-               goto out;
-       }
-       info->tx_ring_ref = err;
-
-       err = gnttab_grant_foreign_access(info->backend_id,
-                                         virt_to_mfn(info->rx), 0);
-       if (err < 0) {
-               xenbus_dev_error(dev, err, "granting access to rx ring page");
-               goto out;
-       }
-       info->rx_ring_ref = err;
-
-       err = HYPERVISOR_event_channel_op(&op);
-       if (err) {
-               xenbus_dev_error(dev, err, "allocating event channel");
-               goto out;
-       }
-
-       connect_device(info, op.u.alloc_unbound.port);
+
+/* ** Close down ** */
+
+
+/**
+ * Handle the change of state of the backend to Closing.  We must delete our
+ * device-layer structures now, to ensure that writes are flushed through to
+ * the backend.  Once is this done, we can switch to Closed in
+ * acknowledgement.
+ */
+static void netfront_closing(struct xenbus_device *dev)
+{
+       struct netfront_info *info = dev->data;
+
+       DPRINTK("netfront_closing: %s removed\n", dev->nodename);
+
+       close_netdev(info);
+
+       xenbus_switch_state(dev, NULL, XenbusStateClosed);
+}
+
+
+static int netfront_remove(struct xenbus_device *dev)
+{
+       struct netfront_info *info = dev->data;
+
+       DPRINTK("%s\n", dev->nodename);
+
+       netif_free(info);
+       kfree(info);
 
        return 0;
-
- out:
-       netif_free(info);
-       return err;
-}
-
-static void end_access(int ref, void *page)
-{
-       if (ref != GRANT_INVALID_REF)
-               gnttab_end_foreign_access(ref, 0, (unsigned long)page);
-}
+}
+
 
 static void netif_free(struct netfront_info *info)
 {
+       netif_disconnect_backend(info);
+       close_netdev(info);
+}
+
+
+static void close_netdev(struct netfront_info *info)
+{
+       if (info->netdev) {
+#ifdef CONFIG_PROC_FS
+               xennet_proc_delif(info->netdev);
+#endif
+               unregister_netdev(info->netdev);
+               info->netdev = NULL;
+       }
+}
+
+
+static void netif_disconnect_backend(struct netfront_info *info)
+{
+       /* Stop old i/f to prevent errors whilst we rebuild the state. */
+       spin_lock_irq(&info->tx_lock);
+       spin_lock(&info->rx_lock);
+       netif_stop_queue(info->netdev);
+       /* info->backend_state = BEST_DISCONNECTED; */
+       spin_unlock(&info->rx_lock);
+       spin_unlock_irq(&info->tx_lock);
+    
        end_access(info->tx_ring_ref, info->tx);
        end_access(info->rx_ring_ref, info->rx);
        info->tx_ring_ref = GRANT_INVALID_REF;
@@ -1053,203 +1230,22 @@
        info->evtchn = info->irq = 0;
 }
 
-/* Stop network device and free tx/rx queues and irq. */
-static void shutdown_device(struct net_private *np)
-{
-       /* Stop old i/f to prevent errors whilst we rebuild the state. */
-       spin_lock_irq(&np->tx_lock);
-       spin_lock(&np->rx_lock);
-       netif_stop_queue(np->netdev);
-       /* np->backend_state = BEST_DISCONNECTED; */
-       spin_unlock(&np->rx_lock);
-       spin_unlock_irq(&np->tx_lock);
-    
-       /* Free resources. */
-       netif_free(np);
-}
-
-/* Common code used when first setting up, and when resuming. */
-static int talk_to_backend(struct xenbus_device *dev,
-                          struct netfront_info *info)
-{
-       char *backend, *mac, *e, *s;
-       const char *message;
-       struct xenbus_transaction *xbt;
-       int err, i;
-
-       backend = NULL;
-       err = xenbus_gather(NULL, dev->nodename,
-                           "backend-id", "%i", &info->backend_id,
-                           "backend", NULL, &backend,
-                           NULL);
-       if (XENBUS_EXIST_ERR(err))
-               goto out;
-       if (backend && strlen(backend) == 0) {
-               err = -ENOENT;
-               goto out;
-       }
-       if (err < 0) {
-               xenbus_dev_error(dev, err, "reading %s/backend or backend-id",
-                                dev->nodename);
-               goto out;
-       }
-
-       mac = xenbus_read(NULL, dev->nodename, "mac", NULL);
-       if (IS_ERR(mac)) {
-               err = PTR_ERR(mac);
-               xenbus_dev_error(dev, err, "reading %s/mac",
-                                dev->nodename);
-               goto out;
-       }
-       s = mac;
-       for (i = 0; i < ETH_ALEN; i++) {
-               info->mac[i] = simple_strtoul(s, &e, 16);
-               if (s == e || (e[0] != ':' && e[0] != 0)) {
-                       kfree(mac);
-                       err = -ENOENT;
-                       xenbus_dev_error(dev, err, "parsing %s/mac",
-                                        dev->nodename);
-                       goto out;
-               }
-               s = &e[1];
-       }
-       kfree(mac);
-
-       /* Create shared ring, alloc event channel. */
-       err = setup_device(dev, info);
-       if (err) {
-               xenbus_dev_error(dev, err, "setting up ring");
-               goto out;
-       }
-
-again:
-       xbt = xenbus_transaction_start();
-       if (IS_ERR(xbt)) {
-               xenbus_dev_error(dev, err, "starting transaction");
-               goto destroy_ring;
-       }
-
-       err = xenbus_printf(xbt, dev->nodename, "tx-ring-ref","%u",
-                           info->tx_ring_ref);
-       if (err) {
-               message = "writing tx ring-ref";
-               goto abort_transaction;
-       }
-       err = xenbus_printf(xbt, dev->nodename, "rx-ring-ref","%u",
-                           info->rx_ring_ref);
-       if (err) {
-               message = "writing rx ring-ref";
-               goto abort_transaction;
-       }
-       err = xenbus_printf(xbt, dev->nodename,
-                           "event-channel", "%u", info->evtchn);
-       if (err) {
-               message = "writing event-channel";
-               goto abort_transaction;
-       }
-
-       err = xenbus_transaction_end(xbt, 0);
-       if (err) {
-               if (err == -EAGAIN)
-                       goto again;
-               xenbus_dev_error(dev, err, "completing transaction");
-               goto destroy_ring;
-       }
-
-       info->watch.node = backend;
-       info->watch.callback = watch_for_status;
-       err = register_xenbus_watch(&info->watch);
-       if (err) {
-               message = "registering watch on backend";
-               goto destroy_ring;
-       }
-
-       info->backend = backend;
-
-       return 0;
-
- abort_transaction:
-       xenbus_transaction_end(xbt, 1);
-       xenbus_dev_error(dev, err, "%s", message);
- destroy_ring:
-       shutdown_device(info);
- out:
-       if (backend)
-               kfree(backend);
-       return err;
-}
-
-/*
- * Setup supplies the backend dir, virtual device.
- * We place an event channel and shared frame entries.
- * We watch backend to wait if it's ok.
- */
-static int netfront_probe(struct xenbus_device *dev,
-                         const struct xenbus_device_id *id)
-{
-       int err;
-       struct net_device *netdev;
-       struct netfront_info *info;
-       unsigned int handle;
-
-       err = xenbus_scanf(NULL, dev->nodename, "handle", "%u", &handle);
-       if (XENBUS_EXIST_ERR(err))
-               return err;
-       if (err < 0) {
-               xenbus_dev_error(dev, err, "reading handle");
-               return err;
-       }
-
-       err = create_netdev(handle, dev, &netdev);
-       if (err) {
-               xenbus_dev_error(dev, err, "creating netdev");
-               return err;
-       }
-
-       info = netdev_priv(netdev);
-       dev->data = info;
-
-       err = talk_to_backend(dev, info);
-       if (err) {
-               destroy_netdev(netdev);
-               kfree(netdev);
-               dev->data = NULL;
-               return err;
-       }
-
-       return 0;
-}
-
-static int netfront_remove(struct xenbus_device *dev)
-{
-       struct netfront_info *info = dev->data;
-
-       if (info->backend)
-               unregister_xenbus_watch(&info->watch);
-
-       netif_free(info);
-
-       kfree(info->backend);
-       kfree(info);
-
-       return 0;
-}
-
-static int netfront_suspend(struct xenbus_device *dev)
-{
-       struct netfront_info *info = dev->data;
-       unregister_xenbus_watch(&info->watch);
-       kfree(info->backend);
-       info->backend = NULL;
-       return 0;
-}
-
-static int netfront_resume(struct xenbus_device *dev)
-{
-       struct netfront_info *info = dev->data;
-       netif_free(info);
-       return talk_to_backend(dev, info);
-}
+
+static void end_access(int ref, void *page)
+{
+       if (ref != GRANT_INVALID_REF)
+               gnttab_end_foreign_access(ref, 0, (unsigned long)page);
+}
+
+
+/* ** Driver registration ** */
+
+
+static struct xenbus_device_id netfront_ids[] = {
+       { "vif" },
+       { "" }
+};
+
 
 static struct xenbus_driver netfront = {
        .name = "vif",
@@ -1258,13 +1254,15 @@
        .probe = netfront_probe,
        .remove = netfront_remove,
        .resume = netfront_resume,
-       .suspend = netfront_suspend,
+       .otherend_changed = backend_changed,
 };
 
-static void __init init_net_xenbus(void)
-{
-       xenbus_register_driver(&netfront);
-}
+
+static struct notifier_block notifier_inetdev = {
+       .notifier_call  = inetdev_notify,
+       .next           = NULL,
+       .priority       = 0
+};
 
 static int __init netif_init(void)
 {
@@ -1280,14 +1278,24 @@
 
        (void)register_inetaddr_notifier(&notifier_inetdev);
 
-       init_net_xenbus();
-
-       return err;
-}
+       return xenbus_register_frontend(&netfront);
+}
+module_init(netif_init);
+
 
 static void netif_exit(void)
 {
-}
+       unregister_inetaddr_notifier(&notifier_inetdev);
+
+       return xenbus_unregister_driver(&netfront);
+}
+module_exit(netif_exit);
+
+MODULE_LICENSE("BSD");
+ 
+ 
+/* ** /proc **/
+
 
 #ifdef CONFIG_PROC_FS
 
@@ -1300,7 +1308,7 @@
 {
        struct net_device *dev =
                (struct net_device *)((unsigned long)data & ~3UL);
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        int len = 0, which_target = (long)data & 3;
     
        switch (which_target)
@@ -1326,7 +1334,7 @@
 {
        struct net_device *dev =
                (struct net_device *)((unsigned long)data & ~3UL);
-       struct net_private *np = netdev_priv(dev);
+       struct netfront_info *np = netdev_priv(dev);
        int which_target = (long)data & 3;
        char string[64];
        long target;
@@ -1440,8 +1448,6 @@
 
 #endif
 
-module_init(netif_init);
-module_exit(netif_exit);
 
 /*
  * Local variables:
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/privcmd/privcmd.c
--- a/linux-2.6-xen-sparse/drivers/xen/privcmd/privcmd.c        Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/privcmd/privcmd.c        Sat Nov 19 
05:16:29 2005
@@ -31,11 +31,6 @@
 #include <asm-xen/xen-public/xen.h>
 #include <asm-xen/xen-public/dom0_ops.h>
 #include <asm-xen/xen_proc.h>
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
-#define pud_t pgd_t
-#define pud_offset(d, va) d
-#endif
 
 static struct proc_dir_entry *privcmd_intf;
 
@@ -152,7 +147,8 @@
                privcmd_mmapbatch_t m;
                struct vm_area_struct *vma = NULL;
                unsigned long *p, addr;
-               unsigned long mfn, ptep;
+               unsigned long mfn; 
+               uint64_t ptep;
                int i;
 
                if (copy_from_user(&m, (void *)data, sizeof(m))) {
@@ -217,15 +213,38 @@
 #endif
 
 #ifndef __ia64__
-       case IOCTL_PRIVCMD_GET_MACH2PHYS_START_MFN: {
-               unsigned long m2pv = (unsigned long)machine_to_phys_mapping;
-               pgd_t *pgd = pgd_offset_k(m2pv);
-               pud_t *pud = pud_offset(pgd, m2pv);
-               pmd_t *pmd = pmd_offset(pud, m2pv);
-               unsigned long m2p_start_mfn =
-                       (*(unsigned long *)pmd) >> PAGE_SHIFT; 
-               ret = put_user(m2p_start_mfn, (unsigned long *)data) ?
-                       -EFAULT: 0;
+       case IOCTL_PRIVCMD_GET_MACH2PHYS_MFNS: {
+               pgd_t *pgd; 
+               pud_t *pud; 
+               pmd_t *pmd; 
+               unsigned long m2pv, m2p_mfn;    
+               privcmd_m2pmfns_t m; 
+               unsigned long *p; 
+               int i; 
+
+               if (copy_from_user(&m, (void *)data, sizeof(m)))
+                       return -EFAULT;
+
+               m2pv = (unsigned long)machine_to_phys_mapping;
+
+               p = m.arr; 
+
+               for (i=0; i < m.num; i++) { 
+                       pgd = pgd_offset_k(m2pv);
+                       pud = pud_offset(pgd, m2pv);
+                       pmd = pmd_offset(pud, m2pv);
+                       m2p_mfn  = (*(uint64_t *)pmd >> PAGE_SHIFT)&0xFFFFFFFF;
+                       m2p_mfn += pte_index(m2pv);
+
+                       if (put_user(m2p_mfn, p + i))
+                               return -EFAULT;
+
+                       m2pv += (1 << 21); 
+               }
+
+               ret = 0; 
+               break; 
+
        }
        break;
 #endif
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/tpmback/tpmback.c
--- a/linux-2.6-xen-sparse/drivers/xen/tpmback/tpmback.c        Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/tpmback/tpmback.c        Sat Nov 19 
05:16:29 2005
@@ -167,9 +167,7 @@
 packet_free(struct packet *pak)
 {
        del_singleshot_timer_sync(&pak->processing_timer);
-       if (pak->data_buffer) {
-               kfree(pak->data_buffer);
-       }
+       kfree(pak->data_buffer);
        /*
         * cannot do tpmif_put(pak->tpmif); bad things happen
         * on the last tpmif_put()
@@ -296,9 +294,8 @@
                        DPRINTK(" Grant table operation failure !\n");
                        return 0;
                }
-               phys_to_machine_mapping[__pa(MMAP_VADDR(tpmif,i)) >>
-                                       PAGE_SHIFT] =
-                       FOREIGN_FRAME(map_op.dev_bus_addr >> PAGE_SHIFT);
+               set_phys_to_machine(__pa(MMAP_VADDR(tpmif,i)) >> PAGE_SHIFT,
+                       FOREIGN_FRAME(map_op.dev_bus_addr >> PAGE_SHIFT));
 
                tocopy = MIN(size - offset, PAGE_SIZE);
 
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/tpmback/xenbus.c
--- a/linux-2.6-xen-sparse/drivers/xen/tpmback/xenbus.c Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/tpmback/xenbus.c Sat Nov 19 05:16:29 2005
@@ -41,19 +41,16 @@
 {
        struct backend_info *be = dev->data;
 
-       if (be->watch.node) {
+       if (be->watch.node)
                unregister_xenbus_watch(&be->watch);
-       }
        unregister_xenbus_watch(&be->backend_watch);
 
        tpmif_vtpm_close(be->instance);
 
-       if (be->tpmif) {
+       if (be->tpmif)
                tpmif_put(be->tpmif);
-       }
-
-       if (be->frontpath)
-               kfree(be->frontpath);
+
+       kfree(be->frontpath);
        kfree(be);
        return 0;
 }
@@ -258,8 +255,7 @@
 free_be:
        if (be->backend_watch.node)
                unregister_xenbus_watch(&be->backend_watch);
-       if (frontend)
-               kfree(frontend);
+       kfree(frontend);
        kfree(be);
        return err;
 }
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/tpmfront/tpmfront.c
--- a/linux-2.6-xen-sparse/drivers/xen/tpmfront/tpmfront.c      Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/tpmfront/tpmfront.c      Sat Nov 19 
05:16:29 2005
@@ -387,8 +387,7 @@
 destroy_tpmring:
        destroy_tpmring(info, &my_private);
 out:
-       if (backend)
-               kfree(backend);
+       kfree(backend);
        return err;
 }
 
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/xenbus/Makefile
--- a/linux-2.6-xen-sparse/drivers/xen/xenbus/Makefile  Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/xenbus/Makefile  Sat Nov 19 05:16:29 2005
@@ -1,6 +1,7 @@
 obj-y  += xenbus.o
 
 xenbus-objs =
+xenbus-objs += xenbus_client.o 
 xenbus-objs += xenbus_comms.o
 xenbus-objs += xenbus_xs.o
 xenbus-objs += xenbus_probe.o 
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_comms.c
--- a/linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_comms.c    Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_comms.c    Sat Nov 19 
05:16:29 2005
@@ -36,7 +36,7 @@
 #include <asm-xen/xenbus.h>
 #include "xenbus_comms.h"
 
-static int xenbus_irq      = 0;
+static int xenbus_irq;
 
 extern void xenbus_probe(void *); 
 extern int xenstored_ready; 
@@ -51,7 +51,7 @@
 
 static irqreturn_t wake_waiting(int irq, void *unused, struct pt_regs *regs)
 {
-       if(unlikely(xenstored_ready == 0)) {
+       if (unlikely(xenstored_ready == 0)) {
                xenstored_ready = 1; 
                schedule_work(&probe_work); 
        } 
@@ -188,9 +188,6 @@
        }
 
        xenbus_irq = err;
-
-       /* FIXME zero out page -- domain builder should probably do this*/
-       memset(mfn_to_virt(xen_start_info->store_mfn), 0, PAGE_SIZE);
 
        return 0;
 }
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_probe.c
--- a/linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_probe.c    Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_probe.c    Sat Nov 19 
05:16:29 2005
@@ -3,6 +3,7 @@
  *
  * Copyright (C) 2005 Rusty Russell, IBM Corporation
  * Copyright (C) 2005 Mike Wray, Hewlett-Packard
+ * Copyright (C) 2005 XenSource Ltd
  * 
  * This file may be distributed separately from the Linux kernel, or
  * incorporated into other software packages, subject to the following license:
@@ -25,7 +26,13 @@
  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  * IN THE SOFTWARE.
  */
-#define DEBUG
+
+#if 0
+#define DPRINTK(fmt, args...) \
+    printk("xenbus_probe (%s:%d) " fmt ".\n", __FUNCTION__, __LINE__, ##args)
+#else
+#define DPRINTK(fmt, args...) ((void)0)
+#endif
 
 #include <linux/kernel.h>
 #include <linux/err.h>
@@ -85,6 +92,7 @@
        struct device dev;
 };
 
+
 /* device/<type>/<id> => <type>-<id> */
 static int frontend_bus_id(char bus_id[BUS_ID_SIZE], const char *nodename)
 {
@@ -102,6 +110,62 @@
        *strchr(bus_id, '/') = '-';
        return 0;
 }
+
+
+static int read_otherend_details(struct xenbus_device *xendev,
+                                char *id_node, char *path_node)
+{
+       int err = xenbus_gather(NULL, xendev->nodename,
+                               id_node, "%i", &xendev->otherend_id,
+                               path_node, NULL, &xendev->otherend,
+                               NULL);
+       if (err) {
+               xenbus_dev_fatal(xendev, err,
+                                "reading other end details from %s",
+                                xendev->nodename);
+               return err;
+       }
+       if (strlen(xendev->otherend) == 0 ||
+           !xenbus_exists(NULL, xendev->otherend, "")) {
+               xenbus_dev_fatal(xendev, -ENOENT, "missing other end from %s",
+                                xendev->nodename);
+               kfree(xendev->otherend);
+               xendev->otherend = NULL;
+               return -ENOENT;
+       }
+
+       return 0;
+}
+
+
+static int read_backend_details(struct xenbus_device *xendev)
+{
+       return read_otherend_details(xendev, "backend-id", "backend");
+}
+
+
+static int read_frontend_details(struct xenbus_device *xendev)
+{
+       return read_otherend_details(xendev, "frontend-id", "frontend");
+}
+
+
+static void free_otherend_details(struct xenbus_device *dev)
+{
+       kfree(dev->otherend);
+       dev->otherend = NULL;
+}
+
+
+static void free_otherend_watch(struct xenbus_device *dev)
+{
+       if (dev->otherend_watch.node) {
+               unregister_xenbus_watch(&dev->otherend_watch);
+               kfree(dev->otherend_watch.node);
+               dev->otherend_watch.node = NULL;
+       }
+}
+
 
 /* Bus type for frontend drivers. */
 static int xenbus_probe_frontend(const char *type, const char *name);
@@ -165,6 +229,8 @@
        int i = 0;
        int length = 0;
 
+       DPRINTK("");
+
        if (dev == NULL)
                return -ENODEV;
 
@@ -211,20 +277,88 @@
        },
 };
 
+
+static void otherend_changed(struct xenbus_watch *watch,
+                            const char **vec, unsigned int len)
+{
+       struct xenbus_device *dev =
+               container_of(watch, struct xenbus_device, otherend_watch);
+       struct xenbus_driver *drv = to_xenbus_driver(dev->dev.driver);
+       XenbusState state;
+
+       /* Protect us against watches firing on old details when the otherend
+          details change, say immediately after a resume. */
+       if (!dev->otherend ||
+           strncmp(dev->otherend, vec[XS_WATCH_PATH],
+                   strlen(dev->otherend))) {
+               DPRINTK("Ignoring watch at %s", vec[XS_WATCH_PATH]);
+               return;
+       }
+
+       state = xenbus_read_driver_state(dev->otherend);
+
+       DPRINTK("state is %d, %s, %s",
+               state, dev->otherend_watch.node, vec[XS_WATCH_PATH]);
+       if (drv->otherend_changed)
+               drv->otherend_changed(dev, state);
+}
+
+
+static int talk_to_otherend(struct xenbus_device *dev)
+{
+       struct xenbus_driver *drv = to_xenbus_driver(dev->dev.driver);
+       int err;
+
+       free_otherend_watch(dev);
+       free_otherend_details(dev);
+
+       err = drv->read_otherend_details(dev);
+       if (err)
+               return err;
+
+       return xenbus_watch_path2(dev, dev->otherend, "state",
+                                 &dev->otherend_watch, otherend_changed);
+}
+
+
 static int xenbus_dev_probe(struct device *_dev)
 {
        struct xenbus_device *dev = to_xenbus_device(_dev);
        struct xenbus_driver *drv = to_xenbus_driver(_dev->driver);
        const struct xenbus_device_id *id;
-
-       if (!drv->probe)
-               return -ENODEV;
+       int err;
+
+       DPRINTK("");
+
+       err = talk_to_otherend(dev);
+       if (err) {
+               printk(KERN_WARNING
+                      "xenbus_probe: talk_to_otherend on %s failed.\n",
+                      dev->nodename);
+               return err;
+       }
+
+       if (!drv->probe) {
+               err = -ENODEV;
+               goto fail;
+       }
 
        id = match_device(drv->ids, dev);
-       if (!id)
-               return -ENODEV;
-
-       return drv->probe(dev, id);
+       if (!id) {
+               err = -ENODEV;
+               goto fail;
+       }
+
+       err = drv->probe(dev, id);
+       if (err)
+               goto fail;
+
+       return 0;
+fail:
+       xenbus_dev_error(dev, err, "xenbus_dev_probe on %s", dev->nodename);
+       xenbus_switch_state(dev, NULL, XenbusStateClosed);
+       return -ENODEV;
+       
 }
 
 static int xenbus_dev_remove(struct device *_dev)
@@ -232,9 +366,16 @@
        struct xenbus_device *dev = to_xenbus_device(_dev);
        struct xenbus_driver *drv = to_xenbus_driver(_dev->driver);
 
-       if (!drv->remove)
-               return 0;
-       return drv->remove(dev);
+       DPRINTK("");
+
+       free_otherend_watch(dev);
+       free_otherend_details(dev);
+
+       if (drv->remove)
+               drv->remove(dev);
+
+       xenbus_switch_state(dev, NULL, XenbusStateClosed);
+       return 0;
 }
 
 static int xenbus_register_driver_common(struct xenbus_driver *drv,
@@ -254,16 +395,21 @@
        return ret;
 }
 
-int xenbus_register_driver(struct xenbus_driver *drv)
-{
+int xenbus_register_frontend(struct xenbus_driver *drv)
+{
+       drv->read_otherend_details = read_backend_details;
+
        return xenbus_register_driver_common(drv, &xenbus_frontend);
 }
-EXPORT_SYMBOL(xenbus_register_driver);
+EXPORT_SYMBOL(xenbus_register_frontend);
 
 int xenbus_register_backend(struct xenbus_driver *drv)
 {
+       drv->read_otherend_details = read_frontend_details;
+
        return xenbus_register_driver_common(drv, &xenbus_backend);
 }
+EXPORT_SYMBOL(xenbus_register_backend);
 
 void xenbus_unregister_driver(struct xenbus_driver *drv)
 {
@@ -304,6 +450,8 @@
        struct xenbus_device *xendev = to_xenbus_device(dev);
        struct xb_find_info *info = data;
        int len = strlen(info->nodename);
+
+       DPRINTK("%s", info->nodename);
 
        if (!strncmp(xendev->nodename, info->nodename, len)) {
                info->dev = xendev;
@@ -327,12 +475,15 @@
        } while (info.dev);
 }
 
-static void xenbus_release_device(struct device *dev)
+static void xenbus_dev_free(struct xenbus_device *xendev)
+{
+       kfree(xendev);
+}
+
+static void xenbus_dev_release(struct device *dev)
 {
        if (dev) {
-               struct xenbus_device *xendev = to_xenbus_device(dev);
-
-               kfree(xendev);
+               xenbus_dev_free(to_xenbus_device(dev));
        }
 }
 
@@ -369,13 +520,31 @@
 }
 DEVICE_ATTR(devtype, S_IRUSR | S_IRGRP | S_IROTH, xendev_show_devtype, NULL);
 
+
 static int xenbus_probe_node(struct xen_bus_type *bus,
                             const char *type,
                             const char *nodename)
 {
+#define CHECK_FAIL                             \
+       do {                                    \
+               if (err)                        \
+                       goto fail;              \
+       }                                       \
+       while (0)                               \
+
+
        int err;
        struct xenbus_device *xendev;
-       unsigned int stringlen;
+       size_t stringlen;
+       char *tmpstring;
+
+       XenbusState state = xenbus_read_driver_state(nodename);
+
+       if (state != XenbusStateInitialising) {
+               /* Device is not new, so ignore it.  This can happen if a
+                  device is going away after switching to Closed.  */
+               return 0;
+       }
 
        stringlen = strlen(nodename) + 1 + strlen(type) + 1;
        xendev = kmalloc(sizeof(*xendev) + stringlen, GFP_KERNEL);
@@ -384,31 +553,35 @@
        memset(xendev, 0, sizeof(*xendev));
 
        /* Copy the strings into the extra space. */
-       xendev->nodename = (char *)(xendev + 1);
-       strcpy(xendev->nodename, nodename);
-       xendev->devicetype = xendev->nodename + strlen(xendev->nodename) + 1;
-       strcpy(xendev->devicetype, type);
+
+       tmpstring = (char *)(xendev + 1);
+       strcpy(tmpstring, nodename);
+       xendev->nodename = tmpstring;
+
+       tmpstring += strlen(tmpstring) + 1;
+       strcpy(tmpstring, type);
+       xendev->devicetype = tmpstring;
 
        xendev->dev.parent = &bus->dev;
        xendev->dev.bus = &bus->bus;
-       xendev->dev.release = xenbus_release_device;
+       xendev->dev.release = xenbus_dev_release;
 
        err = bus->get_bus_id(xendev->dev.bus_id, xendev->nodename);
-       if (err) {
-               kfree(xendev);
-               return err;
-       }
+       CHECK_FAIL;
 
        /* Register with generic device framework. */
        err = device_register(&xendev->dev);
-       if (err) {
-               printk("XENBUS: Registering %s device %s: error %i\n",
-                      bus->bus.name, xendev->dev.bus_id, err);
-               kfree(xendev);
-       } else {
-               device_create_file(&xendev->dev, &dev_attr_nodename);
-               device_create_file(&xendev->dev, &dev_attr_devtype);
-       }
+       CHECK_FAIL;
+
+       device_create_file(&xendev->dev, &dev_attr_nodename);
+       device_create_file(&xendev->dev, &dev_attr_devtype);
+
+       return 0;
+
+#undef CHECK_FAIL
+
+fail:
+       xenbus_dev_free(xendev);
        return err;
 }
 
@@ -422,6 +595,8 @@
        if (!nodename)
                return -ENOMEM;
        
+       DPRINTK("%s", nodename);
+
        err = xenbus_probe_node(&xenbus_frontend, type, nodename);
        kfree(nodename);
        return err;
@@ -439,6 +614,8 @@
        if (!nodename)
                return -ENOMEM;
 
+       DPRINTK("%s\n", nodename);
+
        err = xenbus_probe_node(&xenbus_backend, type, nodename);
        kfree(nodename);
        return err;
@@ -451,6 +628,8 @@
        int err = 0;
        char **dir;
        unsigned int i, dir_n = 0;
+
+       DPRINTK("");
 
        nodename = kasprintf("%s/%s/%s", xenbus_backend.root, type, domid);
        if (!nodename)
@@ -574,12 +753,16 @@
 static void frontend_changed(struct xenbus_watch *watch,
                             const char **vec, unsigned int len)
 {
+       DPRINTK("");
+
        dev_changed(vec[XS_WATCH_PATH], &xenbus_frontend);
 }
 
 static void backend_changed(struct xenbus_watch *watch,
                            const char **vec, unsigned int len)
 {
+       DPRINTK("");
+
        dev_changed(vec[XS_WATCH_PATH], &xenbus_backend);
 }
 
@@ -599,6 +782,8 @@
        int err = 0;
        struct xenbus_driver *drv;
        struct xenbus_device *xdev;
+
+       DPRINTK("");
 
        if (dev->driver == NULL)
                return 0;
@@ -607,33 +792,49 @@
        if (drv->suspend)
                err = drv->suspend(xdev);
        if (err)
-               printk("xenbus: suspend %s failed: %i\n", dev->bus_id, err);
+               printk(KERN_WARNING
+                      "xenbus: suspend %s failed: %i\n", dev->bus_id, err);
        return 0;
 }
 
 static int resume_dev(struct device *dev, void *data)
 {
-       int err = 0;
+       int err;
        struct xenbus_driver *drv;
        struct xenbus_device *xdev;
+
+       DPRINTK("");
 
        if (dev->driver == NULL)
                return 0;
        drv = to_xenbus_driver(dev->driver);
        xdev = container_of(dev, struct xenbus_device, dev);
+
+       err = talk_to_otherend(xdev);
+       if (err) {
+               printk(KERN_WARNING
+                      "xenbus: resume (talk_to_otherend) %s failed: %i\n",
+                      dev->bus_id, err);
+               return err;
+       }
+
        if (drv->resume)
                err = drv->resume(xdev);
        if (err)
-               printk("xenbus: resume %s failed: %i\n", dev->bus_id, err);
-       return 0;
+               printk(KERN_WARNING
+                      "xenbus: resume %s failed: %i\n", dev->bus_id, err);
+       return err;
 }
 
 void xenbus_suspend(void)
 {
+       DPRINTK("");
+
        bus_for_each_dev(&xenbus_frontend.bus, NULL, NULL, suspend_dev);
        bus_for_each_dev(&xenbus_backend.bus, NULL, NULL, suspend_dev);
        xs_suspend();
 }
+EXPORT_SYMBOL(xenbus_suspend);
 
 void xenbus_resume(void)
 {
@@ -642,6 +843,7 @@
        bus_for_each_dev(&xenbus_frontend.bus, NULL, NULL, resume_dev);
        bus_for_each_dev(&xenbus_backend.bus, NULL, NULL, resume_dev);
 }
+EXPORT_SYMBOL(xenbus_resume);
 
 
 /* A flag to determine if xenstored is 'ready' (i.e. has started) */
@@ -652,7 +854,7 @@
 {
        int ret = 0;
 
-        if(xenstored_ready > 0) 
+       if (xenstored_ready > 0) 
                ret = nb->notifier_call(nb, 0, NULL);
        else 
                notifier_chain_register(&xenstore_chain, nb);
@@ -682,9 +884,7 @@
        register_xenbus_watch(&be_watch);
 
        /* Notify others that xenstore is up */
-       notifier_call_chain(&xenstore_chain, 0, 0);
-
-       return;
+       notifier_call_chain(&xenstore_chain, 0, NULL);
 }
 
 
@@ -716,10 +916,10 @@
 {
        int err = 0, dom0;
 
-       printk("xenbus_probe_init\n");
+       DPRINTK("");
 
        if (xen_init() < 0) {
-               printk("xen_init failed\n");
+               DPRINTK("failed");
                return -ENODEV;
        }
 
@@ -773,7 +973,8 @@
        /* Initialize the interface to xenstore. */
        err = xs_init(); 
        if (err) {
-               printk("XENBUS: Error initializing xenstore comms: %i\n", err);
+               printk(KERN_WARNING
+                      "XENBUS: Error initializing xenstore comms: %i\n", err);
                return err; 
        }
 
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_xs.c
--- a/linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_xs.c       Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_xs.c       Sat Nov 19 
05:16:29 2005
@@ -199,6 +199,7 @@
        int err;
 
        msg.tx_id = (u32)(unsigned long)t;
+       msg.req_id = 0;
        msg.type = type;
        msg.len = 0;
        for (i = 0; i < num_vecs; i++)
@@ -517,89 +518,6 @@
 }
 EXPORT_SYMBOL(xenbus_printf);
 
-/**
- * Return the path to the error node for the given device, or NULL on failure.
- * If the value returned is non-NULL, then it is the caller's to kfree.
- */
-static char *error_path(struct xenbus_device *dev)
-{
-       char *path_buffer = kmalloc(strlen("error/") + strlen(dev->nodename) +
-                                   1, GFP_KERNEL);
-       if (path_buffer == NULL) {
-               return NULL;
-       }
-
-       strcpy(path_buffer, "error/");
-       strcpy(path_buffer + strlen("error/"), dev->nodename);
-
-       return path_buffer;
-}
-
-/* Report a (negative) errno into the store, with explanation. */
-void xenbus_dev_error(struct xenbus_device *dev, int err, const char *fmt, ...)
-{
-       va_list ap;
-       int ret;
-       unsigned int len;
-       char *printf_buffer = NULL, *path_buffer = NULL;
-
-       printf_buffer = kmalloc(PRINTF_BUFFER_SIZE, GFP_KERNEL);
-       if (printf_buffer == NULL)
-               goto fail;
-
-       len = sprintf(printf_buffer, "%i ", -err);
-       va_start(ap, fmt);
-       ret = vsnprintf(printf_buffer+len, PRINTF_BUFFER_SIZE-len, fmt, ap);
-       va_end(ap);
-
-       BUG_ON(len + ret > PRINTF_BUFFER_SIZE-1);
-       dev->has_error = 1;
-
-       path_buffer = error_path(dev);
-
-       if (path_buffer == NULL) {
-               printk("xenbus: failed to write error node for %s (%s)\n",
-                      dev->nodename, printf_buffer);
-               goto fail;
-       }
-
-       if (xenbus_write(NULL, path_buffer, "error", printf_buffer) != 0) {
-               printk("xenbus: failed to write error node for %s (%s)\n",
-                      dev->nodename, printf_buffer);
-               goto fail;
-       }
-
-fail:
-       if (printf_buffer)
-               kfree(printf_buffer);
-       if (path_buffer)
-               kfree(path_buffer);
-}
-EXPORT_SYMBOL(xenbus_dev_error);
-
-/* Clear any error. */
-void xenbus_dev_ok(struct xenbus_device *dev)
-{
-       if (dev->has_error) {
-               char *path_buffer = error_path(dev);
-
-               if (path_buffer == NULL) {
-                       printk("xenbus: failed to clear error node for %s\n",
-                              dev->nodename);
-                       return;
-               }
-
-               if (xenbus_rm(NULL, path_buffer, "error") != 0)
-                       printk("xenbus: failed to clear error node for %s\n",
-                              dev->nodename);
-               else
-                       dev->has_error = 0;
-
-               kfree(path_buffer);
-       }
-}
-EXPORT_SYMBOL(xenbus_dev_ok);
-       
 /* Takes tuples of names, scanf-style args, and void **, NULL terminated. */
 int xenbus_gather(struct xenbus_transaction *t, const char *dir, ...)
 {
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/asm-i386/hypervisor.h
--- a/linux-2.6-xen-sparse/include/asm-xen/asm-i386/hypervisor.h        Sat Nov 
19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/asm-i386/hypervisor.h        Sat Nov 
19 05:16:29 2005
@@ -39,15 +39,11 @@
 #include <asm/ptrace.h>
 #include <asm/page.h>
 #if defined(__i386__)
-# if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
 #  ifdef CONFIG_X86_PAE
 #   include <asm-generic/pgtable-nopud.h>
 #  else
 #   include <asm-generic/pgtable-nopmd.h>
 #  endif
-# else
-#  define pud_t pgd_t
-# endif
 #endif
 
 extern shared_info_t *HYPERVISOR_shared_info;
@@ -113,22 +109,6 @@
 void xen_invlpg_mask(cpumask_t *mask, unsigned long ptr);
 #endif
 
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
-/* 
-** XXX SMH: 2.4 doesn't have percpu.h (or support SMP guests) so just 
-** include sufficient #defines to allow the below to build. 
-*/
-#define DEFINE_PER_CPU(type, name) \
-    __typeof__(type) per_cpu__##name
-
-#define per_cpu(var, cpu)           (*((void)cpu, &per_cpu__##var))
-#define __get_cpu_var(var)          per_cpu__##var
-#define DECLARE_PER_CPU(type, name) extern __typeof__(type) per_cpu__##name
-
-#define EXPORT_PER_CPU_SYMBOL(var) EXPORT_SYMBOL(per_cpu__##var)
-#define EXPORT_PER_CPU_SYMBOL_GPL(var) EXPORT_SYMBOL_GPL(per_cpu__##var)
-#endif /* linux < 2.6.0 */
-
 /* Returns zero on success else negative errno. */
 int xen_create_contiguous_region(
     unsigned long vstart, unsigned int order, unsigned int address_bits);
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/asm-i386/io.h
--- a/linux-2.6-xen-sparse/include/asm-xen/asm-i386/io.h        Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/asm-i386/io.h        Sat Nov 19 
05:16:29 2005
@@ -228,7 +228,7 @@
  * used as the IO-area pointer (it can be iounmapped as well, so the
  * analogy with PCI is quite large):
  */
-#define __ISA_IO_base ((char __iomem *)(PAGE_OFFSET))
+#define __ISA_IO_base ((char __iomem *)(fix_to_virt(FIX_ISAMAP_BEGIN)))
 
 #define isa_readb(a) readb(__ISA_IO_base + (a))
 #define isa_readw(a) readw(__ISA_IO_base + (a))
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/asm-i386/page.h
--- a/linux-2.6-xen-sparse/include/asm-xen/asm-i386/page.h      Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/asm-i386/page.h      Sat Nov 19 
05:16:29 2005
@@ -84,6 +84,11 @@
                : "=r" (pfn) : "m" (machine_to_phys_mapping[mfn]) );
 
        return pfn;
+}
+
+static inline void set_phys_to_machine(unsigned long pfn, unsigned long mfn)
+{
+       phys_to_machine_mapping[pfn] = mfn;
 }
 
 /* Definitions for machine and pseudophysical addresses. */
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/asm-i386/pgtable.h
--- a/linux-2.6-xen-sparse/include/asm-xen/asm-i386/pgtable.h   Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/asm-i386/pgtable.h   Sat Nov 19 
05:16:29 2005
@@ -438,9 +438,8 @@
 
 #define arbitrary_virt_to_machine(__va)                                        
\
 ({                                                                     \
-       pte_t *__pte = virt_to_ptep(__va);                              \
-       maddr_t __pa = (maddr_t)pte_mfn(*__pte) << PAGE_SHIFT;          \
-       __pa | ((unsigned long)(__va) & (PAGE_SIZE-1));                 \
+       maddr_t m = (maddr_t)pte_mfn(*virt_to_ptep(__va)) << PAGE_SHIFT;\
+       m | ((unsigned long)(__va) & (PAGE_SIZE-1));                    \
 })
 
 #endif /* !__ASSEMBLY__ */
@@ -450,11 +449,11 @@
 #endif /* !CONFIG_DISCONTIGMEM */
 
 int direct_remap_pfn_range(struct vm_area_struct *vma,
-                            unsigned long address, 
-                            unsigned long mfn,
-                            unsigned long size, 
-                            pgprot_t prot,
-                            domid_t  domid);
+                           unsigned long address, 
+                           unsigned long mfn,
+                           unsigned long size, 
+                           pgprot_t prot,
+                           domid_t  domid);
 int direct_kernel_remap_pfn_range(unsigned long address, 
                                  unsigned long mfn,
                                  unsigned long size, 
@@ -462,7 +461,7 @@
                                  domid_t  domid);
 int create_lookup_pte_addr(struct mm_struct *mm,
                            unsigned long address,
-                           unsigned long *ptep);
+                           uint64_t *ptep);
 int touch_pte_range(struct mm_struct *mm,
                     unsigned long address,
                     unsigned long size);
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/io.h
--- a/linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/io.h      Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/io.h      Sat Nov 19 
05:16:29 2005
@@ -298,7 +298,7 @@
  * used as the IO-area pointer (it can be iounmapped as well, so the
  * analogy with PCI is quite large):
  */
-#define __ISA_IO_base ((char __iomem *)(PAGE_OFFSET))
+#define __ISA_IO_base ((char __iomem *)(fix_to_virt(FIX_ISAMAP_BEGIN)))
 
 #define isa_readb(a) readb(__ISA_IO_base + (a))
 #define isa_readw(a) readw(__ISA_IO_base + (a))
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/page.h
--- a/linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/page.h    Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/page.h    Sat Nov 19 
05:16:29 2005
@@ -88,6 +88,11 @@
        return pfn;
 }
 
+static inline void set_phys_to_machine(unsigned long pfn, unsigned long mfn)
+{
+       phys_to_machine_mapping[pfn] = mfn;
+}
+
 /* Definitions for machine and pseudophysical addresses. */
 typedef unsigned long paddr_t;
 typedef unsigned long maddr_t;
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/pgtable.h
--- a/linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/pgtable.h Sat Nov 19 
05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/asm-x86_64/pgtable.h Sat Nov 19 
05:16:29 2005
@@ -29,9 +29,8 @@
 
 #define arbitrary_virt_to_machine(__va)                                        
\
 ({                                                                     \
-       pte_t *__pte = virt_to_ptep(__va);                              \
-       unsigned long __pa = (*(unsigned long *)__pte) & PAGE_MASK;     \
-       __pa | ((unsigned long)(__va) & (PAGE_SIZE-1));                 \
+       maddr_t m = (maddr_t)pte_mfn(*virt_to_ptep(__va)) << PAGE_SHIFT;\
+       m | ((unsigned long)(__va) & (PAGE_SIZE-1));                    \
 })
 #endif
 
@@ -541,7 +540,7 @@
 
 int create_lookup_pte_addr(struct mm_struct *mm,
                            unsigned long address,
-                           unsigned long *ptep);
+                           uint64_t *ptep);
 
 int touch_pte_range(struct mm_struct *mm,
                     unsigned long address,
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/linux-public/privcmd.h
--- a/linux-2.6-xen-sparse/include/asm-xen/linux-public/privcmd.h       Sat Nov 
19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/linux-public/privcmd.h       Sat Nov 
19 05:16:29 2005
@@ -55,6 +55,11 @@
        unsigned long *arr; /* array of mfns - top nibble set on err */
 } privcmd_mmapbatch_t; 
 
+typedef struct privcmd_m2pmfns { 
+       int num;    /* max number of mfns to return */
+       unsigned long *arr; /* array of mfns */
+} privcmd_m2pmfns_t; 
+
 typedef struct privcmd_blkmsg
 {
        unsigned long op;
@@ -69,12 +74,11 @@
  */
 #define IOCTL_PRIVCMD_HYPERCALL                                        \
        _IOC(_IOC_NONE, 'P', 0, sizeof(privcmd_hypercall_t))
-
 #define IOCTL_PRIVCMD_MMAP                                     \
        _IOC(_IOC_NONE, 'P', 2, sizeof(privcmd_mmap_t))
 #define IOCTL_PRIVCMD_MMAPBATCH                                        \
        _IOC(_IOC_NONE, 'P', 3, sizeof(privcmd_mmapbatch_t))
-#define IOCTL_PRIVCMD_GET_MACH2PHYS_START_MFN                  \
+#define IOCTL_PRIVCMD_GET_MACH2PHYS_MFNS                       \
        _IOC(_IOC_READ, 'P', 4, sizeof(unsigned long))
 
 #endif /* __LINUX_PUBLIC_PRIVCMD_H__ */
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/xenbus.h
--- a/linux-2.6-xen-sparse/include/asm-xen/xenbus.h     Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/xenbus.h     Sat Nov 19 05:16:29 2005
@@ -35,10 +35,48 @@
 #include <asm/semaphore.h>
 #include <asm-xen/xen-public/io/xs_wire.h>
 
+/* Register callback to watch this node. */
+struct xenbus_watch
+{
+       struct list_head list;
+
+       /* Path being watched. */
+       const char *node;
+
+       /* Callback (executed in a process context with no locks held). */
+       void (*callback)(struct xenbus_watch *,
+                        const char **vec, unsigned int len);
+};
+
+
+/* The state of either end of the Xenbus, i.e. the current communication
+   status of initialisation across the bus.  States here imply nothing about
+   the state of the connection between the driver and the kernel's device
+   layers.  */
+typedef enum
+{
+  XenbusStateUnknown      = 0,
+  XenbusStateInitialising = 1,
+  XenbusStateInitWait     = 2,  /* Finished early initialisation, but waiting
+                                   for information from the peer or hotplug
+                                  scripts. */
+  XenbusStateInitialised  = 3,  /* Initialised and waiting for a connection
+                                  from the peer. */
+  XenbusStateConnected    = 4,
+  XenbusStateClosing      = 5,  /* The device is being closed due to an error
+                                  or an unplug event. */
+  XenbusStateClosed       = 6
+
+} XenbusState;
+
+
 /* A xenbus device. */
 struct xenbus_device {
-       char *devicetype;
-       char *nodename;
+       const char *devicetype;
+       const char *nodename;
+       const char *otherend;
+       int otherend_id;
+       struct xenbus_watch otherend_watch;
        struct device dev;
        int has_error;
        void *data;
@@ -62,11 +100,14 @@
        const struct xenbus_device_id *ids;
        int (*probe)(struct xenbus_device *dev,
                     const struct xenbus_device_id *id);
+       void (*otherend_changed)(struct xenbus_device *dev,
+                                XenbusState backend_state);
        int (*remove)(struct xenbus_device *dev);
        int (*suspend)(struct xenbus_device *dev);
        int (*resume)(struct xenbus_device *dev);
        int (*hotplug)(struct xenbus_device *, char **, int, char *, int);
        struct device_driver driver;
+       int (*read_otherend_details)(struct xenbus_device *dev);
 };
 
 static inline struct xenbus_driver *to_xenbus_driver(struct device_driver *drv)
@@ -74,7 +115,7 @@
        return container_of(drv, struct xenbus_driver, driver);
 }
 
-int xenbus_register_driver(struct xenbus_driver *drv);
+int xenbus_register_frontend(struct xenbus_driver *drv);
 int xenbus_register_backend(struct xenbus_driver *drv);
 void xenbus_unregister_driver(struct xenbus_driver *drv);
 
@@ -108,25 +149,6 @@
  * sprintf-style type string, and pointer. Returns 0 or errno.*/
 int xenbus_gather(struct xenbus_transaction *t, const char *dir, ...);
 
-/* Report a (negative) errno into the store, with explanation. */
-void xenbus_dev_error(struct xenbus_device *dev, int err, const char *fmt,...);
-
-/* Clear any error. */
-void xenbus_dev_ok(struct xenbus_device *dev);
-
-/* Register callback to watch this node. */
-struct xenbus_watch
-{
-       struct list_head list;
-
-       /* Path being watched. */
-       char *node;
-
-       /* Callback (executed in a process context with no locks held). */
-       void (*callback)(struct xenbus_watch *,
-                        const char **vec, unsigned int len);
-};
-
 /* notifer routines for when the xenstore comes up */
 int register_xenstore_notifier(struct notifier_block *nb);
 void unregister_xenstore_notifier(struct notifier_block *nb);
@@ -152,6 +174,89 @@
 })
 
 #define XENBUS_EXIST_ERR(err) ((err) == -ENOENT || (err) == -ERANGE)
+
+
+/**
+ * Register a watch on the given path, using the given xenbus_watch structure
+ * for storage, and the given callback function as the callback.  Return 0 on
+ * success, or -errno on error.  On success, the given path will be saved as
+ * watch->node, and remains the caller's to free.  On error, watch->node will
+ * be NULL, the device will switch to XenbusStateClosing, and the error will
+ * be saved in the store.
+ */
+int xenbus_watch_path(struct xenbus_device *dev, const char *path,
+                     struct xenbus_watch *watch, 
+                     void (*callback)(struct xenbus_watch *,
+                                      const char **, unsigned int));
+
+
+/**
+ * Register a watch on the given path/path2, using the given xenbus_watch
+ * structure for storage, and the given callback function as the callback.
+ * Return 0 on success, or -errno on error.  On success, the watched path
+ * (path/path2) will be saved as watch->node, and becomes the caller's to
+ * kfree().  On error, watch->node will be NULL, so the caller has nothing to
+ * free, the device will switch to XenbusStateClosing, and the error will be
+ * saved in the store.
+ */
+int xenbus_watch_path2(struct xenbus_device *dev, const char *path,
+                      const char *path2, struct xenbus_watch *watch, 
+                      void (*callback)(struct xenbus_watch *,
+                                       const char **, unsigned int));
+
+
+/**
+ * Advertise in the store a change of the given driver to the given new_state.
+ * Perform the change inside the given transaction xbt.  xbt may be NULL, in
+ * which case this is performed inside its own transaction.  Return 0 on
+ * success, or -errno on error.  On error, the device will switch to
+ * XenbusStateClosing, and the error will be saved in the store.
+ */
+int xenbus_switch_state(struct xenbus_device *dev,
+                       struct xenbus_transaction *xbt,
+                       XenbusState new_state);
+
+
+/**
+ * Grant access to the given ring_mfn to the peer of the given device.  Return
+ * 0 on success, or -errno on error.  On error, the device will switch to
+ * XenbusStateClosing, and the error will be saved in the store.
+ */
+int xenbus_grant_ring(struct xenbus_device *dev, unsigned long ring_mfn);
+
+
+/**
+ * Allocate an event channel for the given xenbus_device, assigning the newly
+ * created local port to *port.  Return 0 on success, or -errno on error.  On
+ * error, the device will switch to XenbusStateClosing, and the error will be
+ * saved in the store.
+ */
+int xenbus_alloc_evtchn(struct xenbus_device *dev, int *port);
+
+
+/**
+ * Return the state of the driver rooted at the given store path, or
+ * XenbusStateClosed if no state can be read.
+ */
+XenbusState xenbus_read_driver_state(const char *path);
+
+
+/***
+ * Report the given negative errno into the store, along with the given
+ * formatted message.
+ */
+void xenbus_dev_error(struct xenbus_device *dev, int err, const char *fmt,
+                     ...);
+
+
+/***
+ * Equivalent to xenbus_dev_error(dev, err, fmt, args), followed by
+ * xenbus_switch_state(dev, NULL, XenbusStateClosing) to schedule an orderly
+ * closedown of this driver and its peer.
+ */
+void xenbus_dev_fatal(struct xenbus_device *dev, int err, const char *fmt,
+                     ...);
+
 
 #endif /* _ASM_XEN_XENBUS_H */
 
diff -r e62c54ab862f -r 878a9891b056 tools/Makefile
--- a/tools/Makefile    Sat Nov 19 05:06:09 2005
+++ b/tools/Makefile    Sat Nov 19 05:16:29 2005
@@ -11,6 +11,7 @@
 SUBDIRS += firmware
 SUBDIRS += security
 SUBDIRS += console
+SUBDIRS += xenmon
 ifeq ($(VTPM_TOOLS),y)
 SUBDIRS += vtpm_manager
 SUBDIRS += vtpm
diff -r e62c54ab862f -r 878a9891b056 tools/blktap/blkif.c
--- a/tools/blktap/blkif.c      Sat Nov 19 05:06:09 2005
+++ b/tools/blktap/blkif.c      Sat Nov 19 05:16:29 2005
@@ -108,8 +108,7 @@
         }
         pblkif = &curs->hash_next;
     }
-    if (blkif != NULL)
-        free(blkif);
+    free(blkif);
 }
 
 void blkif_register_request_hook(blkif_t *blkif, char *name, 
diff -r e62c54ab862f -r 878a9891b056 tools/blktap/parallax/blockstore.c
--- a/tools/blktap/parallax/blockstore.c        Sat Nov 19 05:06:09 2005
+++ b/tools/blktap/parallax/blockstore.c        Sat Nov 19 05:16:29 2005
@@ -604,8 +604,7 @@
     return block;
 
     err:
-    if (qe->block)
-        free(qe->block);
+    free(qe->block);
     free((void *)qe);
     return NULL;
 }
@@ -1072,7 +1071,7 @@
  *
  *   @return: pointer to new block, NULL on error
  */
-void *newblock() {
+void *newblock(void) {
     void *block = malloc(BLOCK_SIZE);
     if (block == NULL) {
         perror("newblock");
@@ -1089,7 +1088,6 @@
  *   @block: block to be freed
  */
 void freeblock(void *block) {
-    if (block != NULL)
         free(block);
 }
 
diff -r e62c54ab862f -r 878a9891b056 tools/blktap/parallax/blockstored.c
--- a/tools/blktap/parallax/blockstored.c       Sat Nov 19 05:06:09 2005
+++ b/tools/blktap/parallax/blockstored.c       Sat Nov 19 05:16:29 2005
@@ -232,7 +232,7 @@
  *
  *   @return: pointer to new block, NULL on error
  */
-void *newblock() {
+void *newblock(void) {
     void *block = malloc(BLOCK_SIZE);
     if (block == NULL) {
         perror("newblock");
@@ -249,7 +249,6 @@
  *   @block: block to be freed
  */
 void freeblock(void *block) {
-    if (block != NULL)
         free(block);
 }
 
diff -r e62c54ab862f -r 878a9891b056 tools/blktap/parallax/requests-async.c
--- a/tools/blktap/parallax/requests-async.c    Sat Nov 19 05:06:09 2005
+++ b/tools/blktap/parallax/requests-async.c    Sat Nov 19 05:16:29 2005
@@ -715,7 +715,7 @@
         r.u.i  = -1;
         /* free any saved node vals. */
         for (i=0; i<3; i++)
-            if (req->radix[i] != 0) free(req->radix[i]);
+            free(req->radix[i]);
         free(req);
         cb(r, req_param);
     }
diff -r e62c54ab862f -r 878a9891b056 tools/blktap/xenbus.c
--- a/tools/blktap/xenbus.c     Sat Nov 19 05:06:09 2005
+++ b/tools/blktap/xenbus.c     Sat Nov 19 05:16:29 2005
@@ -339,10 +339,8 @@
     /* Free everything else. */
     if (be->blkif)
         free_blkif(be->blkif);
-    if (be->frontpath)
-        free(be->frontpath);
-    if (be->backpath)
-        free(be->backpath);
+    free(be->frontpath);
+    free(be->backpath);
     free(be);
     return 0;
 }
@@ -406,8 +404,7 @@
     return;
 
  fail:
-    if (fepath)
-        free(fepath);
+    free(fepath);
 }
 
 
@@ -460,9 +457,7 @@
     }
 
  fail:
-    if (path)
-        free(path);
-
+    free(path);
 }
 
 static void blkback_probe(struct xs_handle *h, struct xenbus_watch *w, 
@@ -537,12 +532,10 @@
        return;
 
  free_be:
-       if ((be) && (be->backend_watch.node))
+       if (be && (be->backend_watch.node))
             unregister_xenbus_watch(h, &be->backend_watch);
-       if (frontend)
-            free(frontend);
-        if (bepath)
-            free(bepath);
+        free(frontend);
+        free(bepath);
        free(be);
        return;
 }
diff -r e62c54ab862f -r 878a9891b056 tools/check/check_hotplug
--- a/tools/check/check_hotplug Sat Nov 19 05:06:09 2005
+++ b/tools/check/check_hotplug Sat Nov 19 05:16:29 2005
@@ -7,7 +7,7 @@
    exit 1
 }
 
-if [ -x /sbin/udev ] && [ ! -z `udev -V` ] && [ `udev -V` -ge 059 ]; then
+if [ -x /sbin/udev ] && [ ! -z `/sbin/udev -V` ] && [ `/sbin/udev -V` -ge 059 
]; then
   exit 0
 fi
 
diff -r e62c54ab862f -r 878a9891b056 tools/console/daemon/io.c
--- a/tools/console/daemon/io.c Sat Nov 19 05:06:09 2005
+++ b/tools/console/daemon/io.c Sat Nov 19 05:16:29 2005
@@ -114,7 +114,7 @@
                        buffer->data, buffer->max_capacity);
                buffer->data = realloc(buffer->data,
                                       buffer->max_capacity);
-               buffer->capacity = buffer->max_capacity;
+               buffer->size = buffer->capacity = buffer->max_capacity;
        }
 }
 
@@ -344,8 +344,7 @@
 
        return dom;
  out:
-       if (dom->conspath)
-               free(dom->conspath);
+       free(dom->conspath);
        free(dom);
        return NULL;
 }
@@ -380,20 +379,16 @@
        if (!buffer_empty(&d->buffer))
                return;
 
-       if (d->buffer.data) {
-               free(d->buffer.data);
-               d->buffer.data = NULL;
-       }
-
        if (d->tty_fd != -1) {
                close(d->tty_fd);
                d->tty_fd = -1;
        }
 
-       if (d->conspath) {
-               free(d->conspath);
-               d->conspath = NULL;
-       }
+       free(d->buffer.data);
+       d->buffer.data = NULL;
+
+       free(d->conspath);
+       d->conspath = NULL;
 
        remove_domain(d);
 }
diff -r e62c54ab862f -r 878a9891b056 tools/examples/Makefile
--- a/tools/examples/Makefile   Sat Nov 19 05:06:09 2005
+++ b/tools/examples/Makefile   Sat Nov 19 05:16:29 2005
@@ -41,7 +41,7 @@
 ifeq ($(findstring $(DI),$(DE)),$(DI))
 HOTPLUGS=install-hotplug install-udev
 else
-ifeq ($(shell [ -x /sbin/udev ] && [ ! -z `udev -V` ] && [ `/sbin/udev -V` -ge 
059 ] && echo 1),1)
+ifeq ($(shell [ -x /sbin/udev ] && [ ! -z `/sbin/udev -V` ] && [ `/sbin/udev 
-V` -ge 059 ] && echo 1),1)
 HOTPLUGS=install-udev
 else
 HOTPLUGS=install-hotplug
diff -r e62c54ab862f -r 878a9891b056 tools/examples/block
--- a/tools/examples/block      Sat Nov 19 05:06:09 2005
+++ b/tools/examples/block      Sat Nov 19 05:16:29 2005
@@ -2,6 +2,12 @@
 
 dir=$(dirname "$0")
 . "$dir/block-common.sh"
+
+case "$command" in
+    online | offline)
+        exit 0
+        ;;
+esac
 
 expand_dev() {
   local dev
@@ -16,10 +22,10 @@
   echo -n $dev
 }
 
-t=$(xenstore_read "$XENBUS_PATH"/type || true)
+t=$(xenstore_read_default "$XENBUS_PATH"/type "MISSING")
 
 case "$command" in 
-  bind)
+  add)
     p=$(xenstore_read "$XENBUS_PATH"/params)
     case $t in 
       phy)
@@ -38,32 +44,25 @@
        done
        exit 1
        ;;
-
-      *)
-        [ -x /etc/xen/scripts/block-"$t" ] && \
-           /etc/xen/scripts/block-"$t" bind $p
-       ;;
     esac
     ;;
 
-  unbind)
-    node=$(xenstore_read "$XENBUS_PATH"/node)
+  remove)
     case $t in 
       phy)
        exit 0
        ;;
 
       file)
+        node=$(xenstore_read "$XENBUS_PATH"/node)
        losetup -d $node
        exit 0
        ;;
-
-      *)
-        [ -x /etc/xen/scripts/block-"$t" ] && \
-           /etc/xen/scripts/block-"$t" unbind $node
-       ;;
-
     esac
     ;;
 
 esac
+
+# If we've reached here, $t is neither phy nor file, so fire a helper script.
+[ -x /etc/xen/scripts/block-"$t" ] && \
+  /etc/xen/scripts/block-"$t" "$command" $node
diff -r e62c54ab862f -r 878a9891b056 tools/examples/block-common.sh
--- a/tools/examples/block-common.sh    Sat Nov 19 05:06:09 2005
+++ b/tools/examples/block-common.sh    Sat Nov 19 05:16:29 2005
@@ -19,9 +19,12 @@
 dir=$(dirname "$0")
 . "$dir/xen-hotplug-common.sh"
 
-command="$1"
+findCommand "$@"
 
-if [ "$command" != "bind" ] && [ "$command" != "unbind" ]
+if [ "$command" != "online" ]  &&
+   [ "$command" != "offline" ] &&
+   [ "$command" != "add" ]     &&
+   [ "$command" != "remove" ]
 then
   log err "Invalid command: $command"
   exit 1
diff -r e62c54ab862f -r 878a9891b056 tools/examples/network-bridge
--- a/tools/examples/network-bridge     Sat Nov 19 05:06:09 2005
+++ b/tools/examples/network-bridge     Sat Nov 19 05:16:29 2005
@@ -16,29 +16,38 @@
 #
 # Usage:
 #
-# network (start|stop|status) {VAR=VAL}*
+# network-bridge (start|stop|status) {VAR=VAL}*
 #
 # Vars:
 #
-# vifnum     Virtual device number to use (default 0). Numbers >=1
+# vifnum     Virtual device number to use (default 0). Numbers >=8
 #            require the netback driver to have nloopbacks set to a
-#            higher value than its default of 1.
+#            higher value than its default of 8.
 # bridge     The bridge to use (default xenbr${vifnum}).
 # netdev     The interface to add to the bridge (default eth${vifnum}).
 # antispoof  Whether to use iptables to prevent spoofing (default no).
 #
+# Internal Vars:
+# pdev="p${netdev}"
+# vdev="veth${vifnum}"
+# vif0="vif0.${vifnum}"
+#
 # start:
-# Creates the bridge and enslaves netdev to it.
-# Copies the IP addresses from netdev to the bridge.
-# Deletes the routes to netdev and adds them on bridge.
+# Creates the bridge
+# Copies the IP and MAC addresses from netdev to vdev
+# Renames netdev to be pdev 
+# Renames vdev to be netdev 
+# Enslaves pdev, vdev to bridge
 #
 # stop:
-# Removes netdev from the bridge.
-# Deletes the routes to bridge and adds them to netdev.
+# Removes netdev from the bridge
+# Transfers addresses, routes from netdev to pdev
+# Renames netdev to vdev
+# Renames pdev to netdev 
+# Deletes bridge
 #
 # status:
-# Print ifconfig for netdev and bridge.
-# Print routes.
+# Print addresses, interfaces, routes
 #
 #============================================================================
 
@@ -97,23 +106,12 @@
 s@\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+/[0-9]\+\)@\1@
 s/${src}/dev ${dst}/
 " | sh -e
-    # Remove automatic routes on destionation device
+    # Remove automatic routes on destination device
     ip route list | sed -ne "
 /dev ${dst}\( \|$\)/ {
   s/^/ip route del /
   p
 }" | sh -e
-}
-
-# Usage: del_addrs src
-del_addrs () {
-    local src=$1
-    ip addr show dev ${src} | egrep '^ *inet ' | sed -e "
-s/inet/ip addr del/
-s@\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+\)/[0-9]\+@\1@
-s/${src}/dev ${src}/
-" | sh -e
-    ip link set dev ${dst} up
 }
 
 # Usage: transfer_routes src dst
@@ -140,6 +138,23 @@
 }" | sh -e
 }
 
+
+##
+# link_exists interface
+#
+# Returns 0 if the interface named exists (whether up or down), 1 otherwise.
+#
+link_exists()
+{
+    if ip link show "$1" >&/dev/null
+    then
+        return 0
+    else
+        return 1
+    fi
+}
+
+
 # Usage: create_bridge bridge
 create_bridge () {
     local bridge=$1
@@ -195,8 +210,12 @@
        return
     fi
 
-    if ! ip link show 2>/dev/null | grep -q "^[0-9]*: ${vdev}"; then
-        echo "
+    if ! link_exists "$vdev"; then
+        if link_exists "$pdev"; then
+            # The device is already up.
+            return
+        else
+            echo "
 Link $vdev is missing.
 This may be because you have reached the limit of the number of interfaces
 that the loopback driver supports.  If the loopback driver is a module, you
@@ -204,12 +223,13 @@
 driver is compiled statically into the kernel, then you may set the parameter
 using loopback.nloopbacks=<N> on the domain 0 kernel command line.
 " >&2
-        exit 1
+            exit 1
+        fi
     fi
 
     create_bridge ${bridge}
 
-    if ip link show ${vdev} 2>/dev/null >/dev/null; then
+    if link_exists "$vdev"; then
        mac=`ip link show ${netdev} | grep 'link\/ether' | sed -e 's/.*ether 
\(..:..:..:..:..:..\).*/\1/'`
        preiftransfer ${netdev}
        transfer_addrs ${netdev} ${vdev}
@@ -262,11 +282,11 @@
     if [ "${bridge}" == "null" ]; then
        return
     fi
-    if ! ip link show ${bridge} >/dev/null 2>&1; then
+    if ! link_exists "$bridge"; then
        return
     fi
 
-    if ip link show ${pdev} 2>/dev/null >/dev/null; then
+    if link_exists "$pdev"; then
        ip link set dev ${vif0} down
        mac=`ip link show ${netdev} | grep 'link\/ether' | sed -e 's/.*ether 
\(..:..:..:..:..:..\).*/\1/'`
        transfer_addrs ${netdev} ${pdev}
diff -r e62c54ab862f -r 878a9891b056 tools/examples/vif-bridge
--- a/tools/examples/vif-bridge Sat Nov 19 05:06:09 2005
+++ b/tools/examples/vif-bridge Sat Nov 19 05:16:29 2005
@@ -9,7 +9,7 @@
 # places, then this script is the default.
 #
 # Usage:
-# vif-bridge (up|down)
+# vif-bridge (add|remove|online|offline)
 #
 # Environment vars:
 # vif         vif interface name (required).
@@ -47,7 +47,7 @@
 fi
 
 case "$command" in
-    up)
+    online)
         if brctl show "$bridge" | grep "$vif" >&/dev/null
         then
           log debug "$vif already attached to $bridge"
@@ -58,9 +58,9 @@
           fatal "brctl addif $bridge $vif failed"
 
         ifconfig "$vif" up || fatal "ifconfig $vif up failed"
-        success
         ;;
-    down)
+
+    offline)
         # vifs are auto-removed from bridge.
         ifconfig "$vif" down || fatal "ifconfig $vif down failed"
         ;;
@@ -69,3 +69,4 @@
 handle_iptable
 
 log debug "Successful vif-bridge operation for $vif, bridge $bridge."
+success
diff -r e62c54ab862f -r 878a9891b056 tools/examples/vif-common.sh
--- a/tools/examples/vif-common.sh      Sat Nov 19 05:06:09 2005
+++ b/tools/examples/vif-common.sh      Sat Nov 19 05:16:29 2005
@@ -22,11 +22,20 @@
 
 findCommand "$@"
 
-if [ "$command" != "up" ] && [ "$command" != "down" ]
+if [ "$command" != "online" ]  &&
+   [ "$command" != "offline" ] &&
+   [ "$command" != "add" ]     &&
+   [ "$command" != "remove" ]
 then
   log err "Invalid command: $command"
   exit 1
 fi
+
+case "$command" in
+    add | remove)
+        exit 0
+        ;;
+esac
 
 
 # Parameters may be read from the environment, the command line arguments, and
@@ -46,14 +55,17 @@
 
 function frob_iptable()
 {
-  if [ "$command" == "up" ]
+  if [ "$command" == "online" ]
   then
     local c="-A"
   else
     local c="-D"
   fi
 
-  iptables "$c" FORWARD -m physdev --physdev-in "$vif" "$@" -j ACCEPT
+  iptables "$c" FORWARD -m physdev --physdev-in "$vif" "$@" -j ACCEPT ||
+    log err \
+     "iptables $c FORWARD -m physdev --physdev-in $vif $@ -j ACCEPT failed.
+If you are using iptables, this may affect networking for guest domains."
 }
 
 
@@ -66,6 +78,15 @@
 #
 function handle_iptable()
 {
+  # Check for a working iptables installation.  Checking for the iptables
+  # binary is not sufficient, because the user may not have the appropriate
+  # modules installed.  If iptables is not working, then there's no need to do
+  # anything with it, so we can just return.
+  if ! iptables -L >&/dev/null
+  then
+    return
+  fi
+
   if [ "$ip" != "" ]
   then
       local addr
diff -r e62c54ab862f -r 878a9891b056 tools/examples/vif-nat
--- a/tools/examples/vif-nat    Sat Nov 19 05:06:09 2005
+++ b/tools/examples/vif-nat    Sat Nov 19 05:16:29 2005
@@ -9,7 +9,7 @@
 # places, then vif-bridge is the default.
 #
 # Usage:
-# vif-nat (up|down)
+# vif-nat (add|remove|online|offline)
 #
 # Environment vars:
 # vif         vif interface name (required).
@@ -40,12 +40,12 @@
 main_ip=$(ip addr show eth0 | sed -e '/inet /!d;s/^.*inet \([^\s*]\)\s.*$/\1/')
 
 case "$command" in
-    up)
+    online)
         ifconfig ${vif} ${vif_ip} netmask ${netmask} up
         echo 1 >/proc/sys/net/ipv4/conf/${vif}/proxy_arp
         ipcmd='a'
         ;;
-    down)
+    offline)
         ifconfig ${vif} down
         ipcmd='d'
         ;;
@@ -53,6 +53,6 @@
 
 ip r ${ipcmd} ${ip} dev ${vif} src ${main_ip}
 
-handle_iptable()
+handle_iptable
 
 success
diff -r e62c54ab862f -r 878a9891b056 tools/examples/vif-route
--- a/tools/examples/vif-route  Sat Nov 19 05:06:09 2005
+++ b/tools/examples/vif-route  Sat Nov 19 05:16:29 2005
@@ -9,7 +9,7 @@
 # places, then vif-bridge is the default.
 #
 # Usage:
-# vif-route (up|down)
+# vif-route (add|remove|online|offline)
 #
 # Environment vars:
 # vif         vif interface name (required).
@@ -26,12 +26,12 @@
 main_ip=$(ip addr show eth0 | sed -e '/inet /!d;s/^.*inet \([^\s*]\)\s.*$/\1/')
 
 case "$command" in
-    up)
+    online)
         ifconfig ${vif} ${main_ip} netmask 255.255.255.255 up
         echo 1 >/proc/sys/net/ipv4/conf/${vif}/proxy_arp
         ipcmd='a'
         ;;
-    down)
+    offline)
         ifdown ${vif}
         ipcmd='d'
         ;;
@@ -45,6 +45,6 @@
     done 
 fi
 
-handle_iptable()
+handle_iptable
 
 success
diff -r e62c54ab862f -r 878a9891b056 tools/examples/xen-backend.agent
--- a/tools/examples/xen-backend.agent  Sat Nov 19 05:06:09 2005
+++ b/tools/examples/xen-backend.agent  Sat Nov 19 05:16:29 2005
@@ -2,35 +2,25 @@
 
 PATH=/etc/xen/scripts:$PATH
 
+case "$XENBUS_TYPE" in
+  vbd)
+    /etc/xen/scripts/block "$ACTION"
+    ;;
+  vif)
+    [ -n "$script" ] && $script "$ACTION"
+    ;;
+esac
+
 case "$ACTION" in
   add)
-    case "$XENBUS_TYPE" in
-      vbd)
-       /etc/xen/scripts/block bind
-        ;;
-    esac
     ;;
   remove)
-    case "$XENBUS_TYPE" in
-      vbd)
-       /etc/xen/scripts/block unbind
-        ;;
-      vif)
-        [ -n "$script" ] && $script down
-        ;;
-    esac
     # remove device backend store entries
-    xenstore-rm -t "$XENBUS_PATH"
-    xenstore-rm -t "error/$XENBUS_PATH"
+    xenstore-rm -t "$XENBUS_PATH"       || true
+    xenstore-rm -t "error/$XENBUS_PATH" || true
     ;;
   online)
-    case "$XENBUS_TYPE" in
-      vif)
-        [ -n "$script" ] && $script up
-        ;;
-    esac
     ;;
   offline)
     ;;
 esac
-
diff -r e62c54ab862f -r 878a9891b056 tools/examples/xen-backend.rules
--- a/tools/examples/xen-backend.rules  Sat Nov 19 05:06:09 2005
+++ b/tools/examples/xen-backend.rules  Sat Nov 19 05:16:29 2005
@@ -1,4 +1,5 @@
-SUBSYSTEM=="xen-backend", KERNEL=="vbd*", ACTION=="add", 
RUN+="/etc/xen/scripts/block bind"
-SUBSYSTEM=="xen-backend", KERNEL=="vbd*", ACTION=="remove", 
RUN+="/etc/xen/scripts/block unbind"
-SUBSYSTEM=="xen-backend", KERNEL=="vif*", ACTION=="online", RUN+="$env{script} 
up"
+SUBSYSTEM=="xen-backend", KERNEL=="vbd*", RUN+="/etc/xen/scripts/block 
$env{ACTION}"
+SUBSYSTEM=="xen-backend", KERNEL=="vif*", ACTION=="online", RUN+="$env{script} 
online"
+SUBSYSTEM=="xen-backend", KERNEL=="vif*", ACTION=="offline", 
RUN+="$env{script} offline"
 SUBSYSTEM=="xen-backend", ACTION=="remove", RUN+="/usr/bin/xenstore-rm -t 
$env{XENBUS_PATH}"
+SUBSYSTEM=="xen-backend", ACTION=="remove", RUN+="/usr/bin/xenstore-rm -t 
error/$env{XENBUS_PATH}"
diff -r e62c54ab862f -r 878a9891b056 tools/examples/xmexample.vmx
--- a/tools/examples/xmexample.vmx      Sat Nov 19 05:06:09 2005
+++ b/tools/examples/xmexample.vmx      Sat Nov 19 05:16:29 2005
@@ -35,7 +35,11 @@
 
 # Optionally define mac and/or bridge for the network interfaces.
 # Random MACs are assigned if not given.
-#vif = [ 'mac=aa:00:00:00:00:11, bridge=xenbr0' ]
+# nics default is 1
+#vif = [ 'type=ioemu, mac=aa:00:00:00:00:11, bridge=xenbr0' ]
+nics=1 
+# type=ioemu specify the NIC is an ioemu device not netfront
+vif = [ 'type=ioemu, bridge=xenbr0' ]
 
 #----------------------------------------------------------------------------
 # Define the disk devices you want the domain to have access to, and
@@ -117,6 +121,11 @@
 #nographic=0
 
 
+#-----------------------------------------------------------------------------
+#   serial port re-direct to pty deivce, /dev/pts/n 
+#   then xm console or minicom can connect
+#serial='pty'
+
 #----------------------------------------------------------------------------
 # enable ne2000, default = 0(use pcnet)
 ne2000=0
diff -r e62c54ab862f -r 878a9891b056 tools/ioemu/hw/magic-load.c
--- a/tools/ioemu/hw/magic-load.c       Sat Nov 19 05:06:09 2005
+++ b/tools/ioemu/hw/magic-load.c       Sat Nov 19 05:16:29 2005
@@ -196,10 +196,8 @@
        goto error_freesyms;
 
     /* Commit */
-    if (disas_symtab)
-       qemu_free(disas_symtab); /* XXX Merge with old symbols? */
-    if (disas_strtab)
-       qemu_free(disas_strtab);
+    qemu_free(disas_symtab); /* XXX Merge with old symbols? */
+    qemu_free(disas_strtab);
     disas_symtab = syms;
     disas_num_syms = nsyms;
     disas_strtab = str;
diff -r e62c54ab862f -r 878a9891b056 tools/ioemu/target-i386-dm/Makefile
--- a/tools/ioemu/target-i386-dm/Makefile       Sat Nov 19 05:06:09 2005
+++ b/tools/ioemu/target-i386-dm/Makefile       Sat Nov 19 05:16:29 2005
@@ -7,7 +7,7 @@
 TARGET_PATH=$(SRC_PATH)/target-$(TARGET_ARCH)
 VPATH=$(SRC_PATH):$(TARGET_PATH):$(SRC_PATH)/hw:$(SRC_PATH)/audio
 DEFINES=-I. -I$(TARGET_PATH) -I$(SRC_PATH)
-DEFINES+= -I$(XEN_ROOT)/tools/libxc
+DEFINES+= -I$(XEN_ROOT)/tools/libxc -I$(XEN_ROOT)/tools/xenstore
 ifdef CONFIG_USER_ONLY
 VPATH+=:$(SRC_PATH)/linux-user
 DEFINES+=-I$(SRC_PATH)/linux-user -I$(SRC_PATH)/linux-user/$(TARGET_ARCH)
@@ -188,7 +188,7 @@
 #########################################################
 
 DEFINES+=-D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE
-LIBS+=-lm -L../../libxc -lxenctrl -lxenguest
+LIBS+=-lm -L../../libxc -lxenctrl -lxenguest -L../../xenstore -lxenstore
 ifndef CONFIG_USER_ONLY
 LIBS+=-lz
 endif
@@ -376,9 +376,9 @@
 
 clean:
        rm -rf *.o  *.a *~ $(PROGS) gen-op.h opc.h op.h nwfpe slirp
-
-distclean:
-       rm -rf *.o  *.a *~ $(PROGS) gen-op.h opc.h op.h nwfpe slirp
+       rm -rf config.mak config.h
+
+distclean: clean
 
 install: all 
        if [ ! -d $(INSTALL_DIR) ];then mkdir -p $(INSTALL_DIR);fi
diff -r e62c54ab862f -r 878a9891b056 tools/ioemu/target-i386-dm/helper2.c
--- a/tools/ioemu/target-i386-dm/helper2.c      Sat Nov 19 05:06:09 2005
+++ b/tools/ioemu/target-i386-dm/helper2.c      Sat Nov 19 05:16:29 2005
@@ -416,6 +416,7 @@
        FD_ZERO(&wakeup_rfds);
        FD_SET(evtchn_fd, &wakeup_rfds);
        highest_fds = evtchn_fd;
+       env->send_event = 0;
        while (1) {
                 if (vm_running) {
                     if (shutdown_requested) {
@@ -431,7 +432,6 @@
                tv.tv_sec = 0;
                tv.tv_usec = 100000;
 
-               env->send_event = 0;
                retval = select(highest_fds+1, &wakeup_rfds, NULL, NULL, &tv);
                if (retval == -1) {
                        perror("select");
@@ -447,12 +447,13 @@
 #define ULONGLONG_MAX   ULONG_MAX
 #endif
 
-               main_loop_wait(0);
         tun_receive_handler(&rfds);
         if ( FD_ISSET(evtchn_fd, &rfds) ) {
             cpu_handle_ioreq(env);
         }
+               main_loop_wait(0);
                if (env->send_event) {
+                   env->send_event = 0;
                        struct ioctl_evtchn_notify notify;
                        notify.port = ioreq_local_port;
                        (void)ioctl(evtchn_fd, IOCTL_EVTCHN_NOTIFY, &notify);
diff -r e62c54ab862f -r 878a9891b056 tools/ioemu/target-i386-dm/qemu-ifup
--- a/tools/ioemu/target-i386-dm/qemu-ifup      Sat Nov 19 05:06:09 2005
+++ b/tools/ioemu/target-i386-dm/qemu-ifup      Sat Nov 19 05:16:29 2005
@@ -7,4 +7,4 @@
 echo $*
 
 ifconfig $1 0.0.0.0 up
-brctl addif xenbr0 $1
+brctl addif $2 $1
diff -r e62c54ab862f -r 878a9891b056 tools/ioemu/vl.c
--- a/tools/ioemu/vl.c  Sat Nov 19 05:06:09 2005
+++ b/tools/ioemu/vl.c  Sat Nov 19 05:16:29 2005
@@ -76,6 +76,7 @@
 #endif /* CONFIG_SDL */
 
 #include "xenctrl.h"
+#include "xs.h"
 #include "exec-all.h"
 
 //#define DO_TB_FLUSH
@@ -123,6 +124,7 @@
 static char network_script[1024];
 int pit_min_timer_count = 0;
 int nb_nics;
+char bridge[16];
 NetDriverState nd_table[MAX_NICS];
 QEMUTimer *gui_timer;
 QEMUTimer *polling_timer;
@@ -135,7 +137,7 @@
 int gus_enabled = 1;
 int pci_enabled = 1;
 int prep_enabled = 0;
-int rtc_utc = 1;
+int rtc_utc = 0;
 int cirrus_vga_enabled = 1;
 int vga_accelerate = 1;
 int graphic_width = 800;
@@ -1171,6 +1173,48 @@
     return chr;
 }
 
+int store_console_dev(int domid, char *pts)
+{
+    int xc_handle;
+    unsigned int len = 0;
+    struct xs_handle *xs;
+    char *path;
+
+    xs = xs_daemon_open();
+    if (xs == NULL) {
+        fprintf(logfile, "Could not contact XenStore\n");
+        return -1;
+    }
+
+    xc_handle = xc_interface_open();
+    if (xc_handle == -1) {
+        fprintf(logfile, "xc_interface_open() error\n");
+        return -1;
+    }
+    
+    path = xs_get_domain_path(xs, domid);
+    if (path == NULL) {
+        fprintf(logfile, "xs_get_domain_path() error\n");
+        return -1;
+    }
+    path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
+    if (path == NULL) {
+        fprintf(logfile, "realloc error\n");
+        return -1;
+    }
+    strcat(path, "/console/tty");
+    if (!xs_write(xs, NULL, path, pts, strlen(pts))) {
+        fprintf(logfile, "xs_write for console fail");
+        return -1;
+    }
+    
+    free(path);
+    xs_daemon_close(xs);
+    close(xc_handle);
+
+    return 0;
+}
+
 #if defined(__linux__)
 CharDriverState *qemu_chr_open_pty(void)
 {
@@ -1182,6 +1226,7 @@
         return NULL;
     }
     fprintf(stderr, "char device redirected to %s\n", slave_name);
+    store_console_dev(domid, slave_name);
     return qemu_chr_open_fd(master_fd, master_fd);
 }
 #else
@@ -1542,7 +1587,7 @@
 static int net_tun_init(NetDriverState *nd)
 {
     int pid, status;
-    char *args[3];
+    char *args[4];
     char **parg;
     extern int highest_fds;
 
@@ -1558,6 +1603,7 @@
             parg = args;
             *parg++ = network_script;
             *parg++ = nd->ifname;
+            *parg++ = bridge;
             *parg++ = NULL;
             execv(network_script, args);
             exit(1);
@@ -2163,6 +2209,7 @@
            "Network options:\n"
            "-nics n         simulate 'n' network cards [default=1]\n"
            "-macaddr addr   set the mac address of the first interface\n"
+           "-bridge  br     set the bridge interface for nic\n"
            "-n script       set tap/tun network init script [default=%s]\n"
            "-tun-fd fd      use this fd as already opened tap/tun interface\n"
 #ifdef CONFIG_SLIRP
@@ -2253,6 +2300,7 @@
 
     QEMU_OPTION_nics,
     QEMU_OPTION_macaddr,
+    QEMU_OPTION_bridge,
     QEMU_OPTION_n,
     QEMU_OPTION_tun_fd,
     QEMU_OPTION_user_net,
@@ -2323,6 +2371,7 @@
 
     { "nics", HAS_ARG, QEMU_OPTION_nics},
     { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
+    { "bridge", HAS_ARG, QEMU_OPTION_bridge},
     { "n", HAS_ARG, QEMU_OPTION_n },
     { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
 #ifdef CONFIG_SLIRP
@@ -2701,7 +2750,9 @@
                 break;
             case QEMU_OPTION_nographic:
                 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
-                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
+                if(!strcmp(serial_devices[0], "vc"))
+                    pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
+                            "stdio");
                 nographic = 1;
                 break;
 #ifdef CONFIG_VNC
@@ -2778,6 +2829,9 @@
                     fprintf(stderr, "qemu: invalid number of network 
interfaces\n");
                     exit(1);
                 }
+                break;
+            case QEMU_OPTION_bridge:
+                pstrcpy(bridge, sizeof(bridge), optarg);
                 break;
             case QEMU_OPTION_macaddr:
                 {
diff -r e62c54ab862f -r 878a9891b056 tools/ioemu/vnc.c
--- a/tools/ioemu/vnc.c Sat Nov 19 05:06:09 2005
+++ b/tools/ioemu/vnc.c Sat Nov 19 05:16:29 2005
@@ -187,8 +187,7 @@
 
 static void start_mouse_calibration() {
        int size = screen->height*screen->paddedWidthInBytes;
-       if(mouse_magic->calibration)
-               free(mouse_magic->calibration);
+       free(mouse_magic->calibration);
        mouse_magic->calibration = malloc(size);
        memcpy(mouse_magic->calibration, screen->frameBuffer, size);
        calibration_step=0;
@@ -198,8 +197,7 @@
 }
 
 static void stop_mouse_calibration() {
-       if(mouse_magic->calibration)
-               free(mouse_magic->calibration);
+       free(mouse_magic->calibration);
        mouse_magic->calibration = 0;
 }
 
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/Makefile
--- a/tools/libxc/Makefile      Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/Makefile      Sat Nov 19 05:16:29 2005
@@ -102,6 +102,7 @@
        $(INSTALL_DATA) libxenguest.a $(DESTDIR)/usr/$(LIBDIR)
        ln -sf libxenguest.so.$(MAJOR).$(MINOR) 
$(DESTDIR)/usr/$(LIBDIR)/libxenguest.so.$(MAJOR)
        ln -sf libxenguest.so.$(MAJOR) $(DESTDIR)/usr/$(LIBDIR)/libxenguest.so
+       $(INSTALL_DATA) xenguest.h $(DESTDIR)/usr/include
 
 .PHONY: TAGS clean rpm install all
 
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xc_ia64_stubs.c
--- a/tools/libxc/xc_ia64_stubs.c       Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xc_ia64_stubs.c       Sat Nov 19 05:16:29 2005
@@ -77,7 +77,7 @@
 {
     // N.B. gva should be page aligned
     
-    unsigned long *page_array=NULL;
+    unsigned long *page_array = NULL;
     int i;
 
     if ( (page_array = malloc(nr_pages * sizeof(unsigned long))) == NULL ){
@@ -99,8 +99,7 @@
     return 0;
     
 error_out:
-    if (page_array)
-        free(page_array);
+    free(page_array);
     return -1;
 }
 
@@ -657,8 +656,7 @@
         goto error_out;
     }
 
-    if ( image != NULL )
-        free(image);
+    free(image);
 
     ctxt->flags = VGCF_VMX_GUEST;
     ctxt->regs.cr_iip = 0x80000000ffffffb0UL;
@@ -675,9 +673,7 @@
     return rc;
 
  error_out:
-    if ( image != NULL )
-        free(image);
-
+    free(image);
     return -1;
 }
 
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xc_linux_build.c
--- a/tools/libxc/xc_linux_build.c      Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xc_linux_build.c      Sat Nov 19 05:16:29 2005
@@ -351,7 +351,7 @@
         xc_handle, dom, PAGE_SIZE, PROT_READ|PROT_WRITE, page_array[0]);
     memset(start_info, 0, sizeof(*start_info));
     rc = xc_version(xc_handle, XENVER_version, NULL);
-    sprintf(start_info->magic, "xen-%i.%i", rc >> 16, rc & (0xFFFF));
+    sprintf(start_info->magic, "xen-%i.%i-ia64", rc >> 16, rc & (0xFFFF));
     start_info->flags        = flags;
     start_info->store_mfn    = nr_pages - 2;
     start_info->store_evtchn = store_evtchn;
@@ -619,14 +619,18 @@
 
     *store_mfn = page_array[(vstoreinfo_start-dsi.v_start) >> PAGE_SHIFT];
     *console_mfn = page_array[(vconsole_start-dsi.v_start) >> PAGE_SHIFT];
-
+    if ( xc_clear_domain_page(xc_handle, dom, *store_mfn) ||
+         xc_clear_domain_page(xc_handle, dom, *console_mfn) )
+        goto error_out;
 
     start_info = xc_map_foreign_range(
         xc_handle, dom, PAGE_SIZE, PROT_READ|PROT_WRITE,
         page_array[(vstartinfo_start-dsi.v_start)>>PAGE_SHIFT]);
     memset(start_info, 0, sizeof(*start_info));
     rc = xc_version(xc_handle, XENVER_version, NULL);
-    sprintf(start_info->magic, "xen-%i.%i", rc >> 16, rc & (0xFFFF));
+    sprintf(start_info->magic, "xen-%i.%i-x86_%d%s",
+            rc >> 16, rc & (0xFFFF), (unsigned int)sizeof(long)*8,
+            dsi.pae_kernel ? "p" : "");
     start_info->nr_pages     = nr_pages;
     start_info->shared_info  = shared_info_frame << PAGE_SHIFT;
     start_info->flags        = flags;
@@ -670,10 +674,8 @@
     return 0;
 
  error_out:
-    if ( mmu != NULL )
-        free(mmu);
-    if ( page_array != NULL )
-        free(page_array);
+    free(mmu);
+    free(page_array);
     return -1;
 }
 #endif
@@ -768,8 +770,7 @@
         close(initrd_fd);
     if ( initrd_gfd )
         gzclose(initrd_gfd);
-    if ( image != NULL )
-        free(image);
+    free(image);
 
 #ifdef __ia64__
     /* based on new_thread in xen/arch/ia64/domain.c */
@@ -858,9 +859,7 @@
         gzclose(initrd_gfd);
     else if ( initrd_fd >= 0 )
         close(initrd_fd);
-    if ( image != NULL )
-        free(image);
-
+    free(image);
     return -1;
 }
 
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xc_linux_restore.c
--- a/tools/libxc/xc_linux_restore.c    Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xc_linux_restore.c    Sat Nov 19 05:16:29 2005
@@ -12,16 +12,14 @@
 #include "xg_private.h"
 #include "xg_save_restore.h"
 
-
-
 /* max mfn of the whole machine */
-static uint32_t max_mfn; 
+static unsigned long max_mfn; 
 
 /* virtual starting address of the hypervisor */
-static uint32_t hvirt_start; 
+static unsigned long hvirt_start; 
 
 /* #levels of page tables used by the currrent guest */
-static uint32_t pt_levels; 
+static unsigned int pt_levels; 
 
 /* total number of pages used by the current guest */
 static unsigned long max_pfn;
@@ -51,7 +49,6 @@
 
     return (r == count) ? 1 : 0; 
 }
-
 
 /*
 ** In the state file (or during transfer), all page-table pages are 
@@ -62,23 +59,11 @@
 */
 int uncanonicalize_pagetable(unsigned long type, void *page) 
 { 
-    int i, pte_last, xen_start, xen_end; 
+    int i, pte_last; 
     unsigned long pfn; 
     uint64_t pte; 
 
-    /* 
-    ** We need to determine which entries in this page table hold
-    ** reserved hypervisor mappings. This depends on the current
-    ** page table type as well as the number of paging levels. 
-    */
-    xen_start = xen_end = pte_last = PAGE_SIZE / ((pt_levels == 2)? 4 : 8); 
-    
-    if (pt_levels == 2 && type == L2TAB)
-        xen_start = (hvirt_start >> L2_PAGETABLE_SHIFT); 
-
-    if (pt_levels == 3 && type == L3TAB) 
-        xen_start = L3_PAGETABLE_ENTRIES_PAE; 
-
+    pte_last = PAGE_SIZE / ((pt_levels == 2)? 4 : 8); 
 
     /* Now iterate through the page table, uncanonicalizing each PTE */
     for(i = 0; i < pte_last; i++) { 
@@ -87,13 +72,10 @@
             pte = ((uint32_t *)page)[i]; 
         else 
             pte = ((uint64_t *)page)[i]; 
-        
-        if(i >= xen_start && i < xen_end) 
-            pte = 0; 
-        
+
         if(pte & _PAGE_PRESENT) { 
-            
-            pfn = pte >> PAGE_SHIFT; 
+
+            pfn = (pte >> PAGE_SHIFT) & 0xffffffff;
             
             if(pfn >= max_pfn) { 
                 ERR("Frame number in type %lu page table is out of range: "
@@ -103,17 +85,16 @@
             } 
             
             
-            if(type == L1TAB) 
-                pte &= (PAGE_SIZE - 1) & ~(_PAGE_GLOBAL | _PAGE_PAT);
-            else 
-                pte &= (PAGE_SIZE - 1) & ~(_PAGE_GLOBAL | _PAGE_PSE);
-            
-            pte |= p2m[pfn] << PAGE_SHIFT;
-            
+            pte &= 0xffffff0000000fffULL;
+            pte |= (uint64_t)p2m[pfn] << PAGE_SHIFT;
+
             if(pt_levels == 2) 
                 ((uint32_t *)page)[i] = (uint32_t)pte; 
             else 
                 ((uint64_t *)page)[i] = (uint64_t)pte; 
+
+        
+
         }
     }
     
@@ -145,6 +126,9 @@
     /* A table of MFNs to map in the current region */
     unsigned long *region_mfn = NULL;
 
+    /* Types of the pfns in the current region */
+    unsigned long region_pfn_type[MAX_BATCH_SIZE];
+
     /* A temporary mapping, and a copy, of one frame of guest memory. */
     unsigned long *page = NULL;
 
@@ -162,7 +146,7 @@
     unsigned long buf[PAGE_SIZE/sizeof(unsigned long)];
 
     struct mmuext_op pin[MAX_PIN_BATCH];
-    unsigned int nr_pins = 0;
+    unsigned int nr_pins; 
 
 
     max_pfn = nr_pfns; 
@@ -235,10 +219,12 @@
     
     if(xc_domain_memory_increase_reservation(
            xc_handle, dom, max_pfn, 0, 0, NULL) != 0) { 
-        ERR("Failed to increase reservation by %lx KB\n", max_pfn); 
+        ERR("Failed to increase reservation by %lx KB\n", PFN_TO_KB(max_pfn));
         errno = ENOMEM;
         goto out;
     }
+
+    DPRINTF("Increased domain reservation by %lx KB\n", PFN_TO_KB(max_pfn)); 
 
     /* Build the pfn-to-mfn table. We choose MFN ordering returned by Xen. */
     if (xc_get_pfn_list(xc_handle, dom, p2m, max_pfn) != max_pfn) {
@@ -250,6 +236,7 @@
         ERR("Could not initialise for MMU updates");
         goto out;
     }
+
 
     DPRINTF("Reloading memory pages:   0%%\n");
 
@@ -263,7 +250,6 @@
     while (1) { 
 
         int j;
-        unsigned long region_pfn_type[MAX_BATCH_SIZE];
 
         this_pc = (n * 100) / max_pfn;
         if ( (this_pc - prev_pc) >= 5 )
@@ -324,7 +310,7 @@
             if (pagetype == XTAB) 
                 /* a bogus/unmapped page: skip it */
                 continue;
-            
+
             if (pfn > max_pfn) {
                 ERR("pfn out of range");
                 goto out;
@@ -350,10 +336,20 @@
                 ** A page table page - need to 'uncanonicalize' it, i.e. 
                 ** replace all the references to pfns with the corresponding 
                 ** mfns for the new domain. 
-                */ 
-                if(!uncanonicalize_pagetable(pagetype, page))
-                    goto out; 
-
+                ** 
+                ** On PAE we need to ensure that PGDs are in MFNs < 4G, and 
+                ** so we may need to update the p2m after the main loop. 
+                ** Hence we defer canonicalization of L1s until then. 
+                */
+                if(pt_levels != 3 || pagetype != L1TAB) { 
+
+                    if(!uncanonicalize_pagetable(pagetype, page)) {
+                        ERR("failed uncanonicalize pt!\n"); 
+                        goto out; 
+                    }
+
+                } 
+                    
             } else if(pagetype != NOTAB) { 
 
                 ERR("Bogus page type %lx page table is out of range: "
@@ -361,7 +357,6 @@
                 goto out;
 
             } 
-
 
 
             if (verify) {
@@ -388,9 +383,9 @@
             }
 
             if (xc_add_mmu_update(xc_handle, mmu, 
-                                  (mfn << PAGE_SHIFT) | MMU_MACHPHYS_UPDATE,
-                                  pfn)) {
-                ERR("machpys mfn=%ld pfn=%ld", mfn, pfn);
+                                  (((unsigned long long)mfn) << PAGE_SHIFT) 
+                                  | MMU_MACHPHYS_UPDATE, pfn)) {
+                ERR("failed machpys update mfn=%lx pfn=%lx", mfn, pfn);
                 goto out;
             }
         } /* end of 'batch' for loop */
@@ -401,14 +396,39 @@
 
     DPRINTF("Received all pages\n");
 
-    if (pt_levels == 3) {
-
-        /* Get all PGDs below 4GB. */
+    if(pt_levels == 3) { 
+
+        /* 
+        ** XXX SMH on PAE we need to ensure PGDs are in MFNs < 4G. This 
+        ** is a little awkward and involves (a) finding all such PGDs and
+        ** replacing them with 'lowmem' versions; (b) upating the p2m[] 
+        ** with the new info; and (c) canonicalizing all the L1s using the
+        ** (potentially updated) p2m[]. 
+        ** 
+        ** This is relatively slow (and currently involves two passes through
+        ** the pfn_type[] array), but at least seems to be correct. May wish
+        ** to consider more complex approaches to optimize this later. 
+        */
+
+        int j, k; 
+
+        /* First pass: find all L3TABs current in > 4G mfns and get new mfns */
         for (i = 0; i < max_pfn; i++) {
             
             if (((pfn_type[i] & LTABTYPE_MASK)==L3TAB) && (p2m[i]>0xfffffUL)) {
 
                 unsigned long new_mfn; 
+                uint64_t l3ptes[4]; 
+                uint64_t *l3tab; 
+
+                l3tab = (uint64_t *)
+                    xc_map_foreign_range(xc_handle, dom, PAGE_SIZE, 
+                                         PROT_READ, p2m[i]); 
+
+                for(j = 0; j < 4; j++) 
+                    l3ptes[j] = l3tab[j]; 
+                
+                munmap(l3tab, PAGE_SIZE); 
 
                 if (!(new_mfn=xc_make_page_below_4G(xc_handle, dom, p2m[i]))) {
                     ERR("Couldn't get a page below 4GB :-(");
@@ -416,15 +436,58 @@
                 }
                 
                 p2m[i] = new_mfn;
-                if (xc_add_mmu_update(
-                        xc_handle, mmu, 
-                        (new_mfn << PAGE_SHIFT) | MMU_MACHPHYS_UPDATE, i)) {
+                if (xc_add_mmu_update(xc_handle, mmu, 
+                                      (((unsigned long long)new_mfn) 
+                                       << PAGE_SHIFT) | 
+                                      MMU_MACHPHYS_UPDATE, i)) {
                     ERR("Couldn't m2p on PAE root pgdir");
                     goto out;
                 }
+                
+                l3tab = (uint64_t *)
+                    xc_map_foreign_range(xc_handle, dom, PAGE_SIZE, 
+                                         PROT_READ | PROT_WRITE, p2m[i]); 
+                
+                for(j = 0; j < 4; j++) 
+                    l3tab[j] = l3ptes[j]; 
+                
+                munmap(l3tab, PAGE_SIZE); 
+                
             }
         }
-        
+
+        /* Second pass: find all L1TABs and uncanonicalize them */
+        j = 0; 
+
+        for(i = 0; i < max_pfn; i++) { 
+            
+            if (((pfn_type[i] & LTABTYPE_MASK)==L1TAB)) { 
+                region_mfn[j] = p2m[i]; 
+                j++; 
+            }
+
+            if(i == (max_pfn-1) || j == MAX_BATCH_SIZE) { 
+
+                if (!(region_base = xc_map_foreign_batch(
+                          xc_handle, dom, PROT_READ | PROT_WRITE, 
+                          region_mfn, j))) {  
+                    ERR("map batch failed");
+                    goto out;
+                }
+
+                for(k = 0; k < j; k++) {
+                    if(!uncanonicalize_pagetable(L1TAB, 
+                                                 region_base + k*PAGE_SIZE)) {
+                        ERR("failed uncanonicalize pt!\n"); 
+                        goto out; 
+                    } 
+                }
+                
+                munmap(region_base, j*PAGE_SIZE); 
+                j = 0; 
+            }
+        }
+
     }
 
 
@@ -432,16 +495,26 @@
         ERR("Error doing finish_mmu_updates()"); 
         goto out;
     } 
+
 
     /*
      * Pin page tables. Do this after writing to them as otherwise Xen
      * will barf when doing the type-checking.
      */
+    nr_pins = 0; 
     for (i = 0; i < max_pfn; i++) {
+
+        if (i == (max_pfn-1) || nr_pins == MAX_PIN_BATCH) {
+            if (xc_mmuext_op(xc_handle, pin, nr_pins, dom) < 0) { 
+                ERR("Failed to pin batch of %d page tables", nr_pins); 
+                goto out;
+            } 
+            nr_pins = 0;
+        }
 
         if ( (pfn_type[i] & LPINTAB) == 0 )
             continue;
-        
+
         switch(pfn_type[i]) { 
 
         case (L1TAB|LPINTAB): 
@@ -465,23 +538,8 @@
         }
 
         pin[nr_pins].arg1.mfn = p2m[i];
-        
-        if (++nr_pins == MAX_PIN_BATCH) {
-            if (xc_mmuext_op(xc_handle, pin, nr_pins, dom) < 0) { 
-                ERR("Failed to pin batch of %d page tables", nr_pins); 
-                goto out;
-            } 
-            DPRINTF("successfully pinned batch of %d page tables", nr_pins); 
-            nr_pins = 0;
-        }
-    }
-    
-    if (nr_pins != 0) { 
-        if((rc = xc_mmuext_op(xc_handle, pin, nr_pins, dom)) < 0) { 
-            ERR("Failed (2) to pin batch of %d page tables", nr_pins); 
-            DPRINTF("rc is %d\n", rc); 
-            goto out;
-        }
+        nr_pins++; 
+
     }
 
     DPRINTF("\b\b\b\b100%%\n");
@@ -581,23 +639,20 @@
     pfn = ctxt.ctrlreg[3] >> PAGE_SHIFT;
 
     if (pfn >= max_pfn) {
-        DPRINTF("PT base is bad: pfn=%lu max_pfn=%lu type=%08lx\n",
-                pfn, max_pfn, pfn_type[pfn]); 
-        ERR("PT base is bad.");
+        ERR("PT base is bad: pfn=%lu max_pfn=%lu type=%08lx",
+            pfn, max_pfn, pfn_type[pfn]); 
         goto out;
     }
 
     if ((pt_levels == 2) && ((pfn_type[pfn]&LTABTYPE_MASK) != L2TAB)) { 
-        DPRINTF("PT base is bad. pfn=%lu nr=%lu type=%08lx %08lx\n",
-                pfn, max_pfn, pfn_type[pfn], (unsigned long)L2TAB);
-        ERR("PT base is bad.");
+        ERR("PT base is bad. pfn=%lu nr=%lu type=%08lx %08lx",
+            pfn, max_pfn, pfn_type[pfn], (unsigned long)L2TAB);
         goto out;
     }
 
     if ((pt_levels == 3) && ((pfn_type[pfn]&LTABTYPE_MASK) != L3TAB)) { 
-        DPRINTF("PT base is bad. pfn=%lu nr=%lu type=%08lx %08lx\n",
-                pfn, max_pfn, pfn_type[pfn], (unsigned long)L3TAB);
-        ERR("PT base is bad.");
+        ERR("PT base is bad. pfn=%lu nr=%lu type=%08lx %08lx",
+            pfn, max_pfn, pfn_type[pfn], (unsigned long)L3TAB);
         goto out;
     }
     
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xc_linux_save.c
--- a/tools/libxc/xc_linux_save.c       Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xc_linux_save.c       Sat Nov 19 05:16:29 2005
@@ -27,13 +27,13 @@
 
 
 /* max mfn of the whole machine */
-static uint32_t max_mfn; 
+static unsigned long max_mfn; 
 
 /* virtual starting address of the hypervisor */
-static uint32_t hvirt_start; 
+static unsigned long hvirt_start; 
 
 /* #levels of page tables used by the currrent guest */
-static uint32_t pt_levels; 
+static unsigned int pt_levels; 
 
 /* total number of pages used by the current guest */
 static unsigned long max_pfn;
@@ -73,7 +73,7 @@
 */
 
 #define BITS_PER_LONG (sizeof(unsigned long) * 8) 
-#define BITMAP_SIZE   ((max_pfn + BITS_PER_LONG - 1) / BITS_PER_LONG)
+#define BITMAP_SIZE   ((max_pfn + BITS_PER_LONG - 1) / 8)
 
 #define BITMAP_ENTRY(_nr,_bmap) \
    ((unsigned long *)(_bmap))[(_nr)/BITS_PER_LONG]
@@ -500,6 +500,70 @@
 
 
 
+static unsigned long *xc_map_m2p(int xc_handle, 
+                                 unsigned long max_mfn, 
+                                 int prot) 
+{ 
+    privcmd_m2pmfns_t m2p_mfns; 
+    privcmd_mmap_t ioctlx; 
+    privcmd_mmap_entry_t *entries; 
+    unsigned long m2p_chunks, m2p_size; 
+    unsigned long *m2p; 
+    int i, rc; 
+
+    m2p_size   = M2P_SIZE(max_mfn); 
+    m2p_chunks = M2P_CHUNKS(max_mfn); 
+
+
+    m2p_mfns.num = m2p_chunks; 
+
+    if(!(m2p_mfns.arr = malloc(m2p_chunks * sizeof(unsigned long)))) { 
+        ERR("failed to allocate space for m2p mfns!\n"); 
+        return NULL; 
+    } 
+
+    if (ioctl(xc_handle, IOCTL_PRIVCMD_GET_MACH2PHYS_MFNS, &m2p_mfns) < 0) {
+        ERR("xc_get_m2p_mfns:"); 
+        return NULL;
+    }
+
+    if((m2p = mmap(NULL, m2p_size, prot, 
+                   MAP_SHARED, xc_handle, 0)) == MAP_FAILED) {
+        ERR("failed to mmap m2p"); 
+        return NULL; 
+    } 
+    
+
+    if(!(entries = malloc(m2p_chunks * sizeof(privcmd_mmap_entry_t)))) { 
+        ERR("failed to allocate space for mmap entries!\n"); 
+        return NULL; 
+    } 
+
+
+    ioctlx.num   = m2p_chunks;
+    ioctlx.dom   = DOMID_XEN; 
+    ioctlx.entry = entries; 
+    
+    for(i=0; i < m2p_chunks; i++) { 
+        
+        entries[i].va = (unsigned long)(((void *)m2p) + (i * M2P_CHUNK_SIZE)); 
+        entries[i].mfn = m2p_mfns.arr[i]; 
+        entries[i].npages = M2P_CHUNK_SIZE >> PAGE_SHIFT;
+
+    }
+
+    if((rc = ioctl(xc_handle, IOCTL_PRIVCMD_MMAP, &ioctlx)) < 0) {
+        ERR("ioctl_mmap failed (rc = %d)", rc); 
+        return NULL; 
+    }
+        
+    free(m2p_mfns.arr); 
+    free(entries); 
+
+    return m2p; 
+}
+
+
 
 int xc_linux_save(int xc_handle, int io_fd, uint32_t dom, uint32_t max_iters, 
                   uint32_t max_factor, uint32_t flags)
@@ -531,16 +595,12 @@
     /* A copy of the pfn-to-mfn table frame list. */
     unsigned long *p2m_frame_list = NULL;
 
-    unsigned long m2p_start_mfn;
-    
     /* Live mapping of shared info structure */
     shared_info_t *live_shinfo = NULL;
 
     /* base of the region in which domain memory is mapped */
     unsigned char *region_base = NULL;
 
-
-    
     /* power of 2 order of max_pfn */
     int order_nr; 
 
@@ -563,9 +623,6 @@
         max_factor = DEF_MAX_FACTOR; 
     
     initialize_mbit_rate(); 
-
-    DPRINTF("xc_linux_save start DOM%u live=%s\n", dom, live ? 
-            "true" : "false"); 
 
     if(!get_platform_info(xc_handle, dom, 
                           &max_mfn, &hvirt_start, &pt_levels)) {
@@ -647,11 +704,13 @@
     }
 
     /* Setup the mfn_to_pfn table mapping */
-    m2p_start_mfn = xc_get_m2p_start_mfn(xc_handle);
-    live_m2p      = xc_map_foreign_range(xc_handle, DOMID_XEN, M2P_SIZE, 
-                                         PROT_READ, m2p_start_mfn);
-    
-    /* Get a local copy fo the live_P2M_frame_list */
+    if(!(live_m2p = xc_map_m2p(xc_handle, max_mfn, PROT_READ))) { 
+        ERR("Failed to map live M2P table"); 
+        goto out; 
+    } 
+
+    
+    /* Get a local copy of the live_P2M_frame_list */
     if(!(p2m_frame_list = malloc(P2M_FL_SIZE))) { 
         ERR("Couldn't allocate p2m_frame_list array");
         goto out;
@@ -662,11 +721,18 @@
     for (i = 0; i < max_pfn; i += ulpp) {
         if (!translate_mfn_to_pfn(&p2m_frame_list[i/ulpp])) { 
             ERR("Frame# in pfn-to-mfn frame list is not in pseudophys");
+            ERR("entry %d: p2m_frame_list[%ld] is 0x%lx", i, i/ulpp, 
+                p2m_frame_list[i/ulpp]); 
             goto out;
         }
     }
 
     /* Domain is still running at this point */
+
+    if (live && (pt_levels != 2)) {
+        ERR("Live migration supported only for 32-bit non-pae");
+        goto out;
+    }
 
     if (live) {
 
@@ -693,20 +759,14 @@
         
     }
 
-#if 0
-    sent_last_iter = 0xFFFFFFFF; /* Pretend we sent a /lot/ last time */
-#else
-    sent_last_iter = 1 << 20; 
-#endif
+    /* pretend we sent all the pages last iteration */
+    sent_last_iter = max_pfn; 
 
 
     /* calculate the power of 2 order of max_pfn, e.g.
        15->4 16->4 17->5 */
     for (i = max_pfn-1, order_nr = 0; i ; i >>= 1, order_nr++)
         continue;
-
-#undef BITMAP_SIZE
-#define BITMAP_SIZE ((1<<20)/8) 
 
     /* Setup to_send / to_fix and to_skip bitmaps */
     to_send = malloc(BITMAP_SIZE); 
@@ -922,10 +982,8 @@
 
 
                 /* write out pages in batch */
-                if (pagetype == XTAB) {
-                    DPRINTF("SKIP BOGUS page %i mfn %08lx\n", j, pfn_type[j]);
+                if (pagetype == XTAB)
                     continue;
-                }
 
                 pagetype &= LTABTYPE_MASK; 
                 
@@ -950,10 +1008,10 @@
             } /* end of the write out for this batch */
             
             sent_this_iter += batch;
-            
+
+            munmap(region_base, batch*PAGE_SIZE);
+        
         } /* end of this while loop for this iteration */
-        
-        munmap(region_base, batch*PAGE_SIZE);
         
       skip: 
         
@@ -1027,13 +1085,9 @@
 
     DPRINTF("All memory is saved\n");
 
-    /* Success! */
-    rc = 0;
-    
-    /* ^^^^^^ XXX SMH: hmm.. not sure that's really success! */
-    
     /* Zero terminate */
-    if (!write_exact(io_fd, &rc, sizeof(int))) { 
+    i = 0; 
+    if (!write_exact(io_fd, &i, sizeof(int))) { 
         ERR("Error when writing to state file (6)");
         goto out;
     }
@@ -1043,17 +1097,17 @@
         unsigned int i,j;
         unsigned long pfntab[1024]; 
 
-        for ( i = 0, j = 0; i < max_pfn; i++ ) {
-            if ( ! is_mapped(live_p2m[i]) )
+        for (i = 0, j = 0; i < max_pfn; i++) {
+            if (!is_mapped(live_p2m[i]))
                 j++;
         }
-
+        
         if(!write_exact(io_fd, &j, sizeof(unsigned int))) { 
             ERR("Error when writing to state file (6a)");
             goto out;
         }      
         
-        for ( i = 0, j = 0; i < max_pfn; ) {
+        for (i = 0, j = 0; i < max_pfn; ) {
 
             if (!is_mapped(live_p2m[i]))
                 pfntab[j++] = i;
@@ -1097,7 +1151,10 @@
         ERR("Error when writing to state file (1)");
         goto out;
     }
-    
+
+    /* Success! */
+    rc = 0;
+
  out:
 
     if (live_shinfo)
@@ -1110,7 +1167,7 @@
         munmap(live_p2m, P2M_SIZE); 
 
     if(live_m2p) 
-        munmap(live_m2p, M2P_SIZE); 
+        munmap(live_m2p, M2P_SIZE(max_mfn)); 
 
     free(pfn_type);
     free(pfn_batch);
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xc_private.c
--- a/tools/libxc/xc_private.c  Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xc_private.c  Sat Nov 19 05:16:29 2005
@@ -260,18 +260,6 @@
 }
 
 
-unsigned long xc_get_m2p_start_mfn ( int xc_handle )
-{
-    unsigned long mfn;
-
-    if ( ioctl( xc_handle, IOCTL_PRIVCMD_GET_MACH2PHYS_START_MFN, &mfn ) < 0 )
-    {
-        perror("xc_get_m2p_start_mfn:");
-        return 0;
-    }
-    return mfn;
-}
-
 int xc_get_pfn_list(int xc_handle,
                     uint32_t domid, 
                     unsigned long *pfn_buf, 
@@ -336,6 +324,19 @@
     return 0;
 }
 
+int xc_clear_domain_page(int xc_handle,
+                         uint32_t domid,
+                         unsigned long dst_pfn)
+{
+    void *vaddr = xc_map_foreign_range(
+        xc_handle, domid, PAGE_SIZE, PROT_WRITE, dst_pfn);
+    if ( vaddr == NULL )
+        return -1;
+    memset(vaddr, 0, PAGE_SIZE);
+    munmap(vaddr, PAGE_SIZE);
+    return 0;
+}
+
 unsigned long xc_get_filesz(int fd)
 {
     uint16_t sig;
@@ -389,11 +390,21 @@
 
     switch ( cmd )
     {
-    case XENVER_extraversion: argsize = sizeof(xen_extraversion_t); break;
-    case XENVER_compile_info: argsize = sizeof(xen_compile_info_t); break;
-    case XENVER_capabilities: argsize = sizeof(xen_capabilities_info_t); break;
-    case XENVER_changeset:    argsize = sizeof(xen_changeset_info_t); break;
-    case XENVER_parameters:   argsize = sizeof(xen_parameters_info_t); break;
+    case XENVER_extraversion:
+        argsize = sizeof(xen_extraversion_t);
+        break;
+    case XENVER_compile_info:
+        argsize = sizeof(xen_compile_info_t);
+        break;
+    case XENVER_capabilities:
+        argsize = sizeof(xen_capabilities_info_t);
+        break;
+    case XENVER_changeset:
+        argsize = sizeof(xen_changeset_info_t);
+        break;
+    case XENVER_platform_parameters:
+        argsize = sizeof(xen_platform_parameters_t);
+        break;
     }
 
     if ( (argsize != 0) && (mlock(arg, argsize) != 0) )
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xc_vmx_build.c
--- a/tools/libxc/xc_vmx_build.c        Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xc_vmx_build.c        Sat Nov 19 05:16:29 2005
@@ -495,6 +495,9 @@
     }
 
     *store_mfn = page_array[(v_end-2) >> PAGE_SHIFT];
+    if ( xc_clear_domain_page(xc_handle, dom, *store_mfn) )
+        goto error_out;
+
     shared_page_frame = (v_end - PAGE_SIZE) >> PAGE_SHIFT;
 
     if ((e820_page = xc_map_foreign_range(
@@ -627,7 +630,7 @@
 
     if ( mlock(&st_ctxt, sizeof(st_ctxt) ) )
     {
-        PERROR("xc_vmx_build: ctxt mlock failed");
+        PERROR("%s: ctxt mlock failed", __func__);
         return 1;
     }
 
@@ -708,7 +711,6 @@
 
  error_out:
     free(image);
-
     return -1;
 }
 
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xenctrl.h
--- a/tools/libxc/xenctrl.h     Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xenctrl.h     Sat Nov 19 05:16:29 2005
@@ -424,6 +424,9 @@
 int xc_copy_to_domain_page(int xc_handle, uint32_t domid,
                           unsigned long dst_pfn, void *src_page);
 
+int xc_clear_domain_page(int xc_handle, uint32_t domid,
+                         unsigned long dst_pfn);
+
 int xc_ia64_copy_to_domain_pages(int xc_handle, uint32_t domid,
         void* src_page, unsigned long dst_pfn, int nr_pages);
 
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xg_private.h
--- a/tools/libxc/xg_private.h  Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xg_private.h  Sat Nov 19 05:16:29 2005
@@ -153,8 +153,6 @@
     
 } mfn_mapper_t;
 
-unsigned long xc_get_m2p_start_mfn (int xc_handle);
-
 int xc_copy_to_domain_page(int xc_handle, uint32_t domid,
                             unsigned long dst_pfn, void *src_page);
 
diff -r e62c54ab862f -r 878a9891b056 tools/libxc/xg_save_restore.h
--- a/tools/libxc/xg_save_restore.h     Sat Nov 19 05:06:09 2005
+++ b/tools/libxc/xg_save_restore.h     Sat Nov 19 05:16:29 2005
@@ -3,6 +3,8 @@
 ** 
 ** Defintions and utilities for save / restore. 
 */
+
+#include "xc_private.h"
 
 #define DEBUG    1
 #define PROGRESS 0
@@ -55,26 +57,25 @@
 ** Returns 1 on success, 0 on failure. 
 */
 static int get_platform_info(int xc_handle, uint32_t dom, 
-                             /* OUT */ uint32_t *max_mfn,  
-                             /* OUT */ uint32_t *hvirt_start, 
-                             /* OUT */ uint32_t *pt_levels)
+                             /* OUT */ unsigned long *max_mfn,  
+                             /* OUT */ unsigned long *hvirt_start, 
+                             /* OUT */ unsigned int *pt_levels)
     
 { 
     xen_capabilities_info_t xen_caps = "";
-    xen_parameters_info_t xen_parms;
-    xc_physinfo_t physinfo;
+    xen_platform_parameters_t xen_params;
     
-    if (xc_physinfo(xc_handle, &physinfo) != 0) 
-        return 0;
-    
-    if (xc_version(xc_handle, XENVER_parameters, &xen_parms) != 0)
+
+    if (xc_version(xc_handle, XENVER_platform_parameters, &xen_params) != 0)
         return 0;
     
     if (xc_version(xc_handle, XENVER_capabilities, &xen_caps) != 0)
         return 0;
 
-    *max_mfn =     physinfo.total_pages;
-    *hvirt_start = xen_parms.virt_start;
+    if (xc_memory_op(xc_handle, XENMEM_maximum_ram_page, max_mfn) != 0)
+        return 0; 
+    
+    *hvirt_start = xen_params.virt_start;
 
     if (strstr(xen_caps, "xen-3.0-x86_64"))
         *pt_levels = 4;
@@ -95,13 +96,22 @@
 ** entry tell us whether or not the the PFN is currently mapped.
 */
 
-#define PFN_TO_KB(_pfn) ((_pfn) * PAGE_SIZE / 1024)
+#define PFN_TO_KB(_pfn) ((_pfn) << (PAGE_SHIFT - 10))
 #define ROUNDUP(_x,_w) (((unsigned long)(_x)+(1UL<<(_w))-1) & ~((1UL<<(_w))-1))
 
-/* Size in bytes of the M2P and P2M (both rounded up to nearest PAGE_SIZE) */
-#define M2P_SIZE ROUNDUP((max_mfn * sizeof(unsigned long)), PAGE_SHIFT) 
-#define P2M_SIZE ROUNDUP((max_pfn * sizeof(unsigned long)), PAGE_SHIFT) 
 
+/* 
+** The M2P is made up of some number of 'chunks' of at least 2MB in size. 
+** The below definitions and utility function(s) deal with mapping the M2P 
+** regarldess of the underlying machine memory size or architecture. 
+*/
+#define M2P_SHIFT       L2_PAGETABLE_SHIFT_PAE 
+#define M2P_CHUNK_SIZE  (1 << M2P_SHIFT) 
+#define M2P_SIZE(_m)    ROUNDUP(((_m) * sizeof(unsigned long)), M2P_SHIFT) 
+#define M2P_CHUNKS(_m)  (M2P_SIZE((_m)) >> M2P_SHIFT)
+
+/* Size in bytes of the P2M (rounded up to the nearest PAGE_SIZE bytes) */
+#define P2M_SIZE        ROUNDUP((max_pfn * sizeof(unsigned long)), PAGE_SHIFT) 
 
 /* Number of unsigned longs in a page */
 #define ulpp            (PAGE_SIZE/sizeof(unsigned long))
diff -r e62c54ab862f -r 878a9891b056 tools/pygrub/setup.py
--- a/tools/pygrub/setup.py     Sat Nov 19 05:06:09 2005
+++ b/tools/pygrub/setup.py     Sat Nov 19 05:16:29 2005
@@ -34,6 +34,8 @@
     fsys_mods.append(reiser)
     fsys_pkgs.append("grub.fsys.reiser")
 
+pkgs = ['grub', 'grub.fsys']
+pkgs.extend(fsys_pkgs)
 setup(name='pygrub',
       version='0.3',
       description='Boot loader that looks a lot like grub for Xen',
@@ -42,8 +44,7 @@
       license='GPL',
       package_dir={'grub': 'src'},
       scripts = ["src/pygrub"],
-      packages=['grub',
-                'grub.fsys'].extend(fsys_pkgs),
+      packages=pkgs,
       ext_modules = fsys_mods
       )
                
diff -r e62c54ab862f -r 878a9891b056 tools/pygrub/src/pygrub
--- a/tools/pygrub/src/pygrub   Sat Nov 19 05:06:09 2005
+++ b/tools/pygrub/src/pygrub   Sat Nov 19 05:16:29 2005
@@ -89,8 +89,8 @@
     buf = os.read(fd, 512)
     for poff in (446, 462, 478, 494): # partition offsets
         # active partition has 0x80 as the first byte
-        if struct.unpack("<c", buf[p:p+1]) == ('\x80',):
-            return struct.unpack("<", buf[p+8:p+12])[0] * SECTOR_SIZE
+        if struct.unpack("<c", buf[poff:poff+1]) == ('\x80',):
+            return struct.unpack("<L", buf[poff+8:poff+12])[0] * SECTOR_SIZE
     return -1
 
 def get_config(fn):
@@ -113,11 +113,13 @@
             break
 
     if fs is not None:
-        if fs.file_exist("/boot/grub/menu.lst"):
-            grubfile = "/boot/grub/menu.lst"
-        elif fs.file_exist("/boot/grub/grub.conf"):
-            grubfile = "/boot/grub/grub.conf"
-        else:
+        grubfile = None
+        for f in ("/boot/grub/menu.lst", "/boot/grub/grub.conf",
+                  "/grub/menu.lst", "/grub/grub.conf"):
+            if fs.file_exist(f):
+                grubfile = f
+                break
+        if grubfile is None:
             raise RuntimeError, "we couldn't find 
/boot/grub{menu.lst,grub.conf} " + \
                                 "in the image provided. halt!"
         f = fs.open_file(grubfile)
@@ -169,7 +171,7 @@
 #        if c == ord('q'):
 #            selected = -1
 #            break
-        elif c == ord('c'):
+        if c == ord('c'):
             # FIXME: needs to go to command line mode
             continue
         elif c == ord('a'):
@@ -261,7 +263,7 @@
 
     offset = 0
     if is_disk_image(file):
-        offset = get_active_offset(fn)
+        offset = get_active_offset(file)
         if offset == -1:
             raise RuntimeError, "Unable to find active partition on disk"
 
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/lowlevel/xc/xc.c
--- a/tools/python/xen/lowlevel/xc/xc.c Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/lowlevel/xc/xc.c Sat Nov 19 05:16:29 2005
@@ -49,19 +49,16 @@
 
     if ( !PyArg_ParseTupleAndKeywords(args, kwds, "is", kwd_list,
                                       &dom, &corefile) )
-        goto exit;
+        return NULL;
 
     if ( (corefile == NULL) || (corefile[0] == '\0') )
-        goto exit;
+        return NULL;
 
     if ( xc_domain_dumpcore(xc->xc_handle, dom, corefile) != 0 )
         return PyErr_SetFromErrno(xc_error);
     
     Py_INCREF(zero);
     return zero;
-
- exit:
-    return NULL;
 }
 
 static PyObject *pyxc_handle(PyObject *self)
@@ -95,12 +92,7 @@
     {
         if ( !PyList_Check(pyhandle) || 
              (PyList_Size(pyhandle) != sizeof(xen_domain_handle_t)) )
-        {
-        out_exception:
-            errno = EINVAL;
-            PyErr_SetFromErrno(xc_error);
-            return NULL;
-        }
+            goto out_exception;
 
         for ( i = 0; i < sizeof(xen_domain_handle_t); i++ )
         {
@@ -115,6 +107,11 @@
         return PyErr_SetFromErrno(xc_error);
 
     return PyInt_FromLong(dom);
+
+out_exception:
+    errno = EINVAL;
+    PyErr_SetFromErrno(xc_error);
+    return NULL;
 }
 
 static PyObject *pyxc_domain_max_vcpus(PyObject *self,
@@ -270,10 +267,7 @@
     if ( !PyList_Check(pyhandle) || 
          (PyList_Size(pyhandle) != sizeof(xen_domain_handle_t)) )
     {
-    out_exception:
-        errno = EINVAL;
-        PyErr_SetFromErrno(xc_error);
-        return NULL;
+        goto out_exception;
     }
 
     for ( i = 0; i < sizeof(xen_domain_handle_t); i++ )
@@ -289,7 +283,13 @@
     
     Py_INCREF(zero);
     return zero;
-}
+
+out_exception:
+    errno = EINVAL;
+    PyErr_SetFromErrno(xc_error);
+    return NULL;
+}
+
 
 static PyObject *pyxc_domain_getinfo(PyObject *self,
                                      PyObject *args,
@@ -721,7 +721,7 @@
     xen_compile_info_t xen_cc;
     xen_changeset_info_t xen_chgset;
     xen_capabilities_info_t xen_caps;
-    xen_parameters_info_t xen_parms;
+    xen_platform_parameters_t p_parms;
     long xen_version;
     char str[128];
 
@@ -739,17 +739,17 @@
     if ( xc_version(xc->xc_handle, XENVER_capabilities, &xen_caps) != 0 )
         return PyErr_SetFromErrno(xc_error);
 
-    if ( xc_version(xc->xc_handle, XENVER_parameters, &xen_parms) != 0 )
-        return PyErr_SetFromErrno(xc_error);
-
-    sprintf(str,"virt_start=0x%lx",xen_parms.virt_start);
+    if ( xc_version(xc->xc_handle, XENVER_platform_parameters, &p_parms) != 0 )
+        return PyErr_SetFromErrno(xc_error);
+
+    sprintf(str, "virt_start=0x%lx", p_parms.virt_start);
 
     return Py_BuildValue("{s:i,s:i,s:s,s:s,s:s,s:s,s:s,s:s,s:s,s:s}",
                          "xen_major", xen_version >> 16,
                          "xen_minor", (xen_version & 0xffff),
                          "xen_extra", xen_extra,
                          "xen_caps",  xen_caps,
-                         "xen_params", str,
+                         "platform_params", str,
                          "xen_changeset", xen_chgset,
                          "cc_compiler", xen_cc.compiler,
                          "cc_compile_by", xen_cc.compile_by,
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/lowlevel/xs/xs.c
--- a/tools/python/xen/lowlevel/xs/xs.c Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/lowlevel/xs/xs.c Sat Nov 19 05:16:29 2005
@@ -16,11 +16,12 @@
  *
  * Copyright (C) 2005 Mike Wray Hewlett-Packard
  * Copyright (C) 2005 Christian Limpach <Christian.Limpach@xxxxxxxxxxxx>
- *
+ * Copyright (C) 2005 XenSource Ltd.
  */
 
 #include <Python.h>
 
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
@@ -70,6 +71,17 @@
             : PyErr_SetFromErrno(PyExc_RuntimeError));
 }
 
+static void remove_watch(XsHandle *xsh, PyObject *token);
+
+static PyObject *none(bool result);
+
+static int parse_transaction_path(PyObject *self, PyObject *args,
+                                  PyObject *kwds,
+                                  struct xs_handle **xh,
+                                  struct xs_transaction_handle **th,
+                                  char **path);
+
+
 #define xspy_read_doc "\n"                     \
        "Read data from a path.\n"              \
        " path [string]: xenstore path\n"       \
@@ -81,43 +93,29 @@
 
 static PyObject *xspy_read(PyObject *self, PyObject *args, PyObject *kwds)
 {
-    static char *kwd_spec[] = { "transaction", "path", NULL };
-    static char *arg_spec = "ss";
-    char *path = NULL;
-
-    struct xs_handle *xh = xshandle(self);
-    char *xsval = NULL;
-    unsigned int xsval_n = 0;
-    PyObject *val = NULL;
-
+    struct xs_handle *xh;
     struct xs_transaction_handle *th;
-    char *thstr;
-
-    if (!xh)
-        goto exit;
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
-                                     &thstr, &path))
-        goto exit;
-
-    th = (struct xs_transaction_handle *)strtoul(thstr, NULL, 16);
+    char *path;
+
+    char *xsval;
+    unsigned int xsval_n;
+
+    if (!parse_transaction_path(self, args, kwds, &xh, &th, &path))
+        return NULL;
 
     Py_BEGIN_ALLOW_THREADS
     xsval = xs_read(xh, th, path, &xsval_n);
     Py_END_ALLOW_THREADS
-    if (!xsval) {
-        if (errno == ENOENT) {
-            Py_INCREF(Py_None);
-            val = Py_None;
-        } else
-            PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    val = PyString_FromStringAndSize(xsval, xsval_n);
- exit:
-    if (xsval)
+    if (xsval) {
+        PyObject *val = PyString_FromStringAndSize(xsval, xsval_n);
         free(xsval);
-    return val;
-}
+        return val;
+    }
+    else {
+        return none(errno == ENOENT);
+    }
+}
+
 
 #define xspy_write_doc "\n"                                    \
        "Write data to a path.\n"                               \
@@ -137,32 +135,26 @@
     int data_n = 0;
 
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    int xsval = 0;
+    bool result;
 
     struct xs_transaction_handle *th;
     char *thstr;
 
     if (!xh)
-        goto exit;
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
                                      &thstr, &path, &data, &data_n))
-        goto exit;
+        return NULL;
 
     th = (struct xs_transaction_handle *)strtoul(thstr, NULL, 16);
 
     Py_BEGIN_ALLOW_THREADS
-    xsval = xs_write(xh, th, path, data, data_n);
-    Py_END_ALLOW_THREADS
-    if (!xsval) {
-        PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    Py_INCREF(Py_None);
-    val = Py_None;
- exit:
-    return val;
-}
+    result = xs_write(xh, th, path, data, data_n);
+    Py_END_ALLOW_THREADS
+
+    return none(result);
+}
+
 
 #define xspy_ls_doc "\n"                                       \
        "List a directory.\n"                                   \
@@ -175,46 +167,33 @@
 
 static PyObject *xspy_ls(PyObject *self, PyObject *args, PyObject *kwds)
 {
-    static char *kwd_spec[] = { "transaction", "path", NULL };
-    static char *arg_spec = "ss";
-    char *path = NULL;
-
-    struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    char **xsval = NULL;
-    unsigned int xsval_n = 0;
-    int i;
-
+    struct xs_handle *xh;
     struct xs_transaction_handle *th;
-    char *thstr;
-
-    if (!xh)
-        goto exit;
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
-                                     &thstr, &path))
-        goto exit;
-
-
-    th = (struct xs_transaction_handle *)strtoul(thstr, NULL, 16);
+    char *path;
+
+    char **xsval;
+    int xsval_n;
+
+    if (!parse_transaction_path(self, args, kwds, &xh, &th, &path))
+        return NULL;
 
     Py_BEGIN_ALLOW_THREADS
     xsval = xs_directory(xh, th, path, &xsval_n);
     Py_END_ALLOW_THREADS
-    if (!xsval) {
-        if (errno == ENOENT) {
-            Py_INCREF(Py_None);
-            val = Py_None;
-        } else
-            PyErr_SetFromErrno(PyExc_RuntimeError);
-       goto exit;
-    }
-    val = PyList_New(xsval_n);
-    for (i = 0; i < xsval_n; i++)
-        PyList_SetItem(val, i, PyString_FromString(xsval[i]));
-    free(xsval);
- exit:
-    return val;
-}
+
+    if (xsval) {
+        int i;
+        PyObject *val = PyList_New(xsval_n);
+        for (i = 0; i < xsval_n; i++)
+            PyList_SetItem(val, i, PyString_FromString(xsval[i]));
+        free(xsval);
+        return val;
+    }
+    else {
+        return none(errno == ENOENT);
+    }
+}
+
 
 #define xspy_mkdir_doc "\n"                                    \
        "Make a directory.\n"                                   \
@@ -226,37 +205,22 @@
 
 static PyObject *xspy_mkdir(PyObject *self, PyObject *args, PyObject *kwds)
 {
-    static char *kwd_spec[] = { "transaction", "path", NULL };
-    static char *arg_spec = "ss";
-    char *path = NULL;
-
-    struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    int xsval = 0;
-
+    struct xs_handle *xh;
     struct xs_transaction_handle *th;
-    char *thstr;
-
-    if (!xh)
-        goto exit;
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
-                                     &thstr, &path))
-        goto exit;
-
-    th = (struct xs_transaction_handle *)strtoul(thstr, NULL, 16);
-
-    Py_BEGIN_ALLOW_THREADS
-    xsval = xs_mkdir(xh, th, path);
-    Py_END_ALLOW_THREADS
-    if (!xsval) {
-        PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    Py_INCREF(Py_None);
-    val = Py_None;
- exit:
-    return val;
-}
+    char *path;
+
+    bool result;
+
+    if (!parse_transaction_path(self, args, kwds, &xh, &th, &path))
+        return NULL;
+
+    Py_BEGIN_ALLOW_THREADS
+    result = xs_mkdir(xh, th, path);
+    Py_END_ALLOW_THREADS
+
+    return none(result);
+}
+
 
 #define xspy_rm_doc "\n"                       \
        "Remove a path.\n"                      \
@@ -268,37 +232,22 @@
 
 static PyObject *xspy_rm(PyObject *self, PyObject *args, PyObject *kwds)
 {
-    static char *kwd_spec[] = { "transaction", "path", NULL };
-    static char *arg_spec = "ss";
-    char *path = NULL;
-
-    struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    int xsval = 0;
-
+    struct xs_handle *xh;
     struct xs_transaction_handle *th;
-    char *thstr;
-
-    if (!xh)
-        goto exit;
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
-                                     &thstr, &path))
-        goto exit;
-
-    th = (struct xs_transaction_handle *)strtoul(thstr, NULL, 16);
-
-    Py_BEGIN_ALLOW_THREADS
-    xsval = xs_rm(xh, th, path);
-    Py_END_ALLOW_THREADS
-    if (!xsval && errno != ENOENT) {
-        PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    Py_INCREF(Py_None);
-    val = Py_None;
- exit:
-    return val;
-}
+    char *path;
+
+    bool result;
+
+    if (!parse_transaction_path(self, args, kwds, &xh, &th, &path))
+        return NULL;
+
+    Py_BEGIN_ALLOW_THREADS
+    result = xs_rm(xh, th, path);
+    Py_END_ALLOW_THREADS
+
+    return none(result || errno == ENOENT);
+}
+
 
 #define xspy_get_permissions_doc "\n"          \
        "Get the permissions for a path\n"      \
@@ -316,7 +265,6 @@
     char *path = NULL;
 
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
     struct xs_permissions *perms;
     unsigned int perms_n = 0;
     int i;
@@ -325,30 +273,34 @@
     char *thstr;
 
     if (!xh)
-        goto exit;
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
                                      &thstr, &path))
-        goto exit;
+        return NULL;
 
     th = (struct xs_transaction_handle *)strtoul(thstr, NULL, 16);
 
     Py_BEGIN_ALLOW_THREADS
     perms = xs_get_permissions(xh, th, path, &perms_n);
     Py_END_ALLOW_THREADS
-    if (!perms) {
+
+    if (perms) {
+        PyObject *val = PyList_New(perms_n);
+        for (i = 0; i < perms_n; i++, perms++) {
+            PyObject *p = Py_BuildValue("{s:i,s:i,s:i}",
+                                        "dom",  perms->id,
+                                        "read", perms->perms & XS_PERM_READ,
+                                        "write",perms->perms & XS_PERM_WRITE);
+            PyList_SetItem(val, i, p);
+        }
+
+        free(perms);
+        return val;
+    }
+    else {
         PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    val = PyList_New(perms_n);
-    for (i = 0; i < perms_n; i++, perms++) {
-        PyObject *p = Py_BuildValue("{s:i,s:i,s:i}",
-                                    "dom",   perms->id,
-                                    "read",  (perms->perms & XS_PERM_READ),
-                                    "write",  (perms->perms & XS_PERM_WRITE));
-        PyList_SetItem(val, i, p);
-    }
- exit:
-    return val;
+        return NULL;
+    }
 }
 
 #define xspy_set_permissions_doc "\n"          \
@@ -371,7 +323,7 @@
     static char *perm_spec = "i|iiii";
 
     struct xs_handle *xh = xshandle(self);
-    int i, xsval;
+    int i, result;
     struct xs_permissions *xsperms = NULL;
     int xsperms_n = 0;
     PyObject *tuple0 = NULL;
@@ -417,9 +369,9 @@
             xsperms[i].perms |= XS_PERM_WRITE;
     }
     Py_BEGIN_ALLOW_THREADS
-    xsval = xs_set_permissions(xh, th, path, xsperms, xsperms_n);
-    Py_END_ALLOW_THREADS
-    if (!xsval) {
+    result = xs_set_permissions(xh, th, path, xsperms, xsperms_n);
+    Py_END_ALLOW_THREADS
+    if (!result) {
         PyErr_SetFromErrno(PyExc_RuntimeError);
         goto exit;
     }
@@ -427,8 +379,7 @@
     val = Py_None;
  exit:
     Py_XDECREF(tuple0);
-    if (xsperms)
-        free(xsperms);
+    free(xsperms);
     return val;
 }
 
@@ -455,38 +406,39 @@
 
     XsHandle *xsh = (XsHandle *)self;
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    int xsval = 0;
-
-    if (!xh)
-        goto exit;
+    int result = 0;
+
+    if (!xh)
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec, 
                                      &path, &token))
-        goto exit;
-    Py_INCREF(token);
-    sprintf(token_str, "%li", (unsigned long)token);
-    Py_BEGIN_ALLOW_THREADS
-    xsval = xs_watch(xh, path, token_str);
-    Py_END_ALLOW_THREADS
-    if (!xsval) {
-        PyErr_SetFromErrno(PyExc_RuntimeError);
-        Py_DECREF(token);
-        goto exit;
-    }
+        return NULL;
+
+    /* Note that we have to store the watch token in the xs->watches list
+       before registering the watch with xs_watch, otherwise this function
+       races with xs_read_watch.
+    */
 
     for (i = 0; i < PyList_Size(xsh->watches); i++) {
         if (PyList_GetItem(xsh->watches, i) == Py_None) {
-            PyList_SetItem(xsh->watches, i, token);
+            PySequence_SetItem(xsh->watches, i, token);
             break;
         }
     }
     if (i == PyList_Size(xsh->watches))
         PyList_Append(xsh->watches, token);
-    Py_INCREF(Py_None);
-    val = Py_None;
- exit:
-    return val;
-}
+
+    sprintf(token_str, "%li", (unsigned long)token);
+    Py_BEGIN_ALLOW_THREADS
+    result = xs_watch(xh, path, token_str);
+    Py_END_ALLOW_THREADS
+
+    if (!result)
+        remove_watch(xsh, token);
+
+    return none(result);
+}
+
 
 #define xspy_read_watch_doc "\n"                               \
        "Read a watch notification.\n"                          \
@@ -510,9 +462,10 @@
     unsigned int num;
 
     if (!xh)
-        goto exit;
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec))
-        goto exit;
+        return NULL;
+
 again:
     Py_BEGIN_ALLOW_THREADS
     xsval = xs_read_watch(xh, &num);
@@ -541,8 +494,7 @@
     /* Create tuple (path, token). */
     val = Py_BuildValue("(sO)", xsval[XS_WATCH_PATH], token);
  exit:
-    if (xsval)
-        free(xsval);
+    free(xsval);
     return val;
 }
 
@@ -562,37 +514,25 @@
     char *path = NULL;
     PyObject *token;
     char token_str[MAX_STRLEN(unsigned long) + 1];
-    int i;
 
     XsHandle *xsh = (XsHandle *)self;
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    int xsval = 0;
-
-    if (!xh)
-        goto exit;
+    int result = 0;
+
+    if (!xh)
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec, &path,
                                      &token))
-        goto exit;
+        return NULL;
+
     sprintf(token_str, "%li", (unsigned long)token);
     Py_BEGIN_ALLOW_THREADS
-    xsval = xs_unwatch(xh, path, token_str);
-    Py_END_ALLOW_THREADS
-    if (!xsval)
-        PyErr_SetFromErrno(PyExc_RuntimeError);
-    else {
-        Py_INCREF(Py_None);
-        val = Py_None;
-    }
-    for (i = 0; i < PyList_Size(xsh->watches); i++) {
-        if (token == PyList_GetItem(xsh->watches, i)) {
-            Py_INCREF(Py_None);
-            PyList_SetItem(xsh->watches, i, Py_None);
-            break;
-        }
-    }
- exit:
-    return val;
+    result = xs_unwatch(xh, path, token_str);
+    Py_END_ALLOW_THREADS
+
+    remove_watch(xsh, token);
+
+    return none(result);
 }
 
 #define xspy_transaction_start_doc "\n"                                \
@@ -610,26 +550,25 @@
     char *path = NULL;
 
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
     struct xs_transaction_handle *th;
     char thstr[20];
 
     if (!xh)
-        goto exit;
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec, &path))
-        goto exit;
+        return NULL;
+
     Py_BEGIN_ALLOW_THREADS
     th = xs_transaction_start(xh);
     Py_END_ALLOW_THREADS
+
     if (th == NULL) {
         PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
+        return NULL;
     }
 
     sprintf(thstr, "%lX", (unsigned long)th);
-    val = PyString_FromString(thstr);
- exit:
-    return val;
+    return PyString_FromString(thstr);
 }
 
 #define xspy_transaction_end_doc "\n"                                  \
@@ -649,37 +588,37 @@
     int abort = 0;
 
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    int xsval = 0;
+    bool result;
 
     struct xs_transaction_handle *th;
     char *thstr;
 
     if (!xh)
-        goto exit;
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
                                      &thstr, &abort))
-        goto exit;
+        return NULL;
 
     th = (struct xs_transaction_handle *)strtoul(thstr, NULL, 16);
 
     Py_BEGIN_ALLOW_THREADS
-    xsval = xs_transaction_end(xh, th, abort);
-    Py_END_ALLOW_THREADS
-    if (!xsval) {
-       if (errno == EAGAIN) {
-           Py_INCREF(Py_False);
-           val = Py_False;
-           goto exit;
-       }
+    result = xs_transaction_end(xh, th, abort);
+    Py_END_ALLOW_THREADS
+
+    if (result) {
+        Py_INCREF(Py_True);
+        return Py_True;
+    }
+    else if (errno == EAGAIN) {
+        Py_INCREF(Py_False);
+        return Py_False;
+    }
+    else {
         PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    Py_INCREF(Py_True);
-    val = Py_True;
- exit:
-    return val;
-}
+        return NULL;
+    }
+}
+
 
 #define xspy_introduce_domain_doc "\n"                                 \
        "Tell xenstore about a domain so it can talk to it.\n"          \
@@ -701,26 +640,21 @@
     unsigned int port = 0;
 
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    int xsval = 0;
-
-    if (!xh)
-        goto exit;
+    bool result = 0;
+
+    if (!xh)
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
                                      &dom, &page, &port))
-        goto exit;
-    Py_BEGIN_ALLOW_THREADS
-    xsval = xs_introduce_domain(xh, dom, page, port);
-    Py_END_ALLOW_THREADS
-    if (!xsval) {
-        PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    Py_INCREF(Py_None);
-    val = Py_None;
- exit:
-    return val;
-}
+        return NULL;
+
+    Py_BEGIN_ALLOW_THREADS
+    result = xs_introduce_domain(xh, dom, page, port);
+    Py_END_ALLOW_THREADS
+
+    return none(result);
+}
+
 
 #define xspy_release_domain_doc "\n"                                   \
        "Tell xenstore to release its channel to a domain.\n"           \
@@ -735,30 +669,25 @@
                                      PyObject *kwds)
 {
     static char *kwd_spec[] = { "dom", NULL };
-    static char *arg_spec = "i|";
+    static char *arg_spec = "i";
     domid_t dom;
 
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-    int xsval = 0;
-
-    if (!xh)
-        goto exit;
+    bool result = 0;
+
+    if (!xh)
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
                                      &dom))
-        goto exit;
-    Py_BEGIN_ALLOW_THREADS
-    xsval = xs_release_domain(xh, dom);
-    Py_END_ALLOW_THREADS
-    if (!xsval) {
-        PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    Py_INCREF(Py_None);
-    val = Py_None;
- exit:
-    return val;
-}
+        return NULL;
+
+    Py_BEGIN_ALLOW_THREADS
+    result = xs_release_domain(xh, dom);
+    Py_END_ALLOW_THREADS
+
+    return none(result);
+}
+
 
 #define xspy_close_doc "\n"                    \
        "Close the connection to xenstore.\n"   \
@@ -775,24 +704,24 @@
 
     XsHandle *xsh = (XsHandle *)self;
     struct xs_handle *xh = xshandle(self);
-    PyObject *val = NULL;
-
-    if (!xh)
-        goto exit;
+
+    if (!xh)
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec))
-        goto exit;
+        return NULL;
+
     for (i = 0; i < PyList_Size(xsh->watches); i++) {
         /* TODO: xs_unwatch watches */
-        Py_INCREF(Py_None);
-        PyList_SetItem(xsh->watches, i, Py_None);
-    }
+        PySequence_SetItem(xsh->watches, i, Py_None);
+    }
+
     xs_daemon_close(xh);
     xsh->xh = NULL;
+
     Py_INCREF(Py_None);
-    val = Py_None;
- exit:
-    return val;
-}
+    return Py_None;
+}
+
 
 #define xspy_get_domain_path_doc "\n"                  \
        "Return store path of domain, whether or not the domain exists.\n" \
@@ -811,29 +740,90 @@
 
     struct xs_handle *xh = xshandle(self);
     char *xsval = NULL;
-    PyObject *val = NULL;
-
-    if (!xh)
-        goto exit;
+
+    if (!xh)
+        return NULL;
     if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
                                      &domid))
-        goto exit;
+        return NULL;
+
     Py_BEGIN_ALLOW_THREADS
     xsval = xs_get_domain_path(xh, domid);
     Py_END_ALLOW_THREADS
-    if (!xsval) {
-        if (errno == ENOENT) {
-            Py_INCREF(Py_None);
-            val = Py_None;
-        } else
-            PyErr_SetFromErrno(PyExc_RuntimeError);
-        goto exit;
-    }
-    val = PyString_FromString(xsval);
-    free(xsval);
- exit:
-    return val;
-}
+
+    if (xsval) {
+        PyObject *val = PyString_FromString(xsval);
+        free(xsval);
+        return val;
+    }
+    else {
+        return none(errno == ENOENT);
+    }
+}
+
+
+/**
+ * Remove the given token from the watches list belonging to the given
+ * XsHandle, if present.
+ */
+static void remove_watch(XsHandle *xsh, PyObject *token)
+{
+    int i;
+
+    for (i = 0; i < PyList_Size(xsh->watches); i++) {
+        if (PyList_GetItem(xsh->watches, i) == token) {
+            PySequence_SetItem(xsh->watches, i, Py_None);
+            return;
+        }
+    }
+}
+
+
+/**
+ * Parse transaction and path arguments from the given args and kwds,
+ * convert the given self value to an xs_handle, and return all three by
+ * reference.
+ * 
+ * @return 1 on success, in which case *xh, *th, and *path are valid, or 0 on
+ * failure.
+ */
+static int parse_transaction_path(PyObject *self, PyObject *args,
+                                  PyObject *kwds,
+                                  struct xs_handle **xh,
+                                  struct xs_transaction_handle **th,
+                                  char **path)
+{
+    static char *arg_spec = "ss";
+    static char *kwd_spec[] = { "transaction", "path", NULL };
+    char *thstr;
+
+    *xh = xshandle(self);
+
+    if (!xh)
+        return 0;
+
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, arg_spec, kwd_spec,
+                                     &thstr, path))
+        return 0;
+
+    *th = (struct xs_transaction_handle *)strtoul(thstr, NULL, 16);
+
+    return 1;
+}
+
+
+static PyObject *none(bool result)
+{
+    if (result) {
+        Py_INCREF(Py_None);
+        return Py_None;
+    }
+    else {
+        PyErr_SetFromErrno(PyExc_RuntimeError);
+        return NULL;
+    }
+}
+
 
 #define XSPY_METH(_name) {                     \
     .ml_name  = #_name,                                \
@@ -863,9 +853,7 @@
 
 static PyObject *xshandle_getattr(PyObject *self, char *name)
 {
-    PyObject *val = NULL;
-    val = Py_FindMethod(xshandle_methods, self, name);
-    return val;
+    return Py_FindMethod(xshandle_methods, self, name);
 }
 
 static void xshandle_dealloc(PyObject *self)
@@ -947,3 +935,11 @@
 
     module = Py_InitModule(PYPKG, xs_methods);
 }
+
+
+/*
+ * Local variables:
+ *  c-indent-level: 4
+ *  c-basic-offset: 4
+ * End:
+ */
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/util/diagnose.py
--- a/tools/python/xen/util/diagnose.py Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/util/diagnose.py Sat Nov 19 05:16:29 2005
@@ -22,6 +22,7 @@
 from xen.xend.XendClient import server
 from xen.xend.XendError import XendError
 from xen.xend.xenstore.xstransact import xstransact
+from xen.xend.server import DevController
 
 import xen.xend.XendProtocol
 
@@ -107,34 +108,57 @@
                 print ("Cannot find backend path for device %s, %s." %
                        (deviceClass, device))
             else:
-                backend_error = xstransact.Read(
-                    backendPath.replace('backend/', 'error/backend/'),
-                    'error')
+                frontend_state = xstransact.Read(frontendPath, 'state')
+                backend_state  = xstransact.Read(backendPath,  'state')
 
-                if backend_error:
-                    diagnose_device_error(backend_error)
+                print "Backend is in state %s." %  stateString(backend_state)
+                print "Frontend is in state %s." % stateString(frontend_state)
+
+                check_for_error(True)
+                check_for_error(False)
+
+                diagnose_hotplugging()
 
 
-def diagnose_device_error(err):
-    if re.search("2 reading .*/ring-ref and event-channel", err):
-        print ("Backend is stuck waiting for frontend for device %s, %s." %
-               (deviceClass, device))
-        diagnose_stuck_frontend()
+def check_for_error(backend):
+    if backend:
+        path = backendPath.replace('backend/', 'error/backend/')
     else:
-        print ("Device %s, %s shows error %s." %
-               (deviceClass, device, err))
+        path = frontendPath.replace('device/', 'error/device/')
+
+    err = xstransact.Read(path, 'error')
+
+    if err:
+        print ("%s for device %s, %s shows error %s." %
+               (backend and 'Backend' or 'Frontend', deviceClass, device,
+                err))
 
 
-def diagnose_stuck_frontend():
-    if deviceClass == "vbd":
+def diagnose_hotplugging():
+    if deviceClass == 'vbd':
         phy = xstransact.Read(backendPath, 'physical-device')
 
         if phy:
-            print ("Device %s, %s hotplugging has completed successfully." %
+            print ('Device %s, %s hotplugging has completed successfully, '
+                   'and is connected to physical device %s.' %
+                   (deviceClass, device, phy))
+        else:
+            print ('Device %s, %s hotplugging failed.' %
                    (deviceClass, device))
+    elif deviceClass == 'vif':
+        handle = xstransact.Read(backendPath, 'handle')
+
+        if handle:
+            print ('Device %s, %s hotplugging has completed successfully, '
+                   'and is using handle %s.' %
+                   (deviceClass, device, handle))
         else:
-            print ("Device %s, %s hotplugging failed." %
+            print ('Device %s, %s hotplugging failed.' %
                    (deviceClass, device))
+
+
+def stateString(state):
+    return state and DevController.xenbusState[int(state)] or '<None>'
 
 
 def main(argv = None):
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xend/XendCheckpoint.py
--- a/tools/python/xen/xend/XendCheckpoint.py   Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/XendCheckpoint.py   Sat Nov 19 05:16:29 2005
@@ -129,7 +129,7 @@
         l = read_exact(fd, sizeof_unsigned_long,
                        "not a valid guest state file: pfn count read")
         nr_pfns = unpack("=L", l)[0]   # XXX endianess
-        if nr_pfns > 1024*1024:     # XXX
+        if nr_pfns > 16*1024*1024:     # XXX 
             raise XendError(
                 "not a valid guest state file: pfn count out of range")
 
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xend/XendClient.py
--- a/tools/python/xen/xend/XendClient.py       Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/XendClient.py       Sat Nov 19 05:16:29 2005
@@ -301,13 +301,6 @@
         return self.xendPost(self.domainurl(dom),
                             {'op'    : 'set_vcpus',
                              'vcpus' : vcpus })
-
-    def xend_domain_vif_limit(self, id, vif, credit, period):
-        return self.xendPost(self.domainurl(id),
-                            { 'op'      : 'vif_limit_set',
-                              'vif'     : vif,
-                              'credit'  : credit,
-                              'period'  : period })
 
     def xend_domain_devices(self, id, type):
         return self.xendPost(self.domainurl(id),
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xend/XendDomain.py
--- a/tools/python/xen/xend/XendDomain.py       Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/XendDomain.py       Sat Nov 19 05:16:29 2005
@@ -36,6 +36,7 @@
 from xen.xend.XendError import XendError
 from xen.xend.XendLogging import log
 from xen.xend.server import relocate
+from xen.xend.xenstore.xswatch import xswatch
 
 
 xc = xen.lowlevel.xc.new()
@@ -58,9 +59,9 @@
         # to import XendDomain from XendDomainInfo causes unbounded recursion.
         # So we stuff the XendDomain instance (self) into xroot's components.
         xroot.add_component("xen.xend.XendDomain", self)
+
         self.domains = {}
         self.domains_lock = threading.RLock()
-        self.watchReleaseDomain()
 
         self.domains_lock.acquire()
         try:
@@ -68,6 +69,13 @@
                 XendDomainInfo.recreate(self.xen_domains()[PRIV_DOMAIN],
                                         True))
             self.dom0_setup()
+
+            # This watch registration needs to be before the refresh call, so
+            # that we're sure that we haven't missed any releases, but inside
+            # the domains_lock, as we don't want the watch to fire until after
+            # the refresh call has completed.
+            xswatch("@releaseDomain", self.onReleaseDomain)
+            
             self.refresh(True)
         finally:
             self.domains_lock.release()
@@ -112,11 +120,7 @@
             self.refresh()
         finally:
             self.domains_lock.release()
-            
-
-    def watchReleaseDomain(self):
-        from xen.xend.xenstore.xswatch import xswatch
-        self.releaseDomain = xswatch("@releaseDomain", self.onReleaseDomain)
+        return 1
 
 
     def xen_domains(self):
@@ -467,17 +471,6 @@
         except Exception, ex:
             raise XendError(str(ex))
 
-
-    def domain_vif_limit_set(self, domid, vif, credit, period):
-        """Limit the vif's transmission rate
-        """
-        dominfo = self.domain_lookup(domid)
-        dev = dominfo.getDevice('vif', vif)
-        if not dev:
-            raise XendError("invalid vif")
-        return dev.setCreditLimit(credit, period)
-
-
     def domain_maxmem_set(self, domid, mem):
         """Set the memory limit for a domain.
 
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xend/XendDomainInfo.py
--- a/tools/python/xen/xend/XendDomainInfo.py   Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/XendDomainInfo.py   Sat Nov 19 05:16:29 2005
@@ -45,6 +45,8 @@
 
 from xen.xend.xenstore.xstransact import xstransact
 from xen.xend.xenstore.xsutil import GetDomainPath, IntroduceDomain
+from xen.xend.xenstore.xswatch import xswatch
+
 
 """Shutdown code for poweroff."""
 DOMAIN_POWEROFF = 0
@@ -82,7 +84,6 @@
 
 SHUTDOWN_TIMEOUT = 30
 
-DOMROOT = '/local/domain/'
 VMROOT  = '/vm/'
 
 ZOMBIE_PREFIX = 'Zombie-'
@@ -100,26 +101,52 @@
 #log.setLevel(logging.TRACE)
 
 
-## Configuration entries that we expect to round-trip -- be read from the
+##
+# All parameters of VMs that may be configured on-the-fly, or at start-up.
+# 
+VM_CONFIG_PARAMS = [
+    ('name',        str),
+    ('on_poweroff', str),
+    ('on_reboot',   str),
+    ('on_crash',    str),
+    ]
+
+
+##
+# Configuration entries that we expect to round-trip -- be read from the
 # config file or xc, written to save-files (i.e. through sxpr), and reused as
 # config on restart or restore, all without munging.  Some configuration
 # entries are munged for backwards compatibility reasons, or because they
 # don't come out of xc in the same form as they are specified in the config
 # file, so those are handled separately.
 ROUNDTRIPPING_CONFIG_ENTRIES = [
-        ('name',         str),
-        ('uuid',         str),
-        ('ssidref',      int),
-        ('vcpus',        int),
-        ('vcpu_avail',   int),
-        ('cpu_weight',   float),
-        ('memory',       int),
-        ('maxmem',       int),
-        ('bootloader',   str),
-        ('on_poweroff',  str),
-        ('on_reboot',    str),
-        ('on_crash',     str)
+    ('uuid',       str),
+    ('ssidref',    int),
+    ('vcpus',      int),
+    ('vcpu_avail', int),
+    ('cpu_weight', float),
+    ('memory',     int),
+    ('maxmem',     int),
+    ('bootloader', str),
     ]
+
+ROUNDTRIPPING_CONFIG_ENTRIES += VM_CONFIG_PARAMS
+
+
+##
+# All entries written to the store.  This is VM_CONFIGURATION_PARAMS, plus
+# those entries written to the store that cannot be reconfigured on-the-fly.
+#
+VM_STORE_ENTRIES = [
+    ('uuid',       str),
+    ('ssidref',    int),
+    ('vcpus',      int),
+    ('vcpu_avail', int),
+    ('memory',     int),
+    ('maxmem',     int),
+    ]
+
+VM_STORE_ENTRIES += VM_CONFIG_PARAMS
 
 
 #
@@ -156,6 +183,7 @@
         vm.initDomain()
         vm.storeVmDetails()
         vm.storeDomDetails()
+        vm.registerWatch()
         vm.refreshShutdown()
         return vm
     except:
@@ -211,6 +239,7 @@
         vm.storeVmDetails()
         vm.storeDomDetails()
 
+    vm.registerWatch()
     vm.refreshShutdown(xeninfo)
     return vm
 
@@ -371,12 +400,50 @@
         self.console_port = None
         self.console_mfn = None
 
+        self.vmWatch = None
+
         self.state = STATE_DOM_OK
         self.state_updated = threading.Condition()
         self.refresh_shutdown_lock = threading.Condition()
 
 
     ## private:
+
+    def readVMDetails(self, params):
+        """Read from the store all of those entries that we consider 
+        """
+        try:
+            return self.gatherVm(*params)
+        except ValueError:
+            # One of the int/float entries in params has a corresponding store
+            # entry that is invalid.  We recover, because older versions of
+            # Xend may have put the entry there (memory/target, for example),
+            # but this is in general a bad situation to have reached.
+            log.exception(
+                "Store corrupted at %s!  Domain %d's configuration may be "
+                "affected.", self.vmpath, self.domid)
+            return []
+
+
+    def storeChanged(self):
+        log.debug("XendDomainInfo.storeChanged");
+
+        changed = False
+        
+        def f(x, y):
+            if y is not None and self.info[x[0]] != y:
+                self.info[x[0]] = y
+                changed = True
+
+        map(f, VM_CONFIG_PARAMS, self.readVMDetails(VM_CONFIG_PARAMS))
+
+        if changed:
+            # Update the domain section of the store, as this contains some
+            # parameters derived from the VM configuration.
+            self.storeDomDetails()
+
+        return 1
+
 
     def augmentInfo(self):
         """Augment self.info, as given to us through {@link #recreate}, with
@@ -387,30 +454,8 @@
             if not self.infoIsSet(name) and val is not None:
                 self.info[name] = val
 
-        params = (("name", str),
-                  ("on_poweroff",  str),
-                  ("on_reboot",    str),
-                  ("on_crash",     str),
-                  ("image",        str),
-                  ("memory",       int),
-                  ("maxmem",       int),
-                  ("vcpus",        int),
-                  ("vcpu_avail",   int),
-                  ("start_time", float))
-
-        try:
-            from_store = self.gatherVm(*params)
-        except ValueError, exn:
-            # One of the int/float entries in params has a corresponding store
-            # entry that is invalid.  We recover, because older versions of
-            # Xend may have put the entry there (memory/target, for example),
-            # but this is in general a bad situation to have reached.
-            log.exception(
-                "Store corrupted at %s!  Domain %d's configuration may be "
-                "affected.", self.vmpath, self.domid)
-            return
-
-        map(lambda x, y: useIfNeeded(x[0], y), params, from_store)
+        map(lambda x, y: useIfNeeded(x[0], y), VM_STORE_ENTRIES,
+            self.readVMDetails(VM_STORE_ENTRIES))
 
         device = []
         for c in controllerClasses:
@@ -437,10 +482,18 @@
             defaultInfo('on_crash',     lambda: "restart")
             defaultInfo('cpu',          lambda: None)
             defaultInfo('cpu_weight',   lambda: 1.0)
-            defaultInfo('vcpus',        lambda: int(1))
-
-            self.info['vcpus'] = int(self.info['vcpus'])
-
+
+            # some domains don't have a config file (e.g. dom0 )
+            # to set number of vcpus so we derive available cpus
+            # from max_vcpu_id which is present for running domains.
+            if not self.infoIsSet('vcpus') and self.infoIsSet('max_vcpu_id'):
+                avail = int(self.info['max_vcpu_id'])+1
+            else:
+                avail = int(1)
+
+            defaultInfo('vcpus',        lambda: avail)
+            defaultInfo('online_vcpus', lambda: self.info['vcpus'])
+            defaultInfo('max_vcpu_id',  lambda: self.info['vcpus']-1)
             defaultInfo('vcpu_avail',   lambda: (1 << self.info['vcpus']) - 1)
 
             defaultInfo('memory',       lambda: 0)
@@ -528,23 +581,24 @@
 
         self.introduceDomain()
         self.storeDomDetails()
+        self.registerWatch()
         self.refreshShutdown()
 
         log.debug("XendDomainInfo.completeRestore done")
 
 
     def storeVmDetails(self):
-        to_store = {
-            'uuid':               self.info['uuid']
-            }
+        to_store = {}
+
+        for k in VM_STORE_ENTRIES:
+            if self.infoIsSet(k[0]):
+                to_store[k[0]] = str(self.info[k[0]])
 
         if self.infoIsSet('image'):
             to_store['image'] = sxp.to_string(self.info['image'])
 
-        for k in ['name', 'ssidref', 'memory', 'maxmem', 'on_poweroff',
-                  'on_reboot', 'on_crash', 'vcpus', 'vcpu_avail']:
-            if self.infoIsSet(k):
-                to_store[k] = str(self.info[k])
+        if self.infoIsSet('start_time'):
+            to_store['start_time'] = str(self.info['start_time'])
 
         log.debug("Storing VM details: %s", to_store)
 
@@ -591,13 +645,16 @@
         return result
 
 
-    def setDomid(self, domid):
-        """Set the domain id.
-
-        @param dom: domain id
-        """
-        self.domid = domid
-        self.storeDom("domid", self.domid)
+    ## public:
+
+    def registerWatch(self):
+        """Register a watch on this VM's entries in the store, so that
+        when they are changed externally, we keep up to date.  This should
+        only be called by {@link #create}, {@link #recreate}, or {@link
+        #restore}, once the domain's details have been written, but before the
+        new instance is returned."""
+        self.vmWatch = xswatch(self.vmpath, self.storeChanged)
+
 
     def getDomid(self):
         return self.domid
@@ -927,6 +984,7 @@
         if self.infoIsSet('cpu_time'):
             sxpr.append(['cpu_time', self.info['cpu_time']/1e9])
         sxpr.append(['vcpus', self.info['vcpus']])
+        sxpr.append(['online_vcpus', self.info['online_vcpus']])
             
         if self.infoIsSet('start_time'):
             up_time =  time.time() - self.info['start_time']
@@ -943,16 +1001,13 @@
 
     def getVCPUInfo(self):
         try:
-            def filter_cpumap(map, max):
-                return filter(lambda x: x >= 0, map[0:max])
-
             # We include the domain name and ID, to help xm.
             sxpr = ['domain',
                     ['domid',      self.domid],
                     ['name',       self.info['name']],
-                    ['vcpu_count', self.info['vcpus']]]
-
-            for i in range(0, self.info['vcpus']):
+                    ['vcpu_count', self.info['online_vcpus']]]
+
+            for i in range(0, self.info['max_vcpu_id']+1):
                 info = xc.vcpu_getinfo(self.domid, i)
 
                 sxpr.append(['vcpu',
@@ -962,8 +1017,7 @@
                              ['running',  info['running']],
                              ['cpu_time', info['cpu_time'] / 1e9],
                              ['cpu',      info['cpu']],
-                             ['cpumap',   filter_cpumap(info['cpumap'],
-                                                        self.info['vcpus'])]])
+                             ['cpumap',   info['cpumap']]])
 
             return sxpr
 
@@ -1049,9 +1103,6 @@
                                   self.info['image'],
                                   self.info['device'])
 
-        if self.info['bootloader']:
-            self.image.handleBootloading()
-
         xc.domain_setcpuweight(self.domid, self.info['cpu_weight'])
 
         m = self.image.getDomainMemory(self.info['memory'] * 1024)
@@ -1073,6 +1124,9 @@
         self.introduceDomain()
 
         self.createDevices()
+
+        if self.info['bootloader']:
+            self.image.cleanupBootloading()
 
         self.info['start_time'] = time.time()
 
@@ -1111,6 +1165,13 @@
         """Cleanup VM resources.  Idempotent.  Nothrow guarantee."""
 
         try:
+            try:
+                if self.vmWatch:
+                    self.vmWatch.unwatch()
+                self.vmWatch = None
+            except:
+                log.exception("Unwatching VM path failed.")
+
             self.removeVm()
         except:
             log.exception("Removing VM path failed.")
@@ -1238,6 +1299,7 @@
         False if it is to be destroyed.
         """
 
+        self.configure_bootloader()
         config = self.sxpr()
 
         if self.readVm(RESTART_IN_PROGRESS):
@@ -1340,8 +1402,9 @@
         # FIXME: this assumes the disk is the first device and
         # that we're booting from the first disk
         blcfg = None
+        config = self.sxpr()
         # FIXME: this assumes that we want to use the first disk
-        dev = sxp.child_value(self.config, "device")
+        dev = sxp.child_value(config, "device")
         if dev:
             disk = sxp.child_value(dev, "uname")
             fn = blkdev_uname_to_file(disk)
@@ -1351,7 +1414,7 @@
             msg = "Had a bootloader specified, but can't find disk"
             log.error(msg)
             raise VmError(msg)
-        self.config = sxp.merge(['vm', ['image', blcfg]], self.config)
+        self.info['image'] = sxp.to_string(blcfg)
 
 
     def send_sysrq(self, key):
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xend/XendNode.py
--- a/tools/python/xen/xend/XendNode.py Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/XendNode.py Sat Nov 19 05:16:29 2005
@@ -75,7 +75,7 @@
                 ['xen_minor', xinfo['xen_minor']],
                 ['xen_extra', xinfo['xen_extra']],
                 ['xen_caps',  xinfo['xen_caps']],
-                ['xen_params',xinfo['xen_params']],
+                ['platform_params',xinfo['platform_params']],
                 ['xen_changeset', xinfo['xen_changeset']],
                 ['cc_compiler', xinfo['cc_compiler']],
                 ['cc_compile_by', xinfo['cc_compile_by']],
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xend/image.py
--- a/tools/python/xen/xend/image.py    Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/image.py    Sat Nov 19 05:16:29 2005
@@ -95,7 +95,7 @@
                         ("image/ramdisk", self.ramdisk))
 
 
-    def handleBootloading(self):
+    def cleanupBootloading(self):
         self.unlink(self.kernel)
         self.unlink(self.ramdisk)
 
@@ -258,6 +258,7 @@
             log.debug("args: %s, val: %s" % (a,v))
 
         # Handle disk/network related options
+        mac = None
         for (name, info) in deviceConfig:
             if name == 'vbd':
                uname = sxp.child_value(info, 'uname')
@@ -276,11 +277,21 @@
                ret.append("-%s" % vbddev)
                ret.append("%s" % vbdparam)
             if name == 'vif':
+               type = sxp.child_value(info, 'type')
+               if type != 'ioemu':
+                   continue
+               if mac != None:
+                   continue
                mac = sxp.child_value(info, 'mac')
+               bridge = sxp.child_value(info, 'bridge')
                if mac == None:
                    mac = randomMAC()
+               if bridge == None:
+                   bridge = 'xenbr0'
                ret.append("-macaddr")
                ret.append("%s" % mac)
+               ret.append("-bridge")
+               ret.append("%s" % bridge)
             if name == 'vtpm':
                instance = sxp.child_value(info, 'instance')
                ret.append("-instance")
diff -r e62c54ab862f -r 878a9891b056 
tools/python/xen/xend/server/DevController.py
--- a/tools/python/xen/xend/server/DevController.py     Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/server/DevController.py     Sat Nov 19 05:16:29 2005
@@ -25,9 +25,28 @@
 from xen.xend.xenstore.xstransact import xstransact
 from xen.xend.xenstore.xswatch import xswatch
 
-DEVICE_CREATE_TIMEOUT = 120
+DEVICE_CREATE_TIMEOUT = 5
 HOTPLUG_STATUS_NODE = "hotplug-status"
 HOTPLUG_STATUS_ERROR = "error"
+
+Connected = 1
+Died      = 2
+Error     = 3
+Missing   = 4
+Timeout   = 5
+
+xenbusState = {
+    'Unknown'      : 0,
+    'Initialising' : 1,
+    'InitWait'     : 2,
+    'Initialised'  : 3,
+    'Connected'    : 4,
+    'Closing'      : 5,
+    'Closed'       : 6,
+    }
+
+xenbusState.update(dict(zip(xenbusState.values(), xenbusState.keys())))
+
 
 class DevController:
     """Abstract base class for a device controller.  Device controllers create
@@ -74,18 +93,28 @@
     def waitForDevice(self, devid):
         log.debug("Waiting for %s.", devid)
         
-        status, fn_ret = self.waitForBackend(devid)
-        if status:
+        status = self.waitForBackend(devid)
+
+        if status == Timeout:
             self.destroyDevice(devid)
-            raise VmError( ("Device %s (%s) could not be connected. "
-                            "Hotplug scripts not working") 
-                            % (devid, self.deviceClass))
-
-        elif fn_ret == HOTPLUG_STATUS_ERROR:
+            raise VmError("Device %s (%s) could not be connected. "
+                          "Hotplug scripts not working" %
+                          (devid, self.deviceClass))
+
+        elif status == Error:
             self.destroyDevice(devid)
-            raise VmError( ("Device %s (%s) could not be connected. "
-                            "Backend device not found!") 
-                            % (devid, self.deviceClass))
+            raise VmError("Device %s (%s) could not be connected. "
+                          "Backend device not found" %
+                          (devid, self.deviceClass))
+
+        elif status == Missing:
+            raise VmError("Device %s (%s) could not be connected. "
+                          "Device not found" % (devid, self.deviceClass))
+
+        elif status == Died:
+            self.destroyDevice(devid)
+            raise VmError("Device %s (%s) could not be connected. "
+                          "Device has died" % (devid, self.deviceClass))
 
 
     def reconfigureDevice(self, devid, config):
@@ -116,10 +145,8 @@
         frontpath = self.frontendPath(devid)
         backpath = xstransact.Read(frontpath, "backend")
 
-        xstransact.Remove(frontpath)
-
         if backpath:
-            xstransact.Remove(backpath)
+            xstransact.Write(backpath, 'state', str(xenbusState['Closing']))
         else:
             raise VmError("Device %s not connected" % devid)
            
@@ -257,18 +284,18 @@
         frontpath = self.frontendPath(devid)
         backpath  = self.backendPath(backdom, devid)
         
-        xstransact.Remove(backpath, HOTPLUG_STATUS_NODE)
-
         frontDetails.update({
             'backend' : backpath,
-            'backend-id' : "%i" % backdom.getDomid()
+            'backend-id' : "%i" % backdom.getDomid(),
+            'state' : str(xenbusState['Initialising'])
             })
 
 
         backDetails.update({
             'domain' : self.vm.getName(),
             'frontend' : frontpath,
-            'frontend-id' : "%i" % self.vm.getDomid()
+            'frontend-id' : "%i" % self.vm.getDomid(),
+            'state' : str(xenbusState['Initialising'])
             })
 
         log.debug('DevController: writing %s to %s.', str(frontDetails),
@@ -276,36 +303,37 @@
         log.debug('DevController: writing %s to %s.', str(backDetails),
                   backpath)
 
-        xstransact.Write(frontpath, frontDetails)
-        xstransact.Write(backpath, backDetails)
-
-    def waitForBackend(self,devid):
-        ev = Event()
-
-        def hotplugStatus():
+        while True:
+            t = xstransact()
             try:
-                status = self.readBackend(devid, HOTPLUG_STATUS_NODE)
-            except VmError:
-                status = "died"
-            if status is not None:
-                watch.xs.unwatch(backpath, watch)
-                hotplugStatus.value = status
-                ev.set()
-
-        hotplugStatus.value = None
+                t.remove2(backpath, HOTPLUG_STATUS_NODE)
+
+                t.write2(frontpath, frontDetails)
+                t.write2(backpath,  backDetails)
+
+                if t.commit():
+                    return
+            except:
+                t.abort()
+                raise
+
+
+    def waitForBackend(self, devid):
+
         frontpath = self.frontendPath(devid)
         backpath = xstransact.Read(frontpath, "backend")
 
         if backpath:
-            watch = xswatch(backpath, hotplugStatus)
+            statusPath = backpath + '/' + HOTPLUG_STATUS_NODE
+            ev = Event()
+            result = { 'status': Timeout }
+            
+            xswatch(statusPath, hotplugStatusCallback, statusPath, ev, result)
 
             ev.wait(DEVICE_CREATE_TIMEOUT)
-            if ev.isSet():
-                return (0, hotplugStatus.value)
-            else:
-                return (-1, hotplugStatus.value)
-        else:
-            return (-1, "missing")
+            return result['status']
+        else:
+            return Missing
 
 
     def backendPath(self, backdom, devid):
@@ -327,3 +355,25 @@
     def frontendMiscPath(self):
         return "%s/device-misc/%s" % (self.vm.getDomainPath(),
                                       self.deviceClass)
+
+
+def hotplugStatusCallback(statusPath, ev, result):
+    log.debug("hotplugStatusCallback %s.", statusPath)
+
+    try:
+        status = xstransact.Read(statusPath)
+
+        if status is not None:
+            if status == HOTPLUG_STATUS_ERROR:
+                result['status'] = Error
+            else:
+                result['status'] = Connected
+        else:
+            return 1
+    except VmError:
+        result['status'] = Died
+
+    log.debug("hotplugStatusCallback %d.", result['status'])
+
+    ev.set()
+    return 0
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xend/server/netif.py
--- a/tools/python/xen/xend/server/netif.py     Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/server/netif.py     Sat Nov 19 05:16:29 2005
@@ -35,16 +35,16 @@
 def randomMAC():
     """Generate a random MAC address.
 
-    Uses OUI (Organizationally Unique Identifier) AA:00:00, an
-    unassigned one that used to belong to DEC. The OUI list is
-    available at 'standards.ieee.org'.
+    Uses OUI (Organizationally Unique Identifier) 00-16-3E, allocated to
+    Xensource, Inc. The OUI list is available at
+    http://standards.ieee.org/regauth/oui/oui.txt.
 
     The remaining 3 fields are random, with the first bit of the first
     random field set 0.
 
     @return: MAC address string
     """
-    mac = [ 0xaa, 0x00, 0x00,
+    mac = [ 0x00, 0x16, 0x3e,
             random.randint(0x00, 0x7f),
             random.randint(0x00, 0xff),
             random.randint(0x00, 0xff) ]
@@ -71,6 +71,9 @@
         script = os.path.join(xroot.network_script_dir,
                               sxp.child_value(config, 'script',
                                               xroot.get_vif_script()))
+        type = sxp.child_value(config, 'type')
+        if type == 'ioemu':
+            return (None,{},{})
         bridge = sxp.child_value(config, 'bridge')
         mac    = sxp.child_value(config, 'mac')
         ipaddr = _get_config_ipaddr(config)
diff -r e62c54ab862f -r 878a9891b056 
tools/python/xen/xend/xenstore/xstransact.py
--- a/tools/python/xen/xend/xenstore/xstransact.py      Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/xenstore/xstransact.py      Sat Nov 19 05:16:29 2005
@@ -10,7 +10,7 @@
 
 class xstransact:
 
-    def __init__(self, path):
+    def __init__(self, path = ""):
         assert path is not None
         
         self.in_transaction = False # Set this temporarily -- if this
@@ -41,7 +41,7 @@
         return rc
 
     def _read(self, key):
-        path = "%s/%s" % (self.path, key)
+        path = self.prependPath(key)
         try:
             return xshandle().read(self.transaction, path)
         except RuntimeError, ex:
@@ -66,7 +66,7 @@
         return ret
 
     def _write(self, key, data):
-        path = "%s/%s" % (self.path, key)
+        path = self.prependPath(key)
         try:
             xshandle().write(self.transaction, path, data)
         except RuntimeError, ex:
@@ -99,7 +99,7 @@
             raise TypeError
 
     def _remove(self, key):
-        path = "%s/%s" % (self.path, key)
+        path = self.prependPath(key)
         return xshandle().rm(self.transaction, path)
 
     def remove(self, *args):
@@ -114,7 +114,7 @@
                 self._remove(key)
 
     def _list(self, key):
-        path = "%s/%s" % (self.path, key)
+        path = self.prependPath(key)
         l = xshandle().ls(self.transaction, path)
         if l:
             return map(lambda x: key + "/" + x, l)
@@ -177,18 +177,15 @@
                 (key, fn, defval) = tup
 
             val = self._read(key)
-            # If fn is str, then this will successfully convert None to
-            # 'None'.  If it is int, then it will throw TypeError on None, or
-            # on any other non-integer value.  We have to, therefore, both
-            # check explicitly for None, and catch TypeError.  Either failure
-            # will result in defval being used instead.
+            # If fn is str, then this will successfully convert None to 'None'
+            # (which we don't want).  If it is int or float, then it will
+            # throw ValueError on any non-convertible value.  We check
+            # explicitly for None, using defval instead, but allow ValueError
+            # to propagate.
             if val is None:
                 val = defval
             else:
-                try:
-                    val = fn(val)
-                except TypeError:
-                    val = defval
+                val = fn(val)
             ret.append(val)
         if len(ret) == 1:
             return ret[0]
@@ -215,6 +212,30 @@
                 self._write(key, fmt % val)
 
 
+    def remove2(self, middlePath, *args):
+        self.callRebased(middlePath, self.remove, *args)
+
+
+    def write2(self, middlePath, *args):
+        self.callRebased(middlePath, self.write, *args)
+
+
+    def callRebased(self, middlePath, func, *args):
+        oldpath = self.path
+        self.path = self.prependPath(middlePath)
+        try:
+            func(*args)
+        finally:
+            self.path = oldpath
+
+
+    def prependPath(self, key):
+        if self.path:
+            return self.path + '/' + key
+        else:
+            return key
+
+
     def Read(cls, path, *args):
         """If only one argument is given (path), return the value stored at
         that path.  If two arguments are given, treat the second argument as a
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xend/xenstore/xswatch.py
--- a/tools/python/xen/xend/xenstore/xswatch.py Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xend/xenstore/xswatch.py Sat Nov 19 05:16:29 2005
@@ -5,9 +5,7 @@
 # Public License.  See the file "COPYING" in the main directory of
 # this archive for more details.
 
-import select
 import threading
-from xen.lowlevel import xs
 from xen.xend.xenstore.xsutil import xshandle
 
 from xen.xend.XendLogging import log
@@ -15,42 +13,49 @@
 
 class xswatch:
 
-    watchThread = None
-    xs = None
-    xslock = threading.Lock()
-    
     def __init__(self, path, fn, *args, **kwargs):
+        self.path = path
         self.fn = fn
         self.args = args
         self.kwargs = kwargs
-        xswatch.watchStart()
-        xswatch.xs.watch(path, self)
-
-    def watchStart(cls):
-        cls.xslock.acquire()
-        if cls.watchThread:
-            cls.xslock.release()
-            return
-        cls.xs = xshandle()
-        cls.watchThread = threading.Thread(name="Watcher",
-                                           target=cls.watchMain)
-        cls.watchThread.setDaemon(True)
-        cls.watchThread.start()
-        cls.xslock.release()
-
-    watchStart = classmethod(watchStart)
-
-    def watchMain(cls):
-        while True:
-            try:
-                we = cls.xs.read_watch()
-                watch = we[1]
-                watch.fn(*watch.args, **watch.kwargs)
-            except:
-                log.exception("read_watch failed")
-                # Ignore this exception -- there's no point throwing it
-                # further on because that will just kill the watcher thread,
-                # which achieves nothing.
+        watchStart()
+        xs.watch(path, self)
 
 
-    watchMain = classmethod(watchMain)
+    def unwatch(self):
+        xs.unwatch(self.path, self)
+
+
+watchThread = None
+xs = None
+xslock = threading.Lock()
+
+def watchStart():
+    global watchThread
+    global xs
+    
+    xslock.acquire()
+    try:
+        if watchThread:
+            return
+        xs = xshandle()
+        watchThread = threading.Thread(name="Watcher", target=watchMain)
+        watchThread.setDaemon(True)
+        watchThread.start()
+    finally:
+        xslock.release()
+
+
+def watchMain():
+    while True:
+        try:
+            we = xs.read_watch()
+            watch = we[1]
+            res = watch.fn(*watch.args, **watch.kwargs)
+            if not res:
+                watch.unwatch()
+        except:
+            log.exception("read_watch failed")
+            # Ignore this exception -- there's no point throwing it
+            # further on because that will just kill the watcher thread,
+            # which achieves nothing.
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xm/create.py
--- a/tools/python/xen/xm/create.py     Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xm/create.py     Sat Nov 19 05:16:29 2005
@@ -255,10 +255,11 @@
           fn=append_value, default=[],
           use="Add an IP address to the domain.")
 
-gopts.var('vif', 
val="mac=MAC,be_mac=MAC,bridge=BRIDGE,script=SCRIPT,backend=DOM,vifname=NAME",
+gopts.var('vif', 
val="type=TYPE,mac=MAC,be_mac=MAC,bridge=BRIDGE,script=SCRIPT,backend=DOM,vifname=NAME",
           fn=append_value, default=[],
           use="""Add a network interface with the given MAC address and bridge.
           The vif is configured by calling the given configuration script.
+          If type is not specified, default is netfront not ioemu device.
           If mac is not specified a random MAC address is used.
           The MAC address of the backend interface can be selected with be_mac.
           If not specified then the network backend chooses it's own MAC 
address.
@@ -355,10 +356,6 @@
 gopts.var('cdrom', val='FILE',
           fn=set_value, default='',
           use="Path to cdrom")
-
-gopts.var('macaddr', val='MACADDR',
-          fn=set_value, default='',
-          use="Macaddress of the first network interface")
 
 gopts.var('boot', val="a|b|c|d",
           fn=set_value, default='c',
@@ -512,6 +509,7 @@
             backend = d.get('backend')
             ip = d.get('ip')
             vifname = d.get('vifname')
+            type = d.get('type')
         else:
             mac = None
             be_mac = None
@@ -520,6 +518,7 @@
             backend = None
             ip = None
             vifname = None
+            type = None
         config_vif = ['vif']
         if mac:
             config_vif.append(['mac', mac])
@@ -535,6 +534,8 @@
             config_vif.append(['backend', backend])
         if ip:
             config_vif.append(['ip', ip])
+        if type:
+            config_vif.append(['type', type])
         config_devs.append(['device', config_vif])
 
 def configure_vfr(config, vals):
@@ -549,7 +550,7 @@
     """Create the config for VMX devices.
     """
     args = [ 'device_model', 'vcpus', 'cdrom', 'boot', 'fda', 'fdb',
-             'localtime', 'serial', 'macaddr', 'stdvga', 'isa', 'nographic',
+             'localtime', 'serial', 'stdvga', 'isa', 'nographic',
              'vnc', 'vncviewer', 'sdl', 'display', 'ne2000', 'lapic']
     for a in args:
         if (vals.__dict__[a]):
@@ -564,7 +565,7 @@
     file = blkif.blkdev_uname_to_file(uname)
 
     return bootloader(vals.bootloader, file, not vals.console_autoconnect,
-                      vals.vcpus, vals.blentry)
+                      vals.vcpus, vals.bootentry)
 
 def make_config(vals):
     """Create the domain configuration.
@@ -662,7 +663,7 @@
             (k, v) = b.strip().split('=', 1)
             k = k.strip()
             v = v.strip()
-            if k not in ['mac', 'be_mac', 'bridge', 'script', 'backend', 'ip', 
'vifname']:
+            if k not in ['type', 'mac', 'be_mac', 'bridge', 'script', 
'backend', 'ip', 'vifname']:
                 err('Invalid vif specifier: ' + vif)
             d[k] = v
         vifs.append(d)
@@ -780,7 +781,7 @@
         vals.extra = vnc + ' ' + vals.extra
     
 def preprocess(vals):
-    if not vals.kernel:
+    if not vals.kernel and not vals.bootloader:
         err("No kernel specified")
     preprocess_disk(vals)
     preprocess_pci(vals)
@@ -904,6 +905,9 @@
             opts.setopt('name', os.path.basename(opts.getopt('defconfig')))
         config = make_config(opts.vals)
 
+    if type(config) == str:
+        config = sxp.parse(file(config))[0]
+
     return (opts, config)
 
 
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xm/main.py
--- a/tools/python/xen/xm/main.py       Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xm/main.py       Sat Nov 19 05:16:29 2005
@@ -40,26 +40,81 @@
 
 import console
 
+# Strings for shorthelp
+console_help = "console <DomId>                  Attach to domain DomId's 
console."
+create_help =  """create [-c] <ConfigFile>
+               [Name=Value]..       Create a domain based on Config File"""
+destroy_help = "destroy <DomId>                  Terminate a domain 
immediately"
+help_help =    "help                             Display this message"
+list_help =    "list [--long] [DomId, ...]       List information about 
domains"
+mem_max_help = "mem-max <DomId> <Mem>            Set maximum memory 
reservation for a domain"
+mem_set_help = "mem-set <DomId> <Mem>            Adjust the current memory 
usage for a domain"
+migrate_help = "migrate <DomId> <Host>           Migrate a domain to another 
machine"
+pause_help =   "pause <DomId>                    Pause execution of a domain"
+reboot_help =  "reboot <DomId> [-w][-a]          Reboot a domain"
+restore_help = "restore <File>                   Create a domain from a saved 
state file"
+save_help =    "save <DomId> <File>              Save domain state (and 
config) to file"
+shutdown_help ="shutdown <DomId> [-w][-a][-R|-H] Shutdown a domain"
+top_help =     "top                              Monitor system and domains in 
real-time"
+unpause_help = "unpause <DomId>                  Unpause a paused domain"
+
+help_spacer = """
+   """
+
+# Strings for longhelp
+sysrq_help =   "sysrq   <DomId> <letter>         Send a sysrq to a domain"
+domid_help =   "domid <DomName>                  Converts a domain name to a 
domain id"
+domname_help = "domname <DomId>                  Convert a domain id to a 
domain name"
+set_vcpus_help = """set-vcpus <DomId> <VCPUs>        Enable the specified 
number of VCPUs in a
+                                    domain"""
+vcpu_list_help = "vcpu-list <DomId>                List the VCPUs for a domain 
(or all domains)"
+vcpu_pin_help = "vcpu-pin <DomId> <VCPU> <CPUs>   Set which cpus a VCPU can 
use" 
+dmesg_help =   "dmesg [--clear]                  Read or clear Xen's message 
buffer"
+info_help =    "info                             Get information about the xen 
host"
+log_help = "log      Print the xend log"
+sched_bvt_help = """sched-bvt <Parameters>           Set Borrowed Virtual Time 
scheduler
+                                    parameters"""
+sched_bvt_ctxallow_help = """sched-bvt-ctxallow <Allow>       Set the BVT 
scheduler context switch
+                                    allowance"""
+sched_sedf_help = "sched-sedf <Parameters>          Set simple EDF parameters"
+block_attach_help = """block-attach <DomId> <BackDev> <FrontDev> <Mode>
+                [BackDomId]         Create a new virtual block device"""
+block_detach_help = """block-detach  <DomId> <DevId>    Destroy a domain's 
virtual block device,
+                                    where <DevId> may either be the device ID
+                                    or the device name as mounted in the 
guest"""
+
+block_list_help = "block-list <DomId>               List virtual block devices 
for a domain"
+network_attach_help = """network-attach  <DomID> [script=<script>] [ip=<ip>] 
[mac=<mac>]
+                           [bridge=<bridge>] [backend=<backDomID>]
+                                    Create a new virtual network device """
+network_detach_help = """network-detach  <DomId> <DevId>  Destroy a domain's 
virtual network
+                                    device, where <DevId> is the device ID."""
+
+network_list_help = "network-list <DomId>             List virtual network 
interfaces for a domain"
+vnet_list_help = "vnet-list [-l|--long]            list vnets"
+vnet_create_help = "vnet-create <config>             create a vnet from a 
config file"
+vnet_delete_help = "vnet-delete <vnetid>             delete a vnet"
+
 
 shorthelp = """Usage: xm <subcommand> [args]
     Control, list, and manipulate Xen guest instances
 
-xm common subcommands:
-    console <DomId>         attach to console of DomId
-    create <CfgFile>        create a domain based on Config File
-    destroy <DomId>         terminate a domain immediately
-    help                    display this message
-    list [DomId, ...]       list information about domains
-    mem-max <DomId> <Mem>   set the maximum memory reservation for a domain
-    mem-set <DomId> <Mem>   adjust the current memory usage for a domain
-    migrate <DomId> <Host>  migrate a domain to another machine
-    pause <DomId>           pause execution of a domain
-    reboot <DomId>          reboot a domain
-    restore <File>          create a domain from a saved state file
-    save <DomId> <File>     save domain state (and config) to file
-    shutdown <DomId>        shutdown a domain
-    top                     monitor system and domains in real-time
-    unpause <DomId>         unpause a paused domain
+xm common subcommands:"""  + help_spacer \
++ console_help + help_spacer \
++ create_help + help_spacer \
++ destroy_help + help_spacer \
++ help_help    + help_spacer \
++ list_help    + help_spacer \
++ mem_max_help + help_spacer \
++ mem_set_help + help_spacer \
++ migrate_help + help_spacer \
++ pause_help   + help_spacer \
++ reboot_help  + help_spacer \
++ restore_help + help_spacer \
++ save_help    + help_spacer \
++ shutdown_help + help_spacer \
++ top_help     + help_spacer \
++ unpause_help + """
 
 <DomName> can be substituted for <DomId> in xm subcommands.
 
@@ -72,66 +127,101 @@
 
 xm full list of subcommands:
 
-  Domain Commands:
-    console <DomId>           attach to console of DomId
-    create  <ConfigFile>      create a domain
-    destroy <DomId>           terminate a domain immediately
-    domid   <DomName>         convert a domain name to a domain id
-    domname <DomId>           convert a domain id to a domain name
-    list                      list information about domains
-    mem-max <DomId> <Mem>     set domain maximum memory limit
-    mem-set <DomId> <Mem>     set the domain's memory dynamically
-    migrate <DomId> <Host>    migrate a domain to another machine
-    pause   <DomId>           pause execution of a domain
-    reboot   [-w|-a] <DomId>  reboot a domain
-    restore <File>            create a domain from a saved state file
-    save    <DomId> <File>    save domain state (and config) to file
-    shutdown [-w|-a] <DomId>  shutdown a domain
-    sysrq   <DomId> <letter>  send a sysrq to a domain
-    unpause <DomId>           unpause a paused domain
-    set-vcpus <DomId> <VCPUs> enable the specified number of VCPUs in a domain
-    vcpu-list <DomId>         list the VCPUs for a domain
-    vcpu-pin <DomId> <VCPU> <CPUs>    set which cpus a VCPU can use. 
-
-  Xen Host Commands:
-    dmesg   [--clear]         read or clear Xen's message buffer
-    info                      get information about the xen host
-    log                       print the xend log
-    top                       monitor system and domains in real-time
-
-  Scheduler Commands:
-    sched-bvt <options>       set BVT scheduler parameters
-    sched-bvt-ctxallow <Allow>
-        Set the BVT scheduler context switch allowance
-    sched-sedf <options>      set simple EDF parameters
-
-  Virtual Device Commands:
-    block-attach  <DomId> <BackDev> <FrontDev> <Mode> [BackDomId]
-        Create a new virtual block device 
-    block-detach  <DomId> <DevId>  Destroy a domain's virtual block device,
-                                   where <DevId> may either be the device ID
-                                   or the device name as mounted in the guest.
-    block-list    <DomId>          List virtual block devices for a domain
-
-    network-attach  <DomID> [script=<script>] [ip=<ip>] [mac=<mac>]
-                            [bridge=<bridge>] [backend=<backDomID>]
-        Create a new virtual network device 
-    network-detach  <DomId> <DevId>  Destroy a domain's virtual network
-                                     device, where <DevId> is the device ID.
-    network-limit   <DomId> <Vif> <Credit> <Period>
-        Limit the transmission rate of a virtual network interface
-    network-list    <DomId>        List virtual network interfaces for a domain
-
-  Vnet commands:
-    vnet-list   [-l|--long]    list vnets
-    vnet-create <config>       create a vnet from a config file
-    vnet-delete <vnetid>       delete a vnet
+  Domain Commands: """ + help_spacer \
++ console_help + help_spacer \
++ create_help + help_spacer \
++ destroy_help + help_spacer \
++ domid_help   + help_spacer \
++ domname_help   + help_spacer \
++ list_help    + help_spacer \
++ mem_max_help + help_spacer \
++ mem_set_help + help_spacer \
++ migrate_help + help_spacer \
++ pause_help   + help_spacer \
++ reboot_help  + help_spacer \
++ restore_help + help_spacer \
++ save_help    + help_spacer \
++ shutdown_help + help_spacer \
++ sysrq_help + help_spacer \
++ top_help     + help_spacer \
++ unpause_help + help_spacer \
++ set_vcpus_help + help_spacer \
++ vcpu_pin_help + """
+
+   Xen Host Commands: """ + help_spacer \
++ dmesg_help + help_spacer \
++ info_help + help_spacer \
++ log_help  + help_spacer \
++ top_help  + """
+
+  Scheduler Commands: """ + help_spacer \
++ sched_bvt_help + help_spacer \
++ sched_bvt_ctxallow_help + help_spacer \
++ sched_sedf_help + """
+
+  Virtual Device Commands:"""  + help_spacer \
++ block_attach_help + help_spacer \
++ block_detach_help + help_spacer \
++ block_list_help + help_spacer \
++ network_attach_help + help_spacer \
++ network_detach_help + help_spacer \
++ network_list_help + """
+
+  Vnet commands: """ + help_spacer \
++ vnet_list_help + help_spacer \
++ vnet_create_help + help_spacer \
++ vnet_delete_help + """
 
 <DomName> can be substituted for <DomId> in xm subcommands.
 
 For a short list of subcommands run 'xm help'
 For more help on xm see the xm(1) man page
 For more help on xm create, see the xmdomain.cfg(5) man page"""
+
+# array for xm help <command>
+help = {
+    "--long": longhelp,
+    "console": console_help,
+    "create": create_help,
+    "destroy": destroy_help,
+    "domid ": domid_help,
+    "domname": domname_help,
+    "list": list_help,
+    "mem-max": mem_max_help,
+    "mem-set": mem_set_help,
+    "migrate": migrate_help,
+    "pause": pause_help,
+    "reboot": reboot_help,
+    "restore": restore_help,
+    "save":  save_help,
+    "shutdown": shutdown_help,
+    "sysrq": sysrq_help,
+    "unpause": unpause_help,
+    "set-vcpus": set_vcpus_help,
+    "vcpu-list": vcpu_list_help,
+    "vcpu-pin": vcpu_pin_help,
+#  Xen Host Commands:
+    "dmesg": dmesg_help,
+    "info":  info_help,
+    "log":   log_help,
+    "top":  top_help,
+#  Scheduler Commands:
+    "sched-bvt": sched_bvt_help,
+    "sched-bvt-ctxallow": sched_bvt_ctxallow_help,
+    "sched-sedf":  sched_sedf_help,
+
+#  Virtual Device Commands:
+    "block-attach": block_attach_help,
+    "block-detach": block_detach_help,
+    "block-list": block_list_help,
+    "network-attach": network_attach_help,
+    "network-detach": network_detach_help,
+    "network-list":  network_list_help,
+# Vnet commands:
+    "vnet-list": vnet_list_help,
+    "vnet-create": vnet_create_help,
+    "vnet-delete": vnet_delete_help
+   }
 
 ####################################################################
 #
@@ -260,13 +350,13 @@
         return t(sxp.child_value(info, n, d))
     
     return {
-        'dom'      : get_info('domid',    int,   -1),
-        'name'     : get_info('name',     str,   '??'),
-        'mem'      : get_info('memory',   int,   0),
-        'vcpus'    : get_info('vcpus',    int,   0),
-        'state'    : get_info('state',    str,   '??'),
-        'cpu_time' : get_info('cpu_time', float, 0),
-        'ssidref'  : get_info('ssidref',  int,   0),
+        'dom'      : get_info('domid',        int,   -1),
+        'name'     : get_info('name',         str,   '??'),
+        'mem'      : get_info('memory',       int,   0),
+        'vcpus'    : get_info('online_vcpus', int,   0),
+        'state'    : get_info('state',        str,   '??'),
+        'cpu_time' : get_info('cpu_time',     float, 0),
+        'ssidref'  : get_info('ssidref',      int,   0),
         }
 
 
@@ -556,13 +646,6 @@
 def xm_log(args):
     from xen.xend.XendClient import server
     print server.xend_node_log()
-
-def xm_network_limit(args):
-    arg_check(args,4,"network-limit")
-    dom = args[0]
-    v = map(int, args[1:4])
-    from xen.xend.XendClient import server
-    server.xend_domain_vif_limit(dom, *v)
 
 def xm_network_list(args):
     arg_check(args,1,"network-list")
@@ -716,7 +799,6 @@
     # network
     "network-attach": xm_network_attach,
     "network-detach": xm_network_detach,
-    "network-limit": xm_network_limit,
     "network-list": xm_network_list,
     # vnet
     "vnet-list": xm_vnet_list,
@@ -739,15 +821,10 @@
 aliases = {
     "balloon": "mem-set",
     "vif-list": "network-list",
-    "vif-limit": "network-limit",
     "vbd-create": "block-create",
     "vbd-destroy": "block-destroy",
     "vbd-list": "block-list",
     }
-
-help = {
-    "--long": longhelp
-   }
 
 
 def xm_lookup_cmd(cmd):
@@ -770,7 +847,7 @@
 
 def usage(cmd=None):
     if help.has_key(cmd):
-        print help[cmd]
+        print "   " + help[cmd]
     else:
         print shorthelp
     sys.exit(1)
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xm/shutdown.py
--- a/tools/python/xen/xm/shutdown.py   Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xm/shutdown.py   Sat Nov 19 05:16:29 2005
@@ -22,9 +22,9 @@
 import time
 
 from xen.xend.XendClient import server
+from xen.xend import sxp
 from xen.xm.opts import *
 
-DOM0_NAME = 'Domain-0'
 DOM0_ID = '0'
 
 gopts = Opts(use="""[options] [DOM]
@@ -54,7 +54,8 @@
 
 def shutdown(opts, doms, mode, wait):
     if doms == None: doms = server.xend_domains()
-    for x in [DOM0_NAME, DOM0_ID]:
+    dom0_name = sxp.child_value(server.xend_domain(0), 'name')
+    for x in [dom0_name, DOM0_ID]:
         if x in doms:
             doms.remove(x)
     for d in doms:
diff -r e62c54ab862f -r 878a9891b056 tools/vtpm_manager/manager/securestorage.c
--- a/tools/vtpm_manager/manager/securestorage.c        Sat Nov 19 05:06:09 2005
+++ b/tools/vtpm_manager/manager/securestorage.c        Sat Nov 19 05:16:29 2005
@@ -393,8 +393,7 @@
   vtpmlogerror(VTPM_LOG_VTPM, "Failed to load service data with error = %s\n", 
tpm_get_error_name(status));
  egress:
   
-  if (flat_global)
-    free(flat_global);
+  free(flat_global);
   close(fh);
   
   return status;
diff -r e62c54ab862f -r 878a9891b056 tools/vtpm_manager/util/bsg.c
--- a/tools/vtpm_manager/util/bsg.c     Sat Nov 19 05:06:09 2005
+++ b/tools/vtpm_manager/util/bsg.c     Sat Nov 19 05:16:29 2005
@@ -616,8 +616,7 @@
   else if (format == __FMT_SIZE || format == __FMT_HSIZE) {
     s += size;
     BSG_BYTE* ptr = *(BSG_BYTE**) s;
-    if (ptr)
-      free(ptr);
+    free(ptr);
     s += sizeof(void*);
   } else if (format == __FMT_PACKED) {
 
diff -r e62c54ab862f -r 878a9891b056 tools/xenstat/libxenstat/src/xenstat.c
--- a/tools/xenstat/libxenstat/src/xenstat.c    Sat Nov 19 05:06:09 2005
+++ b/tools/xenstat/libxenstat/src/xenstat.c    Sat Nov 19 05:16:29 2005
@@ -284,10 +284,8 @@
 
        if (node) {
                if (node->domains) {
-                       for (i = 0; i < node->num_domains; i++) {
-                               if (node->domains[i].name)
-                                       free(node->domains[i].name);
-                       }
+                       for (i = 0; i < node->num_domains; i++)
+                               free(node->domains[i].name);
 
                        for (i = 0; i < NUM_COLLECTORS; i++)
                                if((node->flags & collectors[i].flag)
diff -r e62c54ab862f -r 878a9891b056 tools/xenstore/tdb.c
--- a/tools/xenstore/tdb.c      Sat Nov 19 05:06:09 2005
+++ b/tools/xenstore/tdb.c      Sat Nov 19 05:16:29 2005
@@ -45,7 +45,7 @@
 #include "tdb.h"
 #include <stdarg.h>
 #include "talloc.h"
-#define HAVE_MMAP
+#undef HAVE_MMAP
 #else
 #include "includes.h"
 #include "lib/tdb/include/tdb.h"
diff -r e62c54ab862f -r 878a9891b056 tools/xenstore/xenstored_core.c
--- a/tools/xenstore/xenstored_core.c   Sat Nov 19 05:06:09 2005
+++ b/tools/xenstore/xenstored_core.c   Sat Nov 19 05:16:29 2005
@@ -56,6 +56,7 @@
 static bool verbose;
 LIST_HEAD(connections);
 static int tracefd = -1;
+static int reopen_log_pipe[2];
 static char *tracefile = NULL;
 static TDB_CONTEXT *tdb_ctx;
 
@@ -243,20 +244,34 @@
        talloc_free(str);
 }
 
-void reopen_log()
-{
-       if (!tracefile)
-               return;
-
-       if (tracefd > 0)
-               close(tracefd);
-       tracefd = open(tracefile, O_WRONLY|O_CREAT|O_APPEND, 0600);
-       if (tracefd < 0) {
-               perror("Could not open tracefile");
-               return;
-       }
-       write(tracefd, "\n***\n", strlen("\n***\n"));
-}
+
+/**
+ * Signal handler for SIGHUP, which requests that the trace log is reopened
+ * (in the main loop).  A single byte is written to reopen_log_pipe, to awaken
+ * the select() in the main loop.
+ */
+static void trigger_reopen_log(int signal __attribute__((unused)))
+{
+       char c = 'A';
+       write(reopen_log_pipe[1], &c, 1);
+}
+
+
+static void reopen_log()
+{
+       if (tracefile) {
+               if (tracefd > 0)
+                       close(tracefd);
+
+               tracefd = open(tracefile, O_WRONLY|O_CREAT|O_APPEND, 0600);
+
+               if (tracefd < 0)
+                       perror("Could not open tracefile");
+               else
+                       write(tracefd, "\n***\n", strlen("\n***\n"));
+       }
+}
+
 
 static bool write_messages(struct connection *conn)
 {
@@ -331,29 +346,33 @@
        return 0;
 }
 
+
+static void set_fd(int fd, fd_set *set, int *max)
+{
+       FD_SET(fd, set);
+       if (fd > *max)
+               *max = fd;
+}
+
+
 static int initialize_set(fd_set *inset, fd_set *outset, int sock, int ro_sock)
 {
        struct connection *i;
-       int max;
+       int max = -1;
 
        FD_ZERO(inset);
        FD_ZERO(outset);
-       FD_SET(sock, inset);
-       max = sock;
-       FD_SET(ro_sock, inset);
-       if (ro_sock > max)
-               max = ro_sock;
-       FD_SET(eventchn_fd, inset);
-       if (eventchn_fd > max)
-               max = eventchn_fd;
+
+       set_fd(sock,               inset, &max);
+       set_fd(ro_sock,            inset, &max);
+       set_fd(eventchn_fd,        inset, &max);
+       set_fd(reopen_log_pipe[0], inset, &max);
        list_for_each_entry(i, &connections, list) {
                if (i->domain)
                        continue;
-               FD_SET(i->fd, inset);
+               set_fd(i->fd, inset, &max);
                if (!list_empty(&i->out_list))
                        FD_SET(i->fd, outset);
-               if (i->fd > max)
-                       max = i->fd;
        }
        return max;
 }
@@ -1391,8 +1410,6 @@
                barf_perror("Could not create initial node %s", name);
        talloc_free(node);
 }
-
-#
 
 static void setup_structure(void)
 {
@@ -1570,6 +1587,10 @@
            || listen(*ro_sock, 1) != 0)
                barf_perror("Could not listen on sockets");
 
+       if (pipe(reopen_log_pipe)) {
+               barf_perror("pipe");
+       }
+
        /* Setup the database */
        setup_structure();
 
@@ -1592,7 +1613,7 @@
                close(STDERR_FILENO);
        }
 
-       signal(SIGHUP, reopen_log);
+       signal(SIGHUP, trigger_reopen_log);
 
 #ifdef TESTING
        signal(SIGUSR1, stop_failtest);
@@ -1610,6 +1631,12 @@
                        if (errno == EINTR)
                                continue;
                        barf_perror("Select failed");
+               }
+
+               if (FD_ISSET(reopen_log_pipe[0], &inset)) {
+                       char c;
+                       read(reopen_log_pipe[0], &c, 1);
+                       reopen_log();
                }
 
                if (FD_ISSET(*sock, &inset))
diff -r e62c54ab862f -r 878a9891b056 tools/xenstore/xs.c
--- a/tools/xenstore/xs.c       Sat Nov 19 05:06:09 2005
+++ b/tools/xenstore/xs.c       Sat Nov 19 05:16:29 2005
@@ -305,6 +305,7 @@
        struct sigaction ignorepipe, oldact;
 
        msg.tx_id = (uint32_t)(unsigned long)t;
+       msg.req_id = 0;
        msg.type = type;
        msg.len = 0;
        for (i = 0; i < num_vecs; i++)
diff -r e62c54ab862f -r 878a9891b056 tools/xentrace/setsize.c
--- a/tools/xentrace/setsize.c  Sat Nov 19 05:06:09 2005
+++ b/tools/xentrace/setsize.c  Sat Nov 19 05:16:29 2005
@@ -9,9 +9,9 @@
   int xc_handle = xc_interface_open();
   
   if (xc_tbuf_get_size(xc_handle, &size) != 0) {
-    perror("Failure to get tbuf info from Xen. Guess size is 0.");
-    printf("This may mean that tracing is not compiled into xen.\n");
-    exit(1);
+    perror("Failure to get tbuf info from Xen. Guess size is 0");
+    printf("This may mean that tracing is not enabled in xen.\n");
+    //    exit(1);
   }
   else
     printf("Current tbuf size: 0x%x\n", size);
@@ -25,9 +25,10 @@
     perror("set_size Hypercall failure");
     exit(1);
   }
+  printf("set_size succeeded.\n");
   
   if (xc_tbuf_get_size(xc_handle, &size) != 0)
-    perror("Failure to get tbuf info from Xen. Guess size is 0.");
+    perror("Failure to get tbuf info from Xen. Tracing must be enabled first");
   else
     printf("New tbuf size: 0x%x\n", size);
   
diff -r e62c54ab862f -r 878a9891b056 tools/xentrace/xentrace_format
--- a/tools/xentrace/xentrace_format    Sat Nov 19 05:06:09 2005
+++ b/tools/xentrace/xentrace_format    Sat Nov 19 05:16:29 2005
@@ -85,7 +85,9 @@
 
 # structure of trace record + prepended CPU id (as output by xentrace):
 # CPU(I) TSC(Q) EVENT(L) D1(L) D2(L) D3(L) D4(L) D5(L)
-TRCREC = "IQLLLLLL"
+# read CPU id separately to avoid structure packing problems on 64-bit arch.
+CPUREC = "I"
+TRCREC = "QLLLLLL"
 
 last_tsc = [0,0,0,0,0,0,0,0]
 
@@ -94,11 +96,16 @@
 while not interrupted:
     try:
        i=i+1
+        line = sys.stdin.read(struct.calcsize(CPUREC))
+        if not line:
+            break
+        cpu = struct.unpack(CPUREC, line)[0]
+
         line = sys.stdin.read(struct.calcsize(TRCREC))
         if not line:
             break
 
-        (cpu, tsc, event, d1, d2, d3, d4, d5) = struct.unpack(TRCREC, line)
+        (tsc, event, d1, d2, d3, d4, d5) = struct.unpack(TRCREC, line)
 
        #tsc = (tscH<<32) | tscL
 
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/Makefile.am
--- a/tools/xm-test/Makefile.am Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/Makefile.am Sat Nov 19 05:16:29 2005
@@ -1,5 +1,8 @@
 SUBDIRS = ramdisk tests
 EXTRA_DIST = lib runtest.sh mkreport
+
+existing:
+       $(MAKE) -C ramdisk existing
 
 # Remove any pyc's, CVS dirs, and prune the skel dirs
 dist-hook:
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/README
--- a/tools/xm-test/README      Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/README      Sat Nov 19 05:16:29 2005
@@ -38,26 +38,64 @@
 downloaded, extracted, and compiled.  Due to the need to create
 special files, this process must be done as root:
 
+   # ./autogen
    # ./configure
    # make
 
-NB: If you have the initrd.img from a previous version of xm-test, you
-can copy it into the ramdisk directory to eliminate the need to
-rebuild it.  So far, nothing has changed in the ramdisk since xm-test
-version 0.1.1.  If you do this, there is no need to run 'make' again.
-Simply copy the initrd.img file into ramdisk/ and then run the
-runtest.sh script.
+NB: If you have the initrd.img from another installation of xm-test,
+you can copy it into the ramdisk directory to eliminate the need to
+rebuild it.  If you do this, there is no need to run 'make' again.
+Simply copy the initrd-X.Y.img file into ramdisk/ and then run:
+
+   # make existing
+
+This will set up the link so that xm-test will use the existing
+ramdisk.  Next, just run "runtest.sh" normally.  Note that in general,
+you should not attempt to use a ramdisk from a previous minor version
+of xm-test (i.e., don't use a ramdisk from 0.4.0 with 0.5.0.  0.5.0
+should work for 0.5.3 though)
 
 
 Running
 =======
 
-By running "./runtest.sh logfile" at the top level, all tests will be
-run in alphabetic order.  To run a specific test group, run "make
-check" from inside that group directory.  For example:
+To run the full test suite, do the following as root:
+
+   # ./runtest.sh <logfile>
+
+This will run all tests, as well as generate and submit a report at
+the end.  All output files will begin with "<logfile>."  If you wish to
+prevent submission of a report, add "-d" to the command line like this:
+
+   # ./runtest.sh -d <logfile>
+
+It may be useful to run tests without submission as above, and then
+submit the report at a later time.  To do so, run runtest.sh with the
+-s flag and the name of the previously-generated report:
+
+   # ./runtest.sh -s <logfile>
+
+For people needing a quick test run instead the full suite, a quick
+mode has been added that will attempt to run a representative subset
+of tests.  This is not a substitute for the whole suite, but will
+verify that some of the major functions of xen and xm are working:
+
+   # ./runtest.sh -q <logfile>
+
+Because of the current structure of the reporting software, submission
+of quick test run results is not supported.
+
+It may be desirable to run a specific test group.  This can be
+accomplished by doing the following:
 
    # cd tests/create
-   # make check
+   # TEST_VERBOSE=1 make check
+
+When developing or debugging a specific feature, a single test can be
+run to avoid having to run even a whole test group:
+
+   # cd tests/create
+   # TEST_VERBOSE=1 make check TESTS=01_create_basic_pos.test
 
 The runtest.sh script will create several files, including a .report
 file, which is the cleaned up, email-friendly report of failures.
@@ -69,15 +107,9 @@
 allocated to Dom0.  More memory available for allocation to DomUs
 means a more rigorous test.
 
-If you wish to run xm-test in an automated batch environment, you can
-run the script with the "-b" flag, which will try to prevent it from
-asking any questions interactively.  You should run it manually at
-least once to generate the "contact_info" file, which will be used in
-subsequent runs.
-
-BIG FAT WARNING: The framework assumes it is running on a dedicated
-machine.  As such, the library automatically destroys any running
-DomUs on the sytem to provide each test with a "clean slate".
+BIG FAT WARNING: The test framework assumes it is running on a
+dedicated machine.  As such, the library automatically destroys any
+running DomUs on the system to provide each test with a "clean slate".
 
 
 Extending
@@ -99,6 +131,9 @@
 subcommand itself.  The "Makefile.am.template" should be copied into
 the new group directory as "Makefile.am".
 
+See the Writing_Tests_HOWTO file for more detailed information on
+adding tests to the suite.
+
 
 Developer Notes
 ===============
@@ -114,21 +149,6 @@
 Known Issues
 ============
 
-- 08/22/2005 Dan Smith:
-    Current versions of Xen experience long delays on
-    boot, due to the blkif frontend waiting (and timing
-    out) for the backend.  We now implicitly introduce
-    a pause in XmTestDomain.start() to remedy
-    this across all tests that need it.
-
-- 09/22/2005 Dan Smith:
-    The save, restore, and migrate tests have been turned
-    back on, as we have implemented timeout functionality 
-    in "traceCommand".  Since migrate is known to hang, we 
-    can now safely include it in the default test run, and
-    have it be killed if it never finishes.  As before,
-    feedback about these tests would be specifically
-    appreciated.
 
 Reporting Bugs
 ==============
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/configure.ac
--- a/tools/xm-test/configure.ac        Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/configure.ac        Sat Nov 19 05:16:29 2005
@@ -1,7 +1,7 @@
 # xm-test configure.ac input script
 
 # Basic header information
-AC_INIT([xm-test], [0.5.0])
+AC_INIT([xm-test], [0.6.0])
 AM_INIT_AUTOMAKE([1.7 foreign])
 
 # Check for dependencies
@@ -65,5 +65,6 @@
     lib/XmTestLib/config.py
     ])
 
+AC_OUTPUT
 
-AC_OUTPUT
+chmod a+x lib/XmTestReport/xmtest.py
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/lib/XmTestLib/Console.py
--- a/tools/xm-test/lib/XmTestLib/Console.py    Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/lib/XmTestLib/Console.py    Sat Nov 19 05:16:29 2005
@@ -23,19 +23,23 @@
      a _very_ specific value, set in the PROMPT
      variable of this script
 """
-import sys;
-import os;
-import pty;
-import tty;
-import termios;
-import fcntl;
-import select;
+import sys
+import os
+import pty
+import tty
+import termios
+import fcntl
+import select
 
 from Test import *
 
+TIMEDOUT = 1
+RUNAWAY  = 2
+
 class ConsoleError(Exception):
-    def __init__(self, msg):
+    def __init__(self, msg, reason=TIMEDOUT):
         self.errMsg = msg
+        self.reason = reason
 
     def __str__(self):
         return str(self.errMsg)
@@ -52,78 +56,89 @@
                             are included in the history buffer
         """
 
-        self.TIMEOUT          = 30;
-        self.PROMPT           = "@%@%> ";
-        self.domain           = domain;
-        self.historyBuffer    = [];
-        self.historyLines     = 0;
-        self.historyLimit     = historyLimit;
-        self.historySaveAll   = historySaveAll;
-        self.historySaveCmds  = historySaveCmds;
-        self.debugMe          = False;
+        self.TIMEOUT          = 30
+        self.PROMPT           = "@%@%> "
+        self.domain           = domain
+        self.historyBuffer    = []
+        self.historyLines     = 0
+        self.historyLimit     = historyLimit
+        self.historySaveAll   = historySaveAll
+        self.historySaveCmds  = historySaveCmds
+        self.debugMe          = False
         self.limit            = None
+        self.delay            = 2
 
         consoleCmd = ["/usr/sbin/xm", "xm", "console", domain]
 
-        if verbose:
-            print "Console executing: " + str(consoleCmd)
-
-        pid, fd = pty.fork();
-
-        if pid == 0:
-            os.execvp("/usr/sbin/xm", consoleCmd[1:]);
-
-        self.consolePid = pid;
-        self.consoleFd  = fd;
-
-        tty.setraw(self.consoleFd, termios.TCSANOW);
+        start = time.time()
+
+        while (time.time() - start) < self.TIMEOUT:
+            if verbose:
+                print "Console executing: %s" % str(consoleCmd)
+
+            pid, fd = pty.fork()
+
+            if pid == 0:
+                os.execvp("/usr/sbin/xm", consoleCmd[1:])
+
+            self.consolePid = pid
+            self.consoleFd  = fd
+
+            tty.setraw(self.consoleFd, termios.TCSANOW)
             
-        bytes = self.__chewall(self.consoleFd)
-        if bytes < 0:
-            raise ConsoleError("Console didn't respond")
-
+            bytes = self.__chewall(self.consoleFd)
+
+            if bytes > 0:
+                return
+
+            if verbose:
+                print "Console didn't attach, waiting %i sec..." % self.delay
+            time.sleep(self.delay)
+
+        raise ConsoleError("Console didn't respond after %i secs" % 
self.TIMEOUT)
+    
     def __addToHistory(self, line):
-        self.historyBuffer.append(line);
-        self.historyLines += 1;
+        self.historyBuffer.append(line)
+        self.historyLines += 1
         if self.historyLines > self.historyLimit:
-            self.historyBuffer = self.historyBuffer[1:];
-            self.historyLines -= 1;
+            self.historyBuffer = self.historyBuffer[1:]
+            self.historyLines -= 1
 
 
     def clearHistory(self):
         """Clear the history buffer"""
-        self.historyBuffer = [];
-        self.historyLines = 0;
+        self.historyBuffer = []
+        self.historyLines = 0
 
 
     def getHistory(self):
         """Returns a string containing the entire history buffer"""
-        output = "";
+        output = ""
 
         for line in self.historyBuffer:
-            output += line + "\n";
-
-        return output;
+            output += line + "\n"
+
+        return output
 
 
     def setTimeout(self, timeout):
         """Sets the timeout used to determine if a remote command
         has blocked"""
-        self.TIMEOUT = timeout;
+        self.TIMEOUT = timeout
 
 
     def setPrompt(self, prompt):
         """Sets the string key used to delimit the end of command
         output"""
-        self.PROMPT = prompt;
+        self.PROMPT = prompt
 
 
     def __chewall(self, fd):
-        timeout = 0;
-        bytes   = 0;
+        timeout = 0
+        bytes   = 0
         
         while timeout < 3:
-            i, o, e = select.select([fd], [], [], 1);
+            i, o, e = select.select([fd], [], [], 1)
             if fd in i:
                 try:
                     foo = os.read(fd, 1)
@@ -138,12 +153,12 @@
 
             if self.limit and bytes >= self.limit:
                 raise ConsoleError("Console run-away (exceeded %i bytes)"
-                                   % self.limit)
+                                   % self.limit, RUNAWAY)
 
         if self.debugMe:
             print "Ignored %i bytes of miscellaneous console output" % bytes
         
-        return bytes;
+        return bytes
 
 
     def __runCmd(self, command, saveHistory=True):
@@ -152,15 +167,15 @@
         lines  = 0
         bytes  = 0
 
-        self.__chewall(self.consoleFd);
+        self.__chewall(self.consoleFd)
 
         if verbose:
             print "[%s] Sending `%s'" % (self.domain, command)
 
-        os.write(self.consoleFd, "%s\n" % command);
+        os.write(self.consoleFd, "%s\n" % command)
 
         while 1==1:
-            i, o, e = select.select([self.consoleFd], [], [], self.TIMEOUT);
+            i, o, e = select.select([self.consoleFd], [], [], self.TIMEOUT)
 
             if self.consoleFd in i:
                 try:
@@ -176,65 +191,65 @@
 
             if self.limit and bytes >= self.limit:
                 raise ConsoleError("Console run-away (exceeded %i bytes)"
-                                   % self.limit)
+                                   % self.limit, RUNAWAY)
 
             if str == "\n":
                 if lines > 0:
                     output += line + "\n"
                     if saveHistory:
-                        self.__addToHistory(line);
+                        self.__addToHistory(line)
                 elif self.historySaveCmds and saveHistory:
-                    self.__addToHistory("*" + line);
-                lines += 1;
-                line = "";
+                    self.__addToHistory("*" + line)
+                lines += 1
+                line = ""
             elif str == "\r":
                 pass # ignore \r's
             else:
-                line += str;
+                line += str
 
             if line == self.PROMPT:
-                break;
-
-        return output;
+                break
+
+        return output
 
 
     def runCmd(self, command):
         """Runs a command on the remote terminal and returns the output
         as well as the return code.  For example:
         
-        ret = c.runCmd("ls");
-        print ret["output"];
-        sys.exit(run["return"]);
+        ret = c.runCmd("ls")
+        print ret["output"]
+        sys.exit(run["return"])
         
         """
 
         # Allow exceptions to bubble up
-        realOutput = self.__runCmd(command);
-        retOutput  = self.__runCmd("echo $?", saveHistory=False);
+        realOutput = self.__runCmd(command)
+        retOutput  = self.__runCmd("echo $?", saveHistory=False)
 
         try:
-            retCode =  int(retOutput);
+            retCode =  int(retOutput)
         except:
-            retCode = 255;
+            retCode = 255
         return {
             "output": realOutput,
             "return": retCode,
-            };
+            }
 
     def sendInput(self, input):
         """Sends input to the remote terminal, but doesn't check
         for a return code"""
-        realOutput = self.__runCmd(input);
+        realOutput = self.__runCmd(input)
         return {
             "output": realOutput,
             "return": 0,
-            };
+            }
 
     def closeConsole(self):
         """Closes the console connection and ensures that the console
         process is killed"""
-        os.close(self.consoleFd);
-        os.kill(self.consolePid, 2);
+        os.close(self.consoleFd)
+        os.kill(self.consolePid, 2)
 
 
     def setLimit(self, limit):
@@ -254,23 +269,23 @@
     code as the domU command.
     """
 
-    verbose = True;
+    verbose = True
     
     try:
-        t = XmConsole(sys.argv[1]);
+        t = XmConsole(sys.argv[1])
     except ConsoleError, e:
         print "Failed to attach to console (%s)" % str(e)
         sys.exit(255)
 
     try:
-        run = t.runCmd(sys.argv[2]);
+        run = t.runCmd(sys.argv[2])
     except ConsoleError, e:
         print "Console failed (%)" % str(e)
         sys.exit(255)
         
-    t.closeConsole();
-    
-    print run["output"],;
-    sys.exit(run["return"]);
-    
-        
+    t.closeConsole()
+    
+    print run["output"],
+    sys.exit(run["return"])
+    
+        
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/lib/XmTestLib/XenDomain.py
--- a/tools/xm-test/lib/XmTestLib/XenDomain.py  Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/lib/XmTestLib/XenDomain.py  Sat Nov 19 05:16:29 2005
@@ -228,7 +228,7 @@
 #            status, output = traceCommand("xm list")
 
         XenDomain.start(self)
-        waitForBoot()
+#        waitForBoot()
 
     def startNow(self):
         XenDomain.start(self)
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/lib/XmTestReport/xmtest.py.in
--- a/tools/xm-test/lib/XmTestReport/xmtest.py.in       Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/lib/XmTestReport/xmtest.py.in       Sat Nov 19 05:16:29 2005
@@ -1,3 +1,15 @@
 #!/usr/bin/python
 
 XM_TEST_VERSION = "@PACKAGE_VERSION@"
+
+if __name__ == "__main__":
+    import re
+
+    match = re.match("^(\d+)\.(\d+)\.(\d+)$", XM_TEST_VERSION)
+
+    print "XM_TEST_VERSION=%s" % XM_TEST_VERSION
+    if match:
+        print "XM_TEST_MAJ=%s" % match.group(1)
+        print "XM_TEST_MIN=%s" % match.group(2)
+        print "XM_TEST_REV=%s" % match.group(3)
+        
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/ramdisk/Makefile.am
--- a/tools/xm-test/ramdisk/Makefile.am Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/ramdisk/Makefile.am Sat Nov 19 05:16:29 2005
@@ -1,5 +1,5 @@
 
-EXTRA_DIST = skel configs
+EXTRA_DIST = skel configs patches
 
 BR_TAR = buildroot-20050823.tar.bz2
 BR_URL = http://buildroot.uclibc.org/downloads/snapshots/$(BR_TAR)
@@ -8,6 +8,9 @@
 BR_IMG = $(BR_SRC)/rootfs.i386.ext2
 
 BR_ROOT = build_i386/root
+
+XMTEST_MAJ_VER = $(shell echo @PACKAGE_VERSION@ | perl -pe 
's/(\d+)\.(\d+)\.\d+/\1.\2/')
+XMTEST_VER_IMG = initrd-$(XMTEST_MAJ_VER).img
 
 all: initrd.img
 
@@ -21,12 +24,21 @@
        cp configs/buildroot $(BR_SRC)/.config
        cp configs/busybox $(BR_SRC)/package/busybox/busybox.config
        cp configs/uClibc $(BR_SRC)/toolchain/uClibc/uClibc.config
+       (for i in patches/buildroot/*.patch; do \
+         cd $(BR_SRC) && patch -p1 <../$$i; done )
        cd $(BR_SRC) && make oldconfig && make
 
-initrd.img: $(BR_IMG)
+$(XMTEST_VER_IMG): $(BR_IMG)
        (cd skel; tar cf - .) | (cd $(BR_SRC)/$(BR_ROOT); tar xvf -)
        cd $(BR_SRC) && make
-       cp $(BR_IMG) initrd.img
+       cp $(BR_IMG) initrd-$(XMTEST_MAJ_VER).img
+
+initrd.img: $(XMTEST_VER_IMG)
+       ln -sf $(XMTEST_VER_IMG) initrd.img
+
+existing:
+       @[ -f $(XMTEST_VER_IMG) ] && ln -sf $(XMTEST_VER_IMG) initrd.img || \
+       echo Error, $(XMTEST_VER_IMG) not found
 
 clean-local: am_config_clean-local
 
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/ramdisk/configs/buildroot
--- a/tools/xm-test/ramdisk/configs/buildroot   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/ramdisk/configs/buildroot   Sat Nov 19 05:16:29 2005
@@ -225,6 +225,7 @@
 # BR2_PACKAGE_WIRELESS_TOOLS is not set
 # BR2_PACKAGE_XORG is not set
 # BR2_PACKAGE_ZLIB is not set
+BR2_PACKAGE_HPING=y
 
 #
 # Target Options
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/runtest.sh
--- a/tools/xm-test/runtest.sh  Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/runtest.sh  Sat Nov 19 05:16:29 2005
@@ -1,215 +1,271 @@
 #!/bin/sh
 
-usage() {
-    echo "Usage: $0 [opts] <logfile>"
-    echo "  Where opts are:"
-    echo "  -d         : do not submit a report for this run"
-    echo "  -b         : do not ask any questions (batch mode)"
-    echo "  -e <email> : set email address for report"
-}
 ##
 ## Test driver script
 ##
 
-#
-# Defaults
-#
-MAXFAIL=10
-report=yes
-batch=no
-
-#
-# Resolve options
-#
-while [ $# -gt 0 ]
-do
-    case "$1" in
-    -d)
-        echo "(Skipping report submission)"
-        report=no
-        ;;
-    -b)
-        echo "(Batch mode)"
-        batch=yes
-        ;;
-    -e)
-        shift
-        echo $1 > contact_info
-        echo "(Email set to $1)"
-        ;;
-    *)
-        LOGFILE=$1
-        break
-        ;;
-    esac
-    shift
-done
-
-#
-# Usage
-#
-if [ -z $LOGFILE ]; then
-       usage
-       exit 1
-fi
-
-#
-# Output files
-#
-OSREPORTTEMP=${LOGFILE}.os.xml
-PROGREPORTTEMP=${LOGFILE}.prog.xml
-RESULTREPORTTEMP=${LOGFILE}.result.xml
-OUTPUT=${LOGFILE}.output
-SUMMARY=${LOGFILE}.summary
-PASSFAIL=${LOGFILE}.passfail
-REPORT=${LOGFILE}.report
-FAILURES=${LOGFILE}.failures
-               
-#
-# Make sure we're root
-#
-uid=$(id -u)
-if [ $uid != 0 ]; then 
-    echo "ERROR: I must be run as root!"
-    exit 1
-fi
-
-#
-# See if the ramdisk has been built
-#
-rdsize=$(stat -c %s ramdisk/initrd.img 2>/dev/null)
-if [ -z "$rdsize" ] || [ $rdsize -le 16384 ]; then
-    echo "Cannot find a valid ramdisk.  You need to run \"make\" or"
-    echo "copy in a previously-built ramdisk to the ramdisk/ directory"
-    exit 1
-fi
-
-#
-# See if xend is running
-#
-if ! xm list >/dev/null 2>&1; then
-    echo "'xm list' failed: is xend running?"
-    exit 1
-fi
-
-#
-#  Make sure permissions are correct
-#
-chmod a+x lib/XmTestReport/*
-chmod a+x mkreport mergereport
-
-#
+usage() {
+    echo "Usage: $0 [opts] <report>"
+    echo "  Where report is a name that will be used for report files"
+    echo ""
+    echo "  Where opts are:"
+    echo "  -d          : do not submit a report for this run"
+    echo "  -b          : do not ask any questions (batch mode)"
+    echo "  -q          : run a quick test set"
+    echo "  -e <email>  : set email address for report"
+    echo "  -s <report> : just submit report <report>"
+}
+
+# Just submit the report
+submit_report() {
+
+    reportfile=$1
+
+    ./lib/XmTestReport/Report.py $reportfile
+}
+
+# Generate XML result report from output file
+make_result_report() {
+    output=$1
+    reportfile=$2
+    if ! ./lib/XmTestReport/ResultReport.py $output > $reportfile; then
+       echo "Unable to generate clean ResultReport"
+       echo "Take a look at $report"
+       exit 1
+    fi
+}
+
+# Collect environment information for XML report
+make_environment_report() {
+    os=$1
+    prog=$2
+    if ! ./lib/XmTestReport/OSReport.py > $os; then
+       echo "Unable to generate clean OSReport"
+       echo "Take a look at $os"
+       exit 1
+    fi
+    if ! ./lib/XmTestReport/ProgReport.py > $prog; then
+       echo "Unable to generate clean ProgReport"
+       echo "Take a look at $prog"
+       exit 1
+    fi
+}
+
+# Check conditions needed to actually run the tests
+runnable_tests() {     
+    # Make sure we're root
+    uid=$(id -u)
+    if [ $uid != 0 ]; then 
+       echo "ERROR: I must be run as root!"
+       exit 1
+    fi
+
+    # See if the ramdisk has been built
+    rdsize=$(stat -Lc %s ramdisk/initrd.img 2>/dev/null)
+    if [ -z "$rdsize" ] || [ $rdsize -le 16384 ]; then
+       echo "Cannot find a valid ramdisk.  You need to run \"make\" or"
+       echo "copy in a previously-built ramdisk to the ramdisk/ directory"
+       exit 1
+    fi
+
+    # Figure out the version of the ramdisk link and compare it
+    # to what it should be as a cheap way of making sure we're
+    # using the right version
+    realrd=$(readlink ramdisk/initrd.img)
+    eval $(./lib/XmTestReport/xmtest.py)
+    rrdver="initrd-${XM_TEST_MAJ}.${XM_TEST_MIN}.img"
+    if [ "$realrd" != "$rrdver" ]; then
+       echo "Error: ramdisk/initrd.img is from an old version"
+       echo "You need to build a ramdisk from at least 
${XM_TEST_MAJ}.${XM_TEST_MIN}"
+       exit 1
+    fi
+
+    # See if xend is running
+    if ! xm list >/dev/null 2>&1; then
+       echo "'xm list' failed: is xend running?"
+       exit 1
+    fi
+
+}
+
 # Get contact info if needed
-#
-if [ ! -f contact_info ]; then
-    if [ "$batch" = "yes" ]; then
-       echo "Unable to read contact_info!"
-       echo "Please run me once interactively before using batch mode!"
-       exit 1
-    else
-       echo "Please provide your email address so that we can "
-       echo "contact you if we need further information concerning"
-       echo "your results.  Any information provided will be"
-       echo "kept private.  If you wish to remain anonymous, please"
-       echo "hit [ENTER] now."
-       
-       while ! echo "$EMAIL" | grep -q '@'; do
-           echo
-           echo -n "Your email address: "
-           read EMAIL
-           if [ -z $EMAIL ]; then
-               EMAIL="anonymous@xxxxxxxxxxxxx"
-           fi
-       done
-       echo $EMAIL > contact_info
-    fi
-fi
-
-#
-# Collect environment information for XML report
-#
-if ! ./lib/XmTestReport/OSReport.py > $OSREPORTTEMP; then
-    echo "Unable to generate clean OSReport"
-    echo "Take a look at $OSREPORTTEMP"
-    exit 1
-fi
-if ! ./lib/XmTestReport/ProgReport.py > $PROGREPORTTEMP; then
-    echo "Unable to generate clean ProgReport"
-    echo "Take a look at $PROGREPORTTEMP"
-    exit 1
-fi
-
-#
+get_contact_info() {
+    
+    if [ ! -f contact_info ]; then
+       if [ "$batch" = "yes" ]; then
+           echo "Unable to read contact_info!"
+           echo "Please run me once interactively before using batch mode!"
+           exit 1
+       else
+           echo "Please provide your email address so that we can "
+           echo "contact you if we need further information concerning"
+           echo "your results.  Any information provided will be"
+           echo "kept private.  If you wish to remain anonymous, please"
+           echo "hit [ENTER] now."
+           
+           while ! echo "$EMAIL" | grep -q '@'; do
+               echo
+               echo -n "Your email address: "
+               read EMAIL
+               if [ -z $EMAIL ]; then
+                   EMAIL="anonymous@xxxxxxxxxxxxx"
+               fi
+           done
+           echo $EMAIL > contact_info
+       fi
+    fi
+}
+
 # Run the tests
-#
-export TEST_VERBOSE=1
-echo Running tests...
-make -k check > $OUTPUT 2>&1
-
-#
+run_tests() {
+    output=$1
+    echo Running tests...
+    TEST_VERBOSE=1 make -k check > $output 2>&1
+}
+
+run_tests_quick() {
+
+    output=$1
+
+    create_tests="01_create_basic_pos.test 07_create_mem64_pos.test 
10_create_fastdestroy.test 14_create_blockroot_pos.test"
+    unpause_tests="01_unpause_basic_pos.test"
+    memset_tests="01_memset_basic_pos.test 03_memset_random_pos.test"
+    help_tests="06_help_allcmds.test"
+    testgroups="create unpause memset help"
+
+    echo "*** Quick test" > $output
+    for group in $testgroups; do
+       eval $(echo list=\$${group}_tests)
+       echo "*** Running tests [$list] from $group"
+       (cd tests/$group && TEST_VERBOSE=1 make -k check TESTS="$list") >> 
$output 2>&1
+    done
+
+}
+
 # Generate some plain-text reports
-#
-echo "Making PASS/FAIL report ($PASSFAIL)..."
-cat $OUTPUT | egrep '(REASON|PASS|FAIL|XPASS|XFAIL|SKIP)' | perl -pe 
's/^(PASS|FAIL|XPASS|XFAIL)(.+)$/$1$2\n/' > $PASSFAIL
-
-echo "Making FAIL report ($FAILURES)..."
-cat $PASSFAIL | egrep '(REASON|FAIL)' > $FAILURES
-
-NUMPASS=`grep -c PASS $OUTPUT`
-NUMFAIL=`grep -c FAIL $OUTPUT`
-NUMXPASS=`grep -c XPASS $OUTPUT`
-NUMXFAIL=`grep -c XFAIL $OUTPUT`
-cat > $SUMMARY << EOF
+make_text_reports() {
+    passfail=$1
+    failures=$2
+    output=$3
+    reportfile=$4
+    summary=summary.tmp
+    echo "Making PASS/FAIL report ($passfail)..."
+    cat $OUTPUT | egrep '(REASON|PASS|FAIL|XPASS|XFAIL|SKIP)' | perl -pe 
's/^(PASS|FAIL|XPASS|XFAIL)(.+)$/$1$2\n/' > $passfail
+    
+    echo "Making FAIL report ($failures)..."
+    cat $passfail | egrep '(REASON|FAIL)' > $failures
+    
+    NUMPASS=`grep -c PASS $output`
+    NUMFAIL=`grep -c FAIL $output`
+    NUMXPASS=`grep -c XPASS $output`
+    NUMXFAIL=`grep -c XFAIL $output`
+    cat > $summary << EOF
 Xm-test execution summary:
   PASS:  $NUMPASS
   FAIL:  $NUMFAIL
   XPASS: $NUMXPASS
   XFAIL: $NUMXFAIL
 EOF
-
-cat $SUMMARY > $REPORT
-
-echo -e '\n\nDetails:\n' >> $REPORT
- 
-./mkreport $PASSFAIL >> $REPORT
-
-#
-# Check to see if it's worth reporting these results
-#
-#if  [ "$batch"  =   "no" ] && 
-#    [ "$report" =   "yes" ] && 
-#    [ $NUMFAIL  -gt $MAXFAIL ]; then
-#    echo "NOTE: $NUMFAIL tests failed, which may be erroneous.  It may"
-#    echo "be a good idea to review the report before sending.  If you"
-#    echo "choose not to submit the report, it will be saved for your review"
-#    echo "and later submission."
-#    echo
-#    echo -n "Submit anyway? [y/n] "
-#    read ANSWER
-#    if [ "$ANSWER" = "n" ]; then
-#      report=no
-#    fi
-#fi
-
-#
-# Generate the XML result report
-#
-if ! ./lib/XmTestReport/ResultReport.py $OUTPUT > $RESULTREPORTTEMP; then
-    echo "Unable to generate clean ResultReport"
-    echo "Take a look at $RESULTREPORTTEMP"
-    exit 1
-fi
-
-#
-# Maybe submit report and save the combined XML file
-#
-if [ "$report" = "yes" ]; then
-    echo "Sending report..."
-    ./lib/XmTestReport/Report.py -D $OSREPORTTEMP $PROGREPORTTEMP \
-                                    $RESULTREPORTTEMP > $1.xml
-    echo "Report also saved in $1.xml"
-else
-    echo "Saving report to $1.xml..."
-    ./lib/XmTestReport/Report.py -d $OSREPORTTEMP $PROGREPORTTEMP \
-                                    $RESULTREPORTTEMP > $1.xml
-fi
+    
+    cat $summary > $reportfile
+    
+    echo -e '\n\nDetails:\n' >> $reportfile
+    
+    ./mkreport $passfail >> $reportfile
+
+    rm $summary
+}
+
+############
+### Main ###
+############
+
+# Defaults
+MAXFAIL=10
+report=yes
+batch=no
+run=yes
+
+# Resolve options
+while [ $# -gt 0 ]
+  do
+  case "$1" in
+      -d)
+         echo "(Skipping report submission)"
+         report=no
+         ;;
+      -b)
+         echo "(Batch mode)"
+         batch=yes
+         ;;
+      -e)
+         shift
+         echo $1 > contact_info
+         echo "(Email set to $1)"
+         ;;
+      -q)
+         run=quick
+         ;;
+      -s)
+         run=no
+         ;;
+      *)
+         REPORT=$1
+         break
+         ;;
+  esac
+  shift
+done
+
+# Usage
+if [ -z $REPORT ]; then
+       usage
+       exit 1
+fi
+
+# Output files
+OSREPORTTEMP=${REPORT}.os.xml
+PROGREPORTTEMP=${REPORT}.prog.xml
+RESULTREPORTTEMP=${REPORT}.result.xml
+XMLREPORT=${REPORT}.xml
+OUTPUT=${REPORT}.output
+SUMMARY=${REPORT}.summary
+PASSFAIL=${REPORT}.passfail
+TXTREPORT=${REPORT}.report
+FAILURES=${REPORT}.failures
+       
+#  Make sure permissions are correct
+chmod a+x lib/XmTestReport/*
+chmod a+x mkreport mergereport
+
+if [ ! -f contact_info ]; then
+    if [ "$batch" = "yes" ]; then
+       echo "Unable to read contact_info"
+       echo "You must run me interactively once!"
+       exit 1
+    else
+       get_contact_info
+    fi
+fi
+
+if [ "$run" != "no" ]; then
+    runnable_tests
+    make_environment_report $OSREPORTTEMP $PROGREPORTTEMP
+    if [ "$run" = "yes" ]; then
+       run_tests $OUTPUT
+    else
+       run_tests_quick $OUTPUT
+    fi
+    make_text_reports $PASSFAIL $FAILURES $OUTPUT $TXTREPORT
+    make_result_report $OUTPUT $RESULTREPORTTEMP
+    cat $OSREPORTTEMP $PROGREPORTTEMP $RESULTREPORTTEMP > $XMLREPORT
+    rm $OSREPORTTEMP $PROGREPORTTEMP $RESULTREPORTTEMP
+fi
+
+if [ "$report" = "yes" ] && [ "$run" = "yes" ]; then
+    if [ ! -f "$XMLREPORT" ]; then
+       echo "No such file: $XMLREPORT"
+       exit 1
+    fi
+    submit_report $XMLREPORT
+fi
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/block-create/04_block_attach_device_repeatedly_pos.py
--- a/tools/xm-test/tests/block-create/04_block_attach_device_repeatedly_pos.py 
Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/block-create/04_block_attach_device_repeatedly_pos.py 
Sat Nov 19 05:16:29 2005
@@ -38,11 +38,13 @@
     
 for i in range(10):
        status, output = traceCommand("xm block-attach %s phy:ram1 sdb1 w" % 
domain.getName())
-       if status != 0:
-               FAIL("xm block-attach returned invalid %i != 0" % status)
+        if i == 0 and status != 0:
+            FAIL("xm block attach returned invalid %i != 0" % status)
+       if i > 0 and status == 0:
+            FAIL("xm block-attach (repeat) returned invalid %i > 0" % status)
        run = console.runCmd("cat /proc/partitions")
        if not re.search("sdb1", run['output']):
-               FAIL("Device is not actually attached to domU")
+            FAIL("Device is not actually attached to domU")
 
 # Close the console
 console.closeConsole()
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/block-create/06_block_attach_baddomain_neg.py
--- a/tools/xm-test/tests/block-create/06_block_attach_baddomain_neg.py Sat Nov 
19 05:06:09 2005
+++ b/tools/xm-test/tests/block-create/06_block_attach_baddomain_neg.py Sat Nov 
19 05:16:29 2005
@@ -11,7 +11,7 @@
 where = output.find(eyecatcher)
 if status == 0:
        FAIL("xm block-attach returned bad status, expected non 0, status is: 
%i" % status )
-elif where > 1:
+elif where == -1:
        FAIL("xm block-attach returned bad output, expected Error, output is: 
%s" % output )
        
 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/block-create/07_block_attach_baddevice_neg.py
--- a/tools/xm-test/tests/block-create/07_block_attach_baddevice_neg.py Sat Nov 
19 05:06:09 2005
+++ b/tools/xm-test/tests/block-create/07_block_attach_baddevice_neg.py Sat Nov 
19 05:16:29 2005
@@ -42,7 +42,7 @@
 where = output.find(eyecatcher)
 if status == 0:
        FAIL("xm block-attach returned bad status, expected non 0, status is: 
%i" % status )
-elif where > 1:
+elif where == -1:
        FAIL("xm block-attach returned bad output, expected Error, output is: 
%s" % output )
 
 try:
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/block-create/08_block_attach_bad_filedevice_neg.py
--- a/tools/xm-test/tests/block-create/08_block_attach_bad_filedevice_neg.py    
Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/block-create/08_block_attach_bad_filedevice_neg.py    
Sat Nov 19 05:16:29 2005
@@ -41,7 +41,7 @@
 where = output.find(eyecatcher)
 if status == 0:
        FAIL("xm block-attach returned bad status, expected non 0, status is: 
%i" % status )
-elif where > 1:
+elif where == -1:
        FAIL("xm block-attach returned bad output, expected Error, output is: 
%s" % output )
        
 try:
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/block-create/09_block_attach_and_dettach_device_check_data_pos.py
--- 
a/tools/xm-test/tests/block-create/09_block_attach_and_dettach_device_check_data_pos.py
     Sat Nov 19 05:06:09 2005
+++ 
b/tools/xm-test/tests/block-create/09_block_attach_and_dettach_device_check_data_pos.py
     Sat Nov 19 05:16:29 2005
@@ -36,7 +36,9 @@
     saveLog(console.getHistory())
     FAIL(str(e))
     
-os.system("mkfs.ext2 -F /dev/ram1")
+s, o = traceCommand("mke2fs -q -F /dev/ram1")
+if s != 0:
+    FAIL("mke2fs returned %i != 0" % s)
 
 for i in range(10):
        status, output = traceCommand("xm block-attach %s phy:ram1 hda1 w" % 
domain.getName())
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/tests/block-list/Makefile.am
--- a/tools/xm-test/tests/block-list/Makefile.am        Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/block-list/Makefile.am        Sat Nov 19 05:16:29 2005
@@ -5,7 +5,8 @@
        02_block-list_attachbd_pos.test \
        03_block-list_anotherbd_pos.test \
        04_block-list_nodb_pos.test \
-       05_block-list_nonexist_neg.test
+       05_block-list_nonexist_neg.test \
+       06_block-list_checkremove_pos.test
 
 XFAIL_TESTS = 
 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/console/01_console_badopt_neg.py
--- a/tools/xm-test/tests/console/01_console_badopt_neg.py      Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/console/01_console_badopt_neg.py      Sat Nov 19 
05:16:29 2005
@@ -17,5 +17,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm console returned invalid %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm console didn't report error on bad argument")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/console/02_console_baddom_neg.py
--- a/tools/xm-test/tests/console/02_console_baddom_neg.py      Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/console/02_console_baddom_neg.py      Sat Nov 19 
05:16:29 2005
@@ -15,7 +15,7 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm console returned invalid %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm console failed to report error on bad domid")
 
 status, output = traceCommand("xm console NON_EXIST")
@@ -23,5 +23,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm console returned invalid %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm console failed to report error on bad domname") 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/create/02_create_noparm_neg.py
--- a/tools/xm-test/tests/create/02_create_noparm_neg.py        Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/create/02_create_noparm_neg.py        Sat Nov 19 
05:16:29 2005
@@ -12,6 +12,6 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm create returned invalid %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm create failed to report error on missing args")
 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/create/03_create_badparm_neg.py
--- a/tools/xm-test/tests/create/03_create_badparm_neg.py       Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/create/03_create_badparm_neg.py       Sat Nov 19 
05:16:29 2005
@@ -15,5 +15,5 @@
 status, output = traceCommand("xm create -x")
 eyecatcher = "Error:"
 where = output.find(eyecatcher)
-if where != 0:
+if where == -1:
     FAIL("xm create failed to report error on bad arg")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/create/05_create_noroot_noram_neg.py
--- a/tools/xm-test/tests/create/05_create_noroot_noram_neg.py  Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/create/05_create_noroot_noram_neg.py  Sat Nov 19 
05:16:29 2005
@@ -22,5 +22,5 @@
 eyecatcher = "NOROOT"
 status, output = traceCommand("xm list")
 where = output.find(eyecatcher)
-if where != -1 :
+if where != -1:
        FAIL("xm create test05 passed with no root and no ramdisk. Expected 
result: Fail.")
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/tests/create/Makefile.am
--- a/tools/xm-test/tests/create/Makefile.am    Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/create/Makefile.am    Sat Nov 19 05:16:29 2005
@@ -12,8 +12,8 @@
        11_create_concurrent_pos.test \
        12_create_concurrent_stress_pos.test \
        13_create_multinic_pos.test \
-       14_create_blockroot_pos.test
-
+       14_create_blockroot_pos.test \
+       15_create_smallmem_pos.test
 
 DISABLED_TESTS =       05_create_noroot_noram_neg.test 
 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/destroy/02_destroy_noparm_neg.py
--- a/tools/xm-test/tests/destroy/02_destroy_noparm_neg.py      Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/destroy/02_destroy_noparm_neg.py      Sat Nov 19 
05:16:29 2005
@@ -12,5 +12,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm destroy returned invalid %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm destroy failed to report error for missing arg")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/destroy/03_destroy_nonexist_neg.py
--- a/tools/xm-test/tests/destroy/03_destroy_nonexist_neg.py    Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/destroy/03_destroy_nonexist_neg.py    Sat Nov 19 
05:16:29 2005
@@ -12,5 +12,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm destroy returned invalid %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm destroy failed to report error for bad arg")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/destroy/04_destroy_badparm_neg.py
--- a/tools/xm-test/tests/destroy/04_destroy_badparm_neg.py     Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/destroy/04_destroy_badparm_neg.py     Sat Nov 19 
05:16:29 2005
@@ -12,5 +12,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm destroy returned invalid %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm destroy failed to report error for bad domid")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/dmesg/02_dmesg_basic_neg.py
--- a/tools/xm-test/tests/dmesg/02_dmesg_basic_neg.py   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/dmesg/02_dmesg_basic_neg.py   Sat Nov 19 05:16:29 2005
@@ -12,6 +12,6 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm dmesg returned invalid %i != 0" % status)
-elif where == 1:
+elif where == -1:
     FAIL("xm dmesg failed to report error for bad arg")
 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/help/01_help_basic_pos.py
--- a/tools/xm-test/tests/help/01_help_basic_pos.py     Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/help/01_help_basic_pos.py     Sat Nov 19 05:16:29 2005
@@ -10,5 +10,5 @@
 status, output = traceCommand("xm help")
 eyecatcher = "Usage:"
 where = output.find(eyecatcher)
-if where != 0:
+if where == -1:
     FAIL("xm help: didn't see the usage string")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/help/02_help_basic_neg.py
--- a/tools/xm-test/tests/help/02_help_basic_neg.py     Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/help/02_help_basic_neg.py     Sat Nov 19 05:16:29 2005
@@ -10,5 +10,5 @@
 status, output = traceCommand("xm")
 eyecatcher = "Usage:"
 where = output.find(eyecatcher)
-if where != 0:
+if where == -1:
     FAIL("xm: didn't display usage when given no arguments")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/help/03_help_badparm_neg.py
--- a/tools/xm-test/tests/help/03_help_badparm_neg.py   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/help/03_help_badparm_neg.py   Sat Nov 19 05:16:29 2005
@@ -10,5 +10,5 @@
 status, output = traceCommand("xm -x")
 eyecatcher = "Error:"
 where = output.find(eyecatcher)
-if where != 0:
+if where == -1:
     FAIL("xm failed to report error for bad arg")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/help/05_help_nonroot_pos.py
--- a/tools/xm-test/tests/help/05_help_nonroot_pos.py   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/help/05_help_nonroot_pos.py   Sat Nov 19 05:16:29 2005
@@ -13,5 +13,5 @@
 status, output = traceCommand("xm help")
 eyecatcher = "Usage:"
 where = output.find(eyecatcher)
-if where != 0:
+if where == -1:
     FAIL("xm help: didn't see the usage string")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/list/02_list_badparm_neg.py
--- a/tools/xm-test/tests/list/02_list_badparm_neg.py   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/list/02_list_badparm_neg.py   Sat Nov 19 05:16:29 2005
@@ -12,5 +12,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm list returned invalud %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm list failed to report error for bad arg")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/list/03_list_nonexist_neg.py
--- a/tools/xm-test/tests/list/03_list_nonexist_neg.py  Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/list/03_list_nonexist_neg.py  Sat Nov 19 05:16:29 2005
@@ -12,6 +12,6 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm list returned invalid %i != 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm list failed to report error for invalid domid")
 
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/tests/list/06_list_nonroot.py
--- a/tools/xm-test/tests/list/06_list_nonroot.py       Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/list/06_list_nonroot.py       Sat Nov 19 05:16:29 2005
@@ -11,5 +11,5 @@
 status, output = traceCommand("xm list")
 eyecatcher = "Error: Most commands need root access"
 where = output.find(eyecatcher)
-if where != 0:
+if where == -1:
     FAIL("xm help: didn't see the root hint, saw %s" % output)
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/memset/02_memset_badparm_neg.py
--- a/tools/xm-test/tests/memset/02_memset_badparm_neg.py       Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/memset/02_memset_badparm_neg.py       Sat Nov 19 
05:16:29 2005
@@ -24,7 +24,7 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm mem-set returned invalid %i == 0" % status)
-elif where > 1:
+elif where == -1:
     FAIL("xm mem-set failed to report error for missing arg")
 
 # destroy non existent parm input - negative test
@@ -32,7 +32,7 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm mem-set returned invalid %i == 0" % status)
-elif where != 0:
+elif where == -1:
     FAIL("xm mem-set failed to report error for bad arg")
 
 # destroy non existent domain - negative test
@@ -40,14 +40,14 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm mem-set returned invalid %i == 0" % status)
-elif where != 0:
+elif where == -1:
     FAIL("xm mem-set failed to report error for invalid domid")
 
 # destroy non existent domain and memory - negative test
 status, output = traceCommand("xm mem-set 6666 64")
 where = output.find(eyecatcher)
 if status == 0:
-    FAIL("xm mem-set returned invalid %i != 0" % status)
-elif where != 0:
+    FAIL("xm mem-set returned invalid %i == -1" % status)
+elif where == -1:
     FAIL("xm mem-set failed to report error for invalid domid")
 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/memset/04_memset_smallmem_pos.py
--- a/tools/xm-test/tests/memset/04_memset_smallmem_pos.py      Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/memset/04_memset_smallmem_pos.py      Sat Nov 19 
05:16:29 2005
@@ -36,6 +36,17 @@
     # See if this hits the byte limit
     console.runCmd("ls")
 except ConsoleError, e:
-    FAIL(str(e))
+    if e.reason == RUNAWAY:
+        # Need to stop the domain before we restart the console daemon
+        domain.destroy()
+        if verbose:
+            print "*** Attempting restart of xenconsoled"
+            s, o = traceCommand("killall xenconsoled")
+            s, o = traceCommand("xenconsoled")
+            if s != 0:
+                print "*** Starting xenconsoled failed: %i" % s
+        FAIL("Bug #380: I crashed the console system")
+    else:
+        FAIL(str(e))
 
 domain.destroy()
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/pause/01_pause_basic_pos.py
--- a/tools/xm-test/tests/pause/01_pause_basic_pos.py   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/pause/01_pause_basic_pos.py   Sat Nov 19 05:16:29 2005
@@ -49,12 +49,9 @@
 if status != 0:
        FAIL("xm pause returned invalid %i != 0", status)
 
-# Attach a console to it
+# Try to attach a console to it
 try:
     console = XmConsole(domain.getName(), historySaveCmds=True)
-except ConsoleError, e:
-    FAIL(str(e))
-try:
     run = console.runCmd("ls")
     #If we get here, console attached to paused domain (unexpected)
     FAIL("console attached to supposedly paused domain")
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/pause/02_pause_badopt_neg.py
--- a/tools/xm-test/tests/pause/02_pause_badopt_neg.py  Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/pause/02_pause_badopt_neg.py  Sat Nov 19 05:16:29 2005
@@ -25,7 +25,7 @@
 if status == 0:
     domain.destroy()
     FAIL("xm pause returned bad status, expected non 0, status is: %i" % 
status )
-elif where > 1:
+elif where == -1:
     domain.destroy()
     FAIL("xm pause returned bad output, expected Error, output is: %s" % 
output )
 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/pause/03_pause_badname_neg.py
--- a/tools/xm-test/tests/pause/03_pause_badname_neg.py Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/pause/03_pause_badname_neg.py Sat Nov 19 05:16:29 2005
@@ -14,5 +14,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm pause returned bad status, expected non 0, status is: %i" % 
status )
-elif where > 1:
+elif where == -1:
     FAIL("xm pause returned bad output, expected Error, output is: %s" % 
output )
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/pause/04_pause_badid_neg.py
--- a/tools/xm-test/tests/pause/04_pause_badid_neg.py   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/pause/04_pause_badid_neg.py   Sat Nov 19 05:16:29 2005
@@ -14,5 +14,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm pause returned bad status, expected non 0, status is: %i" % 
status )
-elif where > 1:
+elif where == -1:
     FAIL("xm pause returned bad output, expected Error, output is: %s" % 
output )
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/reboot/01_reboot_basic_pos.py
--- a/tools/xm-test/tests/reboot/01_reboot_basic_pos.py Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/reboot/01_reboot_basic_pos.py Sat Nov 19 05:16:29 2005
@@ -17,6 +17,13 @@
         print "Failed to create test domain because:"
         print e.extra
     FAIL(str(e))
+
+try:
+    console = XmConsole(domain.getName())
+except ConsoleError, e:
+    FAIL(str(e))
+
+console.closeConsole()
 
 status, output = traceCommand("xm reboot %s" % domain.getName())
 
@@ -40,8 +47,11 @@
 
 domain.destroy()
 
-items = re.split(" +", run["output"])
-uptime = int(items[3])
-if uptime > 1:
-    FAIL("Uptime too large (%i > 1 minutes); domain didn't reboot")
+match = re.match("^[^up]*up ([0-9]+).*$", run["output"])
+if match:
+    if int(match.group(1)) > 1:
+        FAIL("Uptime too large (%i > 1 minutes); domain didn't reboot")
+else:
+    FAIL("Invalid uptime string: %s (%s)" % (run["output"], match.group(1)))
 
+
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/reboot/02_reboot_badopt_neg.py
--- a/tools/xm-test/tests/reboot/02_reboot_badopt_neg.py        Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/reboot/02_reboot_badopt_neg.py        Sat Nov 19 
05:16:29 2005
@@ -25,7 +25,7 @@
 if status == 0:
     domain.destroy()
     FAIL("xm reboot returned invalid %i == 0" % status )
-elif where > 1:
+elif where == -1:
     domain.destroy()
     FAIL("xm reboot failed to report error for bad arg")
 
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/reboot/03_reboot_badname_neg.py
--- a/tools/xm-test/tests/reboot/03_reboot_badname_neg.py       Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/reboot/03_reboot_badname_neg.py       Sat Nov 19 
05:16:29 2005
@@ -14,5 +14,5 @@
 where = output.find(eyecatcher)
 if status == 0:
     FAIL("xm reboot returned invalid %i == 0" % status )
-elif where > 1:
+elif where == -1:
     FAIL("xm reboot failed to report error for non-existent domain" )
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/restore/02_restore_badparm_neg.py
--- a/tools/xm-test/tests/restore/02_restore_badparm_neg.py     Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/restore/02_restore_badparm_neg.py     Sat Nov 19 
05:16:29 2005
@@ -21,5 +21,5 @@
     FAIL("xm restore returned bad status, expected non 0, status is: %i" % 
status)
 elif where2 == 0:
     FAIL("xm restore returned a stack dump, expected nice error message") 
-elif where1 > 0:
+elif where1 == -1:
     FAIL("xm restore returned bad output, expected Error:, output is: %s" % 
output)
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/restore/03_restore_badfilename_neg.py
--- a/tools/xm-test/tests/restore/03_restore_badfilename_neg.py Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/restore/03_restore_badfilename_neg.py Sat Nov 19 
05:16:29 2005
@@ -21,5 +21,5 @@
     FAIL("xm restore returned bad status, expected non 0, status is: %i" % 
status)
 elif where2 == 0:
     FAIL("xm restore returned a stack dump, expected nice error message") 
-elif where1 > 0:
+elif where1 == -1:
     FAIL("xm restore returned bad output, expected Error:, output is: %s" % 
output)
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/restore/04_restore_withdevices_pos.py
--- a/tools/xm-test/tests/restore/04_restore_withdevices_pos.py Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/restore/04_restore_withdevices_pos.py Sat Nov 19 
05:16:29 2005
@@ -5,13 +5,20 @@
 
 from XmTestLib import *
 
-domain = XmTestDomain()
+import re
+
+domain = XmTestDomain(extraOpts={"nics":2})
 
 domain.configAddDisk("phy:/dev/ram0", "hda1", "w")
+domain.configAddDisk("phy:/dev/ram1", "hdb2", "w")
 
-s, o = traceCommand("mkfs /dev/ram0")
+s, o = traceCommand("mke2fs -q /dev/ram0")
 if s != 0:
-    FAIL("Unable to mkfs /dev/ram0 in dom0")
+    FAIL("Unable to mke2fs /dev/ram0 in dom0")
+
+s, o = traceCommand("mke2fs -q /dev/ram1")
+if s != 0:
+    FAIL("Unable to mke2fs /dev/ram1 in dom0")
 
 try:
     domain.start()
@@ -22,13 +29,38 @@
     console = XmConsole(domain.getName())
     console.sendInput("foo")
 
-    run = console.runCmd("mount /dev/hda1 /mnt")
+    run = console.runCmd("mkdir /mnt/a /mnt/b")
+    if run["return"] != 0:
+        FAIL("Unable to mkdir /mnt/a /mnt/b")
+
+    run = console.runCmd("mount /dev/hda1 /mnt/a")
     if run["return"] != 0:
         FAIL("Unable to mount /dev/hda1")
 
-    run = console.runCmd("echo bar > /mnt/foo")
+    run = console.runCmd("mount /dev/hdb2 /mnt/b")
     if run["return"] != 0:
-        FAIL("Unable to write to block device!")
+        FAIL("Unable to mount /dev/hdb2")
+
+    run = console.runCmd("echo hda1 > /mnt/a/foo")
+    if run["return"] != 0:
+        FAIL("Unable to write to block device hda1!")
+
+    run = console.runCmd("echo hdb2 > /mnt/b/foo")
+    if run["return"] != 0:
+        FAIL("Unable to write to block device hdb2!")
+
+    run = console.runCmd("ifconfig eth0 169.254.0.1 netmask 255.255.255.0")
+    if run["return"] != 0:
+        FAIL("Unable to configure DomU's eth0")
+
+    run = console.runCmd("ifconfig eth1 169.254.1.1 netmask 255.255.255.0")
+    if run["return"] != 0:
+        FAIL("Unable to configure DomU's eth1")
+
+    run = console.runCmd("ifconfig lo 127.0.0.1")
+    if run["return"] != 0:
+        FAIL("Unable to configure DomU's lo")
+
 
 except ConsoleError, e:
     FAIL(str(e))
@@ -63,9 +95,31 @@
     if run["return"] != 0:
         FAIL("ls failed on restored domain")
     
-    run = console.runCmd("cat /mnt/foo | grep bar")
+    run = console.runCmd("cat /mnt/a/foo")
     if run["return"] != 0:
-        FAIL("Unable to read from block device")
+        FAIL("Unable to read from block device hda1")
+    if not re.search("hda1", run["output"]):
+        FAIL("Failed to read correct data from hda1")
+
+    run = console.runCmd("cat /mnt/b/foo")
+    if run["return"] != 0:
+        FAIL("Unable to read from block device hdb2")
+    if not re.search("hdb2", run["output"]):
+        FAIL("Failed to read correct data from hdb2")
+
+    run = console.runCmd("ifconfig")
+    if not re.search("eth0", run["output"]):
+        FAIL("DomU's eth0 disappeared")
+    if not re.search("169.254.0.1", run["output"]):
+        FAIL("DomU's eth0 lost its IP")
+    if not re.search("eth1", run["output"]):
+        FAIL("DomU's eth1 disappeared")
+    if not re.search("169.254.1.1", run["output"]):
+        FAIL("DomU's eth1 lost its IP")
+    if not re.search("Loopback", run["output"]):
+        FAIL("DomU's lo disappeared")
+    if not re.search("127.0.0.1", run["output"]):
+        FAIL("DomU's lo lost its IP")
 
 except ConsoleError, e:
     FAIL(str(e))
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/save/02_save_badparm_neg.py
--- a/tools/xm-test/tests/save/02_save_badparm_neg.py   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/save/02_save_badparm_neg.py   Sat Nov 19 05:16:29 2005
@@ -21,5 +21,5 @@
     FAIL("xm save returned bad status, expected non 0, status is: %i" % status)
 elif where2 == 0:
     FAIL("xm save returned a stack dump, expected nice error message") 
-elif where1 > 0:
+elif where1 == -1:
     FAIL("xm save returned bad output, expected Error:, output is: %s" % 
output)
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/save/03_save_bogusfile_neg.py
--- a/tools/xm-test/tests/save/03_save_bogusfile_neg.py Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/save/03_save_bogusfile_neg.py Sat Nov 19 05:16:29 2005
@@ -38,5 +38,5 @@
     FAIL("xm save returned bad status, expected non 0, status is: %i" % status)
 elif where1 == 0:
     FAIL("xm save returned a stack dump, expected nice error message")
-elif where2 > 0:
+elif where2 == -1:
     FAIL("xm save returned bad output, expected Error:, output is: %s" % 
output)
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/shutdown/02_shutdown_badparm_neg.py
--- a/tools/xm-test/tests/shutdown/02_shutdown_badparm_neg.py   Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/shutdown/02_shutdown_badparm_neg.py   Sat Nov 19 
05:16:29 2005
@@ -32,7 +32,7 @@
 where = output.find(eyecatcher)
 if (ret == 0):
     FAIL("xm shutdown returned invalid %i == 0" % ret)
-elif where != 0:
+elif where == -1:
     FAIL("xm shutdown failed to report error for bad arg")
 
 # Stop the domain (nice shutdown)
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/shutdown/03_shutdown_nonexist_neg.py
--- a/tools/xm-test/tests/shutdown/03_shutdown_nonexist_neg.py  Sat Nov 19 
05:06:09 2005
+++ b/tools/xm-test/tests/shutdown/03_shutdown_nonexist_neg.py  Sat Nov 19 
05:16:29 2005
@@ -18,5 +18,5 @@
 where = output.find(eyecatcher)
 if (ret == 0):
     FAIL("xm shutdown returned invalid %i == 0" % ret)
-elif where != 0:
+elif where == -1:
     FAIL("xm shutdown failed to report error for bad domid")
diff -r e62c54ab862f -r 878a9891b056 xen/acm/acm_chinesewall_hooks.c
--- a/xen/acm/acm_chinesewall_hooks.c   Sat Nov 19 05:06:09 2005
+++ b/xen/acm/acm_chinesewall_hooks.c   Sat Nov 19 05:16:29 2005
@@ -117,8 +117,7 @@
 static void chwall_free_domain_ssid(void *chwall_ssid)
 {
     traceprintk("%s.\n", __func__);
-    if (chwall_ssid != NULL)
-        xfree(chwall_ssid);
+    xfree(chwall_ssid);
     return;
 }
 
@@ -344,14 +343,10 @@
     chwall_bin_pol.max_types = chwall_buf->chwall_max_types;
     chwall_bin_pol.max_ssidrefs = chwall_buf->chwall_max_ssidrefs;
     chwall_bin_pol.max_conflictsets = chwall_buf->chwall_max_conflictsets;
-    if (chwall_bin_pol.ssidrefs != NULL)
-        xfree(chwall_bin_pol.ssidrefs);
-    if (chwall_bin_pol.conflict_aggregate_set != NULL)
-        xfree(chwall_bin_pol.conflict_aggregate_set);
-    if (chwall_bin_pol.running_types != NULL)
-        xfree(chwall_bin_pol.running_types);
-    if (chwall_bin_pol.conflict_sets != NULL)
-        xfree(chwall_bin_pol.conflict_sets);
+    xfree(chwall_bin_pol.ssidrefs);
+    xfree(chwall_bin_pol.conflict_aggregate_set);
+    xfree(chwall_bin_pol.running_types);
+    xfree(chwall_bin_pol.conflict_sets);
     chwall_bin_pol.ssidrefs = ssids;
     chwall_bin_pol.conflict_aggregate_set = conflict_aggregate_set;
     chwall_bin_pol.running_types = running_types;
@@ -360,14 +355,10 @@
 
  error_free:
     printk("%s: ERROR setting policy.\n", __func__);
-    if (ssids != NULL)
-        xfree(ssids);
-    if (conflict_sets != NULL)
-        xfree(conflict_sets);
-    if (running_types != NULL)
-        xfree(running_types);
-    if (conflict_aggregate_set != NULL)
-        xfree(conflict_aggregate_set);
+    xfree(ssids);
+    xfree(conflict_sets);
+    xfree(running_types);
+    xfree(conflict_aggregate_set);
     return -EFAULT;
 }
 
diff -r e62c54ab862f -r 878a9891b056 xen/acm/acm_simple_type_enforcement_hooks.c
--- a/xen/acm/acm_simple_type_enforcement_hooks.c       Sat Nov 19 05:06:09 2005
+++ b/xen/acm/acm_simple_type_enforcement_hooks.c       Sat Nov 19 05:16:29 2005
@@ -130,8 +130,7 @@
 ste_free_domain_ssid(void *ste_ssid)
 {
     traceprintk("%s.\n", __func__);
-    if (ste_ssid != NULL)
-        xfree(ste_ssid);
+    xfree(ste_ssid);
     return;
 }
 
@@ -320,8 +319,7 @@
     /* 3. replace old policy (activate new policy) */
     ste_bin_pol.max_types = ste_buf->ste_max_types;
     ste_bin_pol.max_ssidrefs = ste_buf->ste_max_ssidrefs;
-    if (ste_bin_pol.ssidrefs) 
-        xfree(ste_bin_pol.ssidrefs);
+    xfree(ste_bin_pol.ssidrefs);
     ste_bin_pol.ssidrefs = (domaintype_t *)ssidrefsbuf;
 
     /* clear all ste caches */
@@ -338,7 +336,7 @@
 
  error_free:
     printk("%s: ERROR setting policy.\n", __func__);
-    if (ssidrefsbuf != NULL) xfree(ssidrefsbuf);
+    xfree(ssidrefsbuf);
     return -EFAULT;
 }
 
diff -r e62c54ab862f -r 878a9891b056 xen/arch/ia64/xen/domain.c
--- a/xen/arch/ia64/xen/domain.c        Sat Nov 19 05:06:09 2005
+++ b/xen/arch/ia64/xen/domain.c        Sat Nov 19 05:16:29 2005
@@ -908,7 +908,7 @@
        si = (start_info_t *)alloc_xenheap_page();
        memset(si, 0, PAGE_SIZE);
        d->shared_info->arch.start_info_pfn = __pa(si) >> PAGE_SHIFT;
-       sprintf(si->magic, "Xen-%i.%i", XEN_VERSION, XEN_SUBVERSION);
+       sprintf(si->magic, "xen-%i.%i-ia64", XEN_VERSION, XEN_SUBVERSION);
 
 #if 0
        si->nr_pages     = d->tot_pages;
diff -r e62c54ab862f -r 878a9891b056 xen/arch/ia64/xen/grant_table.c
--- a/xen/arch/ia64/xen/grant_table.c   Sat Nov 19 05:06:09 2005
+++ b/xen/arch/ia64/xen/grant_table.c   Sat Nov 19 05:16:29 2005
@@ -1348,8 +1348,7 @@
     if ( t != NULL )
     {
         xfree(t->active);
-        if ( t->maptrack != NULL )
-            free_xenheap_page(t->maptrack);
+        free_xenheap_page(t->maptrack);
         xfree(t);
     }
     return -ENOMEM;
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/dm/vmx_vioapic.c
--- a/xen/arch/x86/dm/vmx_vioapic.c     Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/dm/vmx_vioapic.c     Sat Nov 19 05:16:29 2005
@@ -158,6 +158,14 @@
     return result;
 }
 
+static void vmx_vioapic_update_imr(struct vmx_vioapic *s, int index)
+{
+   if (s->redirtbl[index].RedirForm.mask)
+       set_bit(index, &s->imr);
+   else
+       clear_bit(index, &s->imr);
+}
+
 static void vmx_vioapic_write_indirect(struct vmx_vioapic *s,
                                       unsigned long addr,
                                       unsigned long length,
@@ -200,6 +208,7 @@
                     redir_content = ((redir_content >> 32) << 32) |
                                     (val & 0xffffffff);
                 s->redirtbl[redir_index].value = redir_content;
+                vmx_vioapic_update_imr(s, redir_index);
             } else  {
                 printk("vmx_vioapic_write_indirect "
                   "error register %x\n", s->ioregsel);
@@ -264,8 +273,10 @@
 
     memset(s, 0, sizeof(vmx_vioapic_t));
 
-    for (i = 0; i < IOAPIC_NUM_PINS; i++)
+    for (i = 0; i < IOAPIC_NUM_PINS; i++) {
         s->redirtbl[i].RedirForm.mask = 0x1;
+        vmx_vioapic_update_imr(s, i);
+    }
 }
 
 static void ioapic_update_config(vmx_vioapic_t *s,
@@ -422,7 +433,13 @@
 
         target = apic_round_robin(
                 s->domain, dest_mode, vector, deliver_bitmask);
-        ioapic_inj_irq(s, target, vector, trig_mode, delivery_mode);
+        if (target)
+            ioapic_inj_irq(s, target, vector, trig_mode, delivery_mode);
+        else{
+            VMX_DBG_LOG(DBG_LEVEL_IOAPIC, "ioapic deliver "
+              "null round robin mask %x vector %x delivery_mode %x\n",
+              deliver_bitmask, vector, deliver_bitmask);
+        }
         break;
     }
 
@@ -457,7 +474,7 @@
 
     ASSERT(s);
 
-    irqs = s->irr & ~s->isr;
+    irqs = s->irr & ~s->isr & ~s->imr;
     return __fls(irqs);
 }
 
@@ -471,7 +488,7 @@
         VMX_DBG_LOG(DBG_LEVEL_IOAPIC, "service_ioapic "
           "highest irqno %x\n", irqno);
 
-        if (!s->redirtbl[irqno].RedirForm.mask) {
+        if (!test_bit(irqno, &s->imr)) {
             ioapic_deliver(s, irqno);
         }
 
@@ -490,7 +507,7 @@
     if (!vmx_apic_support(d))
         return;
 
-    s->irr |= irqs;
+    s->irr |= irqs & ~s->imr;
     service_ioapic(s);
 }
 
@@ -584,7 +601,9 @@
         domain_crash_synchronous();
     }
 
-    s->lapic_info[s->lapic_count ++] = vlapic;
+    /* update count later for race condition on interrupt */
+    s->lapic_info[s->lapic_count] = vlapic;
+    s->lapic_count ++;
 
     return s->lapic_count;
 }
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/domain.c
--- a/xen/arch/x86/domain.c     Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/domain.c     Sat Nov 19 05:16:29 2005
@@ -240,7 +240,10 @@
 
 void free_perdomain_pt(struct domain *d)
 {
-    free_xenheap_page(d->arch.mm_perdomain_pt);
+    free_xenheap_pages(
+        d->arch.mm_perdomain_pt,
+        get_order_from_bytes(PDPT_L1_ENTRIES * sizeof(l1_pgentry_t)));
+
 #ifdef __x86_64__
     free_xenheap_page(d->arch.mm_perdomain_l2);
     free_xenheap_page(d->arch.mm_perdomain_l3);
@@ -251,7 +254,10 @@
 {
     struct domain *d = v->domain;
     l1_pgentry_t gdt_l1e;
-    int vcpuid;
+    int vcpuid, pdpt_order;
+#ifdef __x86_64__
+    int i;
+#endif
 
     if ( is_idle_task(d) )
         return;
@@ -263,13 +269,10 @@
     v->vcpu_info = &d->shared_info->vcpu_data[v->vcpu_id];
     v->cpumap = CPUMAP_RUNANYWHERE;
     SHARE_PFN_WITH_DOMAIN(virt_to_page(d->shared_info), d);
-    set_pfn_from_mfn(virt_to_phys(d->shared_info) >> PAGE_SHIFT,
-            INVALID_M2P_ENTRY);
-
-    d->arch.mm_perdomain_pt = alloc_xenheap_page();
-    memset(d->arch.mm_perdomain_pt, 0, PAGE_SIZE);
-    set_pfn_from_mfn(virt_to_phys(d->arch.mm_perdomain_pt) >> PAGE_SHIFT,
-            INVALID_M2P_ENTRY);
+
+    pdpt_order = get_order_from_bytes(PDPT_L1_ENTRIES * sizeof(l1_pgentry_t));
+    d->arch.mm_perdomain_pt = alloc_xenheap_pages(pdpt_order);
+    memset(d->arch.mm_perdomain_pt, 0, PAGE_SIZE << pdpt_order);
     v->arch.perdomain_ptes = d->arch.mm_perdomain_pt;
 
     /*
@@ -293,9 +296,11 @@
 
     d->arch.mm_perdomain_l2 = alloc_xenheap_page();
     memset(d->arch.mm_perdomain_l2, 0, PAGE_SIZE);
-    d->arch.mm_perdomain_l2[l2_table_offset(PERDOMAIN_VIRT_START)] =
-        l2e_from_page(virt_to_page(d->arch.mm_perdomain_pt),
-                        __PAGE_HYPERVISOR);
+    for ( i = 0; i < (1 << pdpt_order); i++ )
+        d->arch.mm_perdomain_l2[l2_table_offset(PERDOMAIN_VIRT_START)+i] =
+            l2e_from_page(virt_to_page(d->arch.mm_perdomain_pt)+i,
+                          __PAGE_HYPERVISOR);
+
     d->arch.mm_perdomain_l3 = alloc_xenheap_page();
     memset(d->arch.mm_perdomain_l3, 0, PAGE_SIZE);
     d->arch.mm_perdomain_l3[l3_table_offset(PERDOMAIN_VIRT_START)] =
@@ -407,6 +412,7 @@
         /* VMX uses the initially provided page tables as the P2M map. */
         if ( !pagetable_get_paddr(d->arch.phys_table) )
             d->arch.phys_table = v->arch.guest_table;
+        v->arch.guest_table = mk_pagetable(0);
 
         /* Initialize monitor page table */
         v->arch.monitor_table = mk_pagetable(0);
@@ -577,7 +583,7 @@
              put_user(regs->rcx,           rsp-11) )
         {
             DPRINTK("Error while creating failsafe callback frame.\n");
-            domain_crash();
+            domain_crash(n->domain);
         }
 
         regs->entry_vector  = TRAP_syscall;
@@ -646,7 +652,7 @@
 
     regs->rip    = stu.rip;
     regs->cs     = stu.cs | 3; /* force guest privilege */
-    regs->rflags = stu.rflags;
+    regs->rflags = (stu.rflags & ~(EF_IOPL|EF_VM)) | EF_IE;
     regs->rsp    = stu.rsp;
     regs->ss     = stu.ss | 3; /* force guest privilege */
 
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/domain_build.c
--- a/xen/arch/x86/domain_build.c       Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/domain_build.c       Sat Nov 19 05:16:29 2005
@@ -639,7 +639,8 @@
     si->pt_base      = vpt_start;
     si->nr_pt_frames = nr_pt_pages;
     si->mfn_list     = vphysmap_start;
-    sprintf(si->magic, "Xen-%i.%i", XEN_VERSION, XEN_SUBVERSION);
+    sprintf(si->magic, "xen-%i.%i-x86_%d%s",
+            XEN_VERSION, XEN_SUBVERSION, BITS_PER_LONG, xen_pae ? "p" : "");
 
     /* Write the phys->machine and machine->phys table entries. */
     for ( pfn = 0; pfn < d->tot_pages; pfn++ )
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/mm.c
--- a/xen/arch/x86/mm.c Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/mm.c Sat Nov 19 05:16:29 2005
@@ -738,7 +738,7 @@
     memcpy(&pl2e[L2_PAGETABLE_FIRST_XEN_SLOT & (L2_PAGETABLE_ENTRIES-1)],
            &idle_pg_table_l2[L2_PAGETABLE_FIRST_XEN_SLOT],
            L2_PAGETABLE_XEN_SLOTS * sizeof(l2_pgentry_t));
-    for ( i = 0; i < (PERDOMAIN_MBYTES >> (L2_PAGETABLE_SHIFT - 20)); i++ )
+    for ( i = 0; i < PDPT_L2_ENTRIES; i++ )
         pl2e[l2_table_offset(PERDOMAIN_VIRT_START) + i] =
             l2e_from_page(
                 virt_to_page(page_get_owner(page)->arch.mm_perdomain_pt) + i,
@@ -898,6 +898,7 @@
     return 1;
 
  fail:
+    MEM_LOG("Failure in alloc_l3_table: entry %d", i);
     while ( i-- > 0 )
         if ( is_guest_l3_slot(i) )
             put_page_from_l3e(pl3e[i], pfn);
@@ -948,6 +949,7 @@
     return 1;
 
  fail:
+    MEM_LOG("Failure in alloc_l4_table: entry %d", i);
     while ( i-- > 0 )
         if ( is_guest_l4_slot(i) )
             put_page_from_l4e(pl4e[i], pfn);
@@ -1461,6 +1463,22 @@
             {
                 if ( unlikely((x & PGT_type_mask) != (type & PGT_type_mask) ) )
                 {
+                    if ( current->domain == page_get_owner(page) )
+                    {
+                        /*
+                         * This ensures functions like set_gdt() see up-to-date
+                         * type info without needing to clean up writable p.t.
+                         * state on the fast path.
+                         */
+                        LOCK_BIGLOCK(current->domain);
+                        cleanup_writable_pagetable(current->domain);
+                        y = page->u.inuse.type_info;
+                        UNLOCK_BIGLOCK(current->domain);
+                        /* Can we make progress now? */
+                        if ( ((y & PGT_type_mask) == (type & PGT_type_mask)) ||
+                             ((y & PGT_count_mask) == 0) )
+                            goto again;
+                    }
                     if ( ((x & PGT_type_mask) != PGT_l2_page_table) ||
                          ((type & PGT_type_mask) != PGT_l1_page_table) )
                         MEM_LOG("Bad type (saw %" PRtype_info
@@ -2529,7 +2547,7 @@
              * not enough information in just a gpte to figure out how to
              * (re-)shadow this entry.
              */
-            domain_crash();
+            domain_crash(d);
         }
     
         rc = shadow_do_update_va_mapping(va, val, v);
@@ -2918,7 +2936,6 @@
 {
     l1_pgentry_t ol1e, nl1e;
     int modified = 0, i;
-    struct vcpu *v;
 
     for ( i = 0; i < L1_PAGETABLE_ENTRIES; i++ )
     {
@@ -2944,7 +2961,6 @@
 
         if ( unlikely(!get_page_from_l1e(nl1e, d)) )
         {
-            MEM_LOG("ptwr: Could not re-validate l1 page");
             /*
              * Make the remaining p.t's consistent before crashing, so the
              * reference counts are correct.
@@ -2953,9 +2969,8 @@
                    (L1_PAGETABLE_ENTRIES - i) * sizeof(l1_pgentry_t));
 
             /* Crash the offending domain. */
-            set_bit(_DOMF_ctrl_pause, &d->domain_flags);
-            for_each_vcpu ( d, v )
-                vcpu_sleep_nosync(v);
+            MEM_LOG("ptwr: Could not revalidate l1 page");
+            domain_crash(d);
             break;
         }
         
@@ -3066,7 +3081,7 @@
     unsigned int bytes,
     unsigned int do_cmpxchg)
 {
-    unsigned long pfn;
+    unsigned long pfn, l1va;
     struct pfn_info *page;
     l1_pgentry_t pte, ol1e, nl1e, *pl1e;
     struct domain *d = current->domain;
@@ -3103,6 +3118,17 @@
         old  |= full;
     }
 
+    /*
+     * We must not emulate an update to a PTE that is temporarily marked
+     * writable by the batched ptwr logic, else we can corrupt page refcnts! 
+     */
+    if ( ((l1va = d->arch.ptwr[PTWR_PT_ACTIVE].l1va) != 0) &&
+         (l1_linear_offset(l1va) == l1_linear_offset(addr)) )
+        ptwr_flush(d, PTWR_PT_ACTIVE);
+    if ( ((l1va = d->arch.ptwr[PTWR_PT_INACTIVE].l1va) != 0) &&
+         (l1_linear_offset(l1va) == l1_linear_offset(addr)) )
+        ptwr_flush(d, PTWR_PT_INACTIVE);
+
     /* Read the PTE that maps the page being updated. */
     if (__copy_from_user(&pte, &linear_pg_table[l1_linear_offset(addr)],
                          sizeof(pte)))
@@ -3128,7 +3154,10 @@
     /* Check the new PTE. */
     nl1e = l1e_from_intpte(val);
     if ( unlikely(!get_page_from_l1e(nl1e, d)) )
+    {
+        MEM_LOG("ptwr_emulate: could not get_page_from_l1e()");
         return X86EMUL_UNHANDLEABLE;
+    }
 
     /* Checked successfully: do the update (write or cmpxchg). */
     pl1e = map_domain_page(page_to_pfn(page));
@@ -3251,6 +3280,9 @@
     goto emulate; 
 #endif
 
+    PTWR_PRINTK("ptwr_page_fault on l1 pt at va %lx, pfn %lx, eip %lx\n",
+                addr, pfn, (unsigned long)regs->eip);
+    
     /* Get the L2 index at which this L1 p.t. is always mapped. */
     l2_idx = page->u.inuse.type_info & PGT_va_mask;
     if ( unlikely(l2_idx >= PGT_va_unknown) )
@@ -3295,10 +3327,6 @@
         goto emulate;
     }
 
-    PTWR_PRINTK("[%c] page_fault on l1 pt at va %lx, pt for %08lx, "
-                "pfn %lx\n", PTWR_PRINT_WHICH,
-                addr, l2_idx << L2_PAGETABLE_SHIFT, pfn);
-    
     /*
      * We only allow one ACTIVE and one INACTIVE p.t. to be updated at at 
      * time. If there is already one, we must flush it out.
@@ -3316,6 +3344,10 @@
         d->arch.ptwr[which].prev_nr_updates = 1;
         goto emulate;
     }
+
+    PTWR_PRINTK("[%c] batched ptwr_page_fault at va %lx, pt for %08lx, "
+                "pfn %lx\n", PTWR_PRINT_WHICH, addr,
+                l2_idx << L2_PAGETABLE_SHIFT, pfn);
 
     d->arch.ptwr[which].l1va   = addr | 1;
     d->arch.ptwr[which].l2_idx = l2_idx;
@@ -3348,7 +3380,7 @@
         /* Toss the writable pagetable state and crash. */
         unmap_domain_page(d->arch.ptwr[which].pl1e);
         d->arch.ptwr[which].l1va = 0;
-        domain_crash();
+        domain_crash(d);
         return 0;
     }
     
@@ -3369,10 +3401,8 @@
 
     if ( (x == NULL) || (y == NULL) )
     {
-        if ( x != NULL )
-            free_xenheap_page(x);
-        if ( y != NULL )
-            free_xenheap_page(y);
+        free_xenheap_page(x);
+        free_xenheap_page(y);
         return -ENOMEM;
     }
 
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/mtrr/generic.c
--- a/xen/arch/x86/mtrr/generic.c       Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/mtrr/generic.c       Sat Nov 19 05:16:29 2005
@@ -71,8 +71,7 @@
 /*  Free resources associated with a struct mtrr_state  */
 void __init finalize_mtrr_state(void)
 {
-       if (mtrr_state.var_ranges)
-               xfree(mtrr_state.var_ranges);
+       xfree(mtrr_state.var_ranges);
        mtrr_state.var_ranges = NULL;
 }
 
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/nmi.c
--- a/xen/arch/x86/nmi.c        Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/nmi.c        Sat Nov 19 05:16:29 2005
@@ -49,8 +49,6 @@
 #define P6_EVENT_CPU_CLOCKS_NOT_HALTED 0x79
 #define P6_NMI_EVENT           P6_EVENT_CPU_CLOCKS_NOT_HALTED
 
-#define MSR_P4_PERFCTR0                0x300
-#define MSR_P4_CCCR0           0x360
 #define P4_ESCR_EVENT_SELECT(N)        ((N)<<25)
 #define P4_CCCR_OVF_PMI0       (1<<26)
 #define P4_CCCR_OVF_PMI1       (1<<27)
@@ -61,13 +59,10 @@
 #define P4_CCCR_ESCR_SELECT(N) ((N)<<13)
 #define P4_CCCR_ENABLE         (1<<12)
 /* 
- * Set up IQ_COUNTER0 to behave like a clock, by having IQ_CCCR0 filter
+ * Set up IQ_PERFCTR0 to behave like a clock, by having IQ_CCCR0 filter
  * CRU_ESCR0 (with any non-null event selector) through a complemented
  * max threshold. [IA32-Vol3, Section 14.9.9] 
  */
-#define MSR_P4_IQ_COUNTER0     0x30C
-#define MSR_P4_IQ_CCCR0                0x36C
-#define MSR_P4_CRU_ESCR0       0x3B8 /* ESCR no. 4 */
 #define P4_NMI_CRU_ESCR0       P4_ESCR_EVENT_SELECT(0x3F)
 #define P4_NMI_IQ_CCCR0        \
     (P4_CCCR_OVF_PMI0|P4_CCCR_THRESHOLD(15)|P4_CCCR_COMPLEMENT| \
@@ -183,7 +178,7 @@
     if (!(misc_enable & MSR_IA32_MISC_ENABLE_PERF_AVAIL))
         return 0;
 
-    nmi_perfctr_msr = MSR_P4_IQ_COUNTER0;
+    nmi_perfctr_msr = MSR_P4_IQ_PERFCTR0;
     nmi_p4_cccr_val = P4_NMI_IQ_CCCR0;
     if ( smp_num_siblings == 2 )
         nmi_p4_cccr_val |= P4_CCCR_OVF_PMI1;
@@ -196,13 +191,13 @@
     clear_msr_range(0x3C0, 6);
     clear_msr_range(0x3C8, 6);
     clear_msr_range(0x3E0, 2);
-    clear_msr_range(MSR_P4_CCCR0, 18);
-    clear_msr_range(MSR_P4_PERFCTR0, 18);
+    clear_msr_range(MSR_P4_BPU_CCCR0, 18);
+    clear_msr_range(MSR_P4_BPU_PERFCTR0, 18);
         
     wrmsr(MSR_P4_CRU_ESCR0, P4_NMI_CRU_ESCR0, 0);
     wrmsr(MSR_P4_IQ_CCCR0, P4_NMI_IQ_CCCR0 & ~P4_CCCR_ENABLE, 0);
-    Dprintk("setting P4_IQ_COUNTER0 to 0x%08lx\n", -(cpu_khz/nmi_hz*1000));
-    wrmsr(MSR_P4_IQ_COUNTER0, -(cpu_khz/nmi_hz*1000), -1);
+    Dprintk("setting P4_IQ_PERFCTR0 to 0x%08lx\n", -(cpu_khz/nmi_hz*1000));
+    wrmsr(MSR_P4_IQ_PERFCTR0, -(cpu_khz/nmi_hz*1000), -1);
     apic_write(APIC_LVTPC, APIC_DM_NMI);
     wrmsr(MSR_P4_IQ_CCCR0, nmi_p4_cccr_val, 0);
 
@@ -314,7 +309,7 @@
 
     if ( nmi_perfctr_msr )
     {
-        if ( nmi_perfctr_msr == MSR_P4_IQ_COUNTER0 )
+        if ( nmi_perfctr_msr == MSR_P4_IQ_PERFCTR0 )
         {
             /*
              * P4 quirks:
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/setup.c
--- a/xen/arch/x86/setup.c      Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/setup.c      Sat Nov 19 05:16:29 2005
@@ -430,6 +430,10 @@
     /* Sanity check for unwanted bloat of dom0_op_t structure. */
     BUG_ON(sizeof(((dom0_op_t *)0)->u) != sizeof(((dom0_op_t *)0)->u.pad));
 
+    BUG_ON(sizeof(start_info_t) > PAGE_SIZE);
+    BUG_ON(sizeof(shared_info_t) > PAGE_SIZE);
+    BUG_ON(sizeof(vcpu_info_t) != (sizeof(unsigned long) * 4));
+
     init_frametable();
 
     end_boot_allocator();
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/shadow.c
--- a/xen/arch/x86/shadow.c     Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/shadow.c     Sat Nov 19 05:16:29 2005
@@ -22,7 +22,7 @@
  * Jun Nakajima <jun.nakajima@xxxxxxxxx>
  * Chengyuan Li <chengyuan.li@xxxxxxxxx>
  *
- * Extended to support 64-bit guests.
+ * Extended to support 32-bit PAE and 64-bit guests.
  */
 
 #include <xen/config.h>
@@ -34,6 +34,7 @@
 #include <xen/event.h>
 #include <xen/sched.h>
 #include <xen/trace.h>
+#include <asm/shadow_64.h>
 
 extern void free_shadow_pages(struct domain *d);
 
@@ -44,13 +45,13 @@
 #endif
 
 #if CONFIG_PAGING_LEVELS == 3
-#include <asm/shadow_64.h>
 static unsigned long shadow_l3_table(
     struct domain *d, unsigned long gpfn, unsigned long gmfn);
+static inline void validate_bl2e_change( struct domain *d,
+    guest_root_pgentry_t *new_gle_p, pgentry_64_t *shadow_l3, int index);
 #endif
 
 #if CONFIG_PAGING_LEVELS == 4
-#include <asm/shadow_64.h>
 static unsigned long shadow_l4_table(
     struct domain *d, unsigned long gpfn, unsigned long gmfn);
 static void shadow_map_into_current(struct vcpu *v,
@@ -222,7 +223,7 @@
         {
             if (d->arch.ops->guest_paging_levels == PAGING_L2)
             {
-#if CONFIG_PAGING_LEVELS >= 4
+#if CONFIG_PAGING_LEVELS >= 3
                 /* For 32-bit VMX guest, 2 shadow L1s to simulate 1 guest L1
                  * So need allocate 2 continues shadow L1 each time.
                  */
@@ -313,6 +314,8 @@
             goto fail;
         perfc_incr(shadow_l3_pages);
         d->arch.shadow_page_count++;
+        if ( PGT_l3_page_table == PGT_root_page_table )
+            pin = 1;
         break;
 
     case PGT_l4_shadow:
@@ -375,7 +378,7 @@
     {
         if (d->arch.ops->guest_paging_levels == PAGING_L2)
         {
-#if CONFIG_PAGING_LEVELS >=4
+#if CONFIG_PAGING_LEVELS >=3
             free_domheap_pages(page, SL1_ORDER);
 #else
             free_domheap_page(page);
@@ -427,14 +430,10 @@
 
     hl2 = map_domain_page(hl2mfn);
 
-#ifdef __i386__
     if ( shadow_mode_external(d) )
         limit = L2_PAGETABLE_ENTRIES;
     else
         limit = DOMAIN_ENTRIES_PER_L2_PAGETABLE;
-#else
-    limit = 0; /* XXX x86/64 XXX */
-#endif
 
     memset(hl2, 0, limit * sizeof(l1_pgentry_t));
 
@@ -540,7 +539,7 @@
     SH_VLOG("shadow_l2_table(%lx -> %lx)", gmfn, smfn);
     return smfn;
 }
-#endif
+#endif /* CONFIG_PAGING_LEVELS == 2 */
 
 static void shadow_map_l1_into_current_l2(unsigned long va)
 {
@@ -549,7 +548,7 @@
     l1_pgentry_t *spl1e;
     l2_pgentry_t sl2e;
     guest_l1_pgentry_t *gpl1e;
-    guest_l2_pgentry_t gl2e;
+    guest_l2_pgentry_t gl2e = {0};
     unsigned long gl1pfn, gl1mfn, sl1mfn;
     int i, init_table = 0;
 
@@ -593,14 +592,14 @@
     ASSERT( !(l2e_get_flags(old_sl2e) & _PAGE_PRESENT) );
 #endif
 
-#if CONFIG_PAGING_LEVELS >=4
+#if CONFIG_PAGING_LEVELS >=3
     if (d->arch.ops->guest_paging_levels == PAGING_L2)
     {
-        /* for 32-bit VMX guest on 64-bit host,
+        /* for 32-bit VMX guest on 64-bit or PAE host,
          * need update two L2 entries each time
          */
         if ( !get_shadow_ref(sl1mfn))
-                BUG();
+            BUG();
         l2pde_general(d, &gl2e, &sl2e, sl1mfn);
         __guest_set_l2e(v, va, &gl2e);
         __shadow_set_l2e(v, va & ~((1<<L2_PAGETABLE_SHIFT_32) - 1), &sl2e);
@@ -625,19 +624,17 @@
         int index = guest_l1_table_offset(va);
         int min = 1, max = 0;
 
-        unsigned long entries, pt_va;
-        l1_pgentry_t tmp_sl1e;
-        guest_l1_pgentry_t tmp_gl1e;//Prepare for double compile
-
-
-        entries = PAGE_SIZE / sizeof(guest_l1_pgentry_t);
-        pt_va = ((va >> L1_PAGETABLE_SHIFT) & ~(entries - 1)) << 
L1_PAGETABLE_SHIFT;
-        gpl1e = (guest_l1_pgentry_t *) __guest_get_l1e(v, pt_va, &tmp_gl1e);
+        unsigned long tmp_gmfn;
+        l2_pgentry_t tmp_sl2e = {0};
+        guest_l2_pgentry_t tmp_gl2e = {0};
+
+        __guest_get_l2e(v, va, &tmp_gl2e);
+        tmp_gmfn = __gpfn_to_mfn(d, l2e_get_pfn(tmp_gl2e));
+        gpl1e = (guest_l1_pgentry_t *) map_domain_page(tmp_gmfn);
 
         /* If the PGT_l1_shadow has two continual pages */
-        entries = PAGE_SIZE / sizeof(guest_l1_pgentry_t); //1024 entry!!!
-        pt_va = ((va >> L1_PAGETABLE_SHIFT) & ~(entries - 1)) << 
L1_PAGETABLE_SHIFT;
-        spl1e = (l1_pgentry_t *) __shadow_get_l1e(v, pt_va, &tmp_sl1e);
+        __shadow_get_l2e(v, va, &tmp_sl2e);
+        spl1e = (l1_pgentry_t *) map_domain_page(l2e_get_pfn(tmp_sl2e));
 
         for ( i = 0; i < GUEST_L1_PAGETABLE_ENTRIES; i++ )
         {
@@ -662,10 +659,13 @@
             if ( likely(i > max) )
                 max = i;
             set_guest_back_ptr(d, sl1e, sl1mfn, i);
-          }
+        }
 
         frame_table[sl1mfn].tlbflush_timestamp =
             SHADOW_ENCODE_MIN_MAX(min, max);
+
+        unmap_domain_page(gpl1e);
+        unmap_domain_page(spl1e);
     }
 }
 
@@ -674,7 +674,7 @@
 {
     struct vcpu *v = current;
     struct domain *d = v->domain;
-    l2_pgentry_t sl2e;
+    l2_pgentry_t sl2e = {0};
 
     __shadow_get_l2e(v, va, &sl2e);
     if ( !(l2e_get_flags(sl2e) & _PAGE_PRESENT) )
@@ -690,11 +690,23 @@
         }
         else /* check to see if it exists; if so, link it in */
         {
-            l2_pgentry_t gpde = linear_l2_table(v)[l2_table_offset(va)];
-            unsigned long gl1pfn = l2e_get_pfn(gpde);
-            unsigned long sl1mfn = __shadow_status(d, gl1pfn, PGT_l1_shadow);
-
-            ASSERT( l2e_get_flags(gpde) & _PAGE_PRESENT );
+            l2_pgentry_t gpde = {0};
+            unsigned long gl1pfn;
+            unsigned long sl1mfn;
+
+            __guest_get_l2e(v, va, &gpde);
+
+            if ( l2e_get_flags(gpde) & _PAGE_PRESENT )
+            {
+                gl1pfn = l2e_get_pfn(gpde);
+                sl1mfn = __shadow_status(d, gl1pfn, PGT_l1_shadow);
+            }
+            else
+            {
+                // no shadow exists, so there's nothing to do.
+                perfc_incrc(shadow_set_l1e_fail);
+                return;
+            }
 
             if ( sl1mfn )
             {
@@ -738,7 +750,7 @@
     shadow_update_min_max(l2e_get_pfn(sl2e), l1_table_offset(va));
 }
 
-#if CONFIG_PAGING_LEVELS <= 3
+#if CONFIG_PAGING_LEVELS == 2
 static void shadow_invlpg_32(struct vcpu *v, unsigned long va)
 {
     struct domain *d = v->domain;
@@ -767,7 +779,7 @@
 
     shadow_unlock(d);
 }
-#endif
+#endif /* CONFIG_PAGING_LEVELS == 2 */
 
 static struct out_of_sync_entry *
 shadow_alloc_oos_entry(struct domain *d)
@@ -861,7 +873,7 @@
 }
 
 static struct out_of_sync_entry *
-mark_mfn_out_of_sync(struct vcpu *v, unsigned long gpfn,
+__mark_mfn_out_of_sync(struct vcpu *v, unsigned long gpfn,
                              unsigned long mfn)
 {
     struct domain *d = v->domain;
@@ -897,7 +909,6 @@
     entry->v = v;
     entry->gpfn = gpfn;
     entry->gmfn = mfn;
-    entry->snapshot_mfn = shadow_make_snapshot(d, gpfn, mfn);
     entry->writable_pl1e = -1;
 
 #if 0 // this code has not been updated for 32pae & 64 bit modes
@@ -911,20 +922,34 @@
     //
     get_page(page, d);
 
+    return entry;
+}
+
+static struct out_of_sync_entry *
+mark_mfn_out_of_sync(struct vcpu *v, unsigned long gpfn,
+                             unsigned long mfn)
+{
+    struct out_of_sync_entry *entry =
+        __mark_mfn_out_of_sync(v, gpfn, mfn);
+    struct domain *d = v->domain;
+
+    entry->snapshot_mfn = shadow_make_snapshot(d, gpfn, mfn);
     // Add to the out-of-sync list
     //
     entry->next = d->arch.out_of_sync;
     d->arch.out_of_sync = entry;
 
     return entry;
+
 }
 
 static void shadow_mark_va_out_of_sync(
     struct vcpu *v, unsigned long gpfn, unsigned long mfn, unsigned long va)
 {
     struct out_of_sync_entry *entry =
-        shadow_mark_mfn_out_of_sync(v, gpfn, mfn);
+        __mark_mfn_out_of_sync(v, gpfn, mfn);
     l2_pgentry_t sl2e;
+    struct domain *d = v->domain;
 
 #if CONFIG_PAGING_LEVELS >= 4
     {
@@ -959,6 +984,7 @@
     }
     ASSERT(l2e_get_flags(sl2e) & _PAGE_PRESENT);
 
+    entry->snapshot_mfn = shadow_make_snapshot(d, gpfn, mfn);
     // NB: this is stored as a machine address.
     entry->writable_pl1e =
         l2e_get_paddr(sl2e) | (sizeof(l1_pgentry_t) * l1_table_offset(va));
@@ -970,6 +996,11 @@
     //
     if ( !get_shadow_ref(l2e_get_pfn(sl2e)) )
         BUG();
+
+    // Add to the out-of-sync list
+    //
+    entry->next = d->arch.out_of_sync;
+    d->arch.out_of_sync = entry;
 
     FSH_LOG("mark_out_of_sync(va=%lx -> writable_pl1e=%lx)",
             va, entry->writable_pl1e);
@@ -996,7 +1027,10 @@
 
     if (__copy_from_user(&gpte, &guest_pt[index],
                          sizeof(gpte)))
+    {
+        unmap_domain_page(snapshot);
         return 0;
+    }
 
     // This could probably be smarter, but this is sufficent for
     // our current needs.
@@ -1021,7 +1055,7 @@
 static int is_out_of_sync(struct vcpu *v, unsigned long va) /* 
__shadow_out_of_sync */
 {
     struct domain *d = v->domain;
-#if defined (__x86_64__)
+#if CONFIG_PAGING_LEVELS == 4
     unsigned long l2mfn = ((v->arch.flags & TF_kernel_mode)?
                           pagetable_get_pfn(v->arch.guest_table) :
                           pagetable_get_pfn(v->arch.guest_table_user));
@@ -1032,16 +1066,21 @@
     guest_l2_pgentry_t l2e;
     unsigned long l1pfn, l1mfn;
     guest_l1_pgentry_t *guest_pt;
-    guest_l1_pgentry_t tmp_gle;
-    unsigned long pt_va;
 
     ASSERT(shadow_lock_is_acquired(d));
     ASSERT(VALID_M2P(l2pfn));
 
     perfc_incrc(shadow_out_of_sync_calls);
 
-#if CONFIG_PAGING_LEVELS >= 4
-    if (d->arch.ops->guest_paging_levels == PAGING_L4) { /* Mode F */
+#if CONFIG_PAGING_LEVELS >= 3
+
+#define unmap_and_return(x)                                         \
+    if ( guest_pt != (guest_l1_pgentry_t *) v->arch.guest_vtable )  \
+        unmap_domain_page(guest_pt);                                \
+    return (x);
+
+    if (d->arch.ops->guest_paging_levels >= PAGING_L3) 
+    { 
         pgentry_64_t le;
         unsigned long gmfn;
         unsigned long gpfn;
@@ -1051,37 +1090,57 @@
         gpfn = l2pfn;
         guest_pt = (guest_l1_pgentry_t *)v->arch.guest_vtable;
 
-        for (i = PAGING_L4; i >= PAGING_L3; i--) {
+        for ( i = PAGING_L4; i >= PAGING_L3; i-- ) 
+        {
+            if (d->arch.ops->guest_paging_levels == PAGING_L3 
+                && i == PAGING_L4)
+                continue;       /* skip the top-level for 3-level */
+
             if ( page_out_of_sync(&frame_table[gmfn]) &&
-              !snapshot_entry_matches(
-                  d, guest_pt, gpfn, table_offset_64(va, i)) )
-                return 1;
-
+                 !snapshot_entry_matches(
+                     d, guest_pt, gpfn, table_offset_64(va, i)) )
+            {
+                unmap_and_return (1);
+            }
+
+            le = entry_empty();
             __rw_entry(v, va, &le, GUEST_ENTRY | GET_ENTRY | i);
+
             if ( !(entry_get_flags(le) & _PAGE_PRESENT) )
-                return 0;
+            {
+                unmap_and_return (0);
+            }
             gpfn = entry_get_pfn(le);
             gmfn = __gpfn_to_mfn(d, gpfn);
             if ( !VALID_MFN(gmfn) )
-                return 0;
-            /* Todo: check!*/
+            {
+                unmap_and_return (0);
+            }
+            if ( guest_pt != (guest_l1_pgentry_t *)v->arch.guest_vtable )
+                unmap_domain_page(guest_pt);
             guest_pt = (guest_l1_pgentry_t *)map_domain_page(gmfn);
-
         }
 
         /* L2 */
         if ( page_out_of_sync(&frame_table[gmfn]) &&
              !snapshot_entry_matches(d, guest_pt, gpfn, l2_table_offset(va)) )
+        {
+            unmap_and_return (1);
+        }
+
+        if ( guest_pt != (guest_l1_pgentry_t *)v->arch.guest_vtable )
+            unmap_domain_page(guest_pt);
+
+    } 
+    else
+#undef unmap_and_return
+#endif /* CONFIG_PAGING_LEVELS >= 3 */
+    {
+        if ( page_out_of_sync(&frame_table[l2mfn]) &&
+             !snapshot_entry_matches(d, (guest_l1_pgentry_t 
*)v->arch.guest_vtable,
+                                     l2pfn, guest_l2_table_offset(va)) )
             return 1;
-
-
-    } else
-#endif
-
-    if ( page_out_of_sync(&frame_table[l2mfn]) &&
-         !snapshot_entry_matches(d, (guest_l1_pgentry_t *)v->arch.guest_vtable,
-                                 l2pfn, guest_l2_table_offset(va)) )
-        return 1;
+    }
 
     __guest_get_l2e(v, va, &l2e);
     if ( !(guest_l2e_get_flags(l2e) & _PAGE_PRESENT) ||
@@ -1095,15 +1154,17 @@
     if ( !VALID_MFN(l1mfn) )
         return 0;
 
-    pt_va = ((va >> L1_PAGETABLE_SHIFT) & ~(GUEST_L1_PAGETABLE_ENTRIES - 1))
-      << L1_PAGETABLE_SHIFT;
-    guest_pt = (guest_l1_pgentry_t *) __guest_get_l1e(v, pt_va, &tmp_gle);
+    guest_pt = (guest_l1_pgentry_t *) map_domain_page(l1mfn);
 
     if ( page_out_of_sync(&frame_table[l1mfn]) &&
          !snapshot_entry_matches(
-             d, guest_pt, l1pfn, guest_l1_table_offset(va)) )
+             d, guest_pt, l1pfn, guest_l1_table_offset(va)) ) 
+    {
+        unmap_domain_page(guest_pt);
         return 1;
-
+    }
+
+    unmap_domain_page(guest_pt);
     return 0;
 }
 
@@ -1257,7 +1318,7 @@
     }
 
     if ( shadow_mode_external(d) ) {
-        if (write_refs-- == 0)
+        if (--write_refs == 0)
             return 0;
 
          // Use the back pointer to locate the shadow page that can contain
@@ -1314,6 +1375,8 @@
 
     for ( entry = d->arch.out_of_sync; entry; entry = entry->next)
     {
+        int max = -1;
+
         if ( entry->snapshot_mfn == SHADOW_SNAPSHOT_ELSEWHERE )
             continue;
 
@@ -1335,7 +1398,7 @@
                 continue;
         }
 
-        FSH_LOG("resyncing t=%08x gpfn=%lx gmfn=%lx smfn=%lx snapshot_mfn=%lx",
+       FSH_LOG("resyncing t=%08x gpfn=%lx gmfn=%lx smfn=%lx snapshot_mfn=%lx",
                 stype, entry->gpfn, entry->gmfn, smfn, entry->snapshot_mfn);
 
         // Compare guest's new contents to its snapshot, validating
@@ -1373,10 +1436,8 @@
 
             if ( !shadow_mode_refcounts(d) )
                 revalidate_l1(d, (l1_pgentry_t *)guest1, (l1_pgentry_t 
*)snapshot1);
-
             if ( !smfn )
                 break;
-
 
             changed = 0;
 
@@ -1405,12 +1466,13 @@
             perfc_incrc(resync_l1);
             perfc_incr_histo(wpt_updates, changed, PT_UPDATES);
             perfc_incr_histo(l1_entries_checked, max_shadow - min_shadow + 1, 
PT_UPDATES);
-            if ( d->arch.ops->guest_paging_levels == PAGING_L4 &&
+            if ( d->arch.ops->guest_paging_levels >= PAGING_L3 &&
                  unshadow_l1 ) {
-                pgentry_64_t l2e;
+                pgentry_64_t l2e = {0};
 
                 __shadow_get_l2e(entry->v, entry->va, &l2e);
-                if (entry_get_flags(l2e) & _PAGE_PRESENT) {
+
+                if ( entry_get_flags(l2e) & _PAGE_PRESENT ) {
                     entry_remove_flags(l2e, _PAGE_PRESENT);
                     __shadow_set_l2e(entry->v, entry->va, &l2e);
 
@@ -1421,11 +1483,9 @@
 
             break;
         }
-#if defined (__i386__)
+#if CONFIG_PAGING_LEVELS == 2
         case PGT_l2_shadow:
         {
-            int max = -1;
-
             l2_pgentry_t *guest2 = guest;
             l2_pgentry_t *shadow2 = shadow;
             l2_pgentry_t *snapshot2 = snapshot;
@@ -1436,9 +1496,6 @@
             changed = 0;
             for ( i = 0; i < L2_PAGETABLE_ENTRIES; i++ )
             {
-#if CONFIG_X86_PAE
-                BUG();  /* FIXME: need type_info */
-#endif
                 if ( !is_guest_l2_slot(0,i) && !external )
                     continue;
 
@@ -1482,9 +1539,6 @@
             changed = 0;
             for ( i = 0; i < L2_PAGETABLE_ENTRIES; i++ )
             {
-#if CONFIG_X86_PAE
-                BUG();  /* FIXME: need type_info */
-#endif
                 if ( !is_guest_l2_slot(0, i) && !external )
                     continue;
 
@@ -1505,7 +1559,7 @@
             perfc_incr_histo(shm_hl2_updates, changed, PT_UPDATES);
             break;
         }
-#else
+#elif CONFIG_PAGING_LEVELS >= 3
         case PGT_l2_shadow:
         case PGT_l3_shadow:
         {
@@ -1521,19 +1575,35 @@
                       guest_pt[i], snapshot_pt[i], PAGE_FLAG_MASK) )
                 {
                     need_flush |= validate_entry_change(
-                      d, &guest_pt[i], &shadow_pt[i],
-                      shadow_type_to_level(stype));
+                        d, &guest_pt[i], &shadow_pt[i],
+                        shadow_type_to_level(stype));
                     changed++;
                 }
+#if CONFIG_PAGING_LEVELS == 3
+                if ( stype == PGT_l3_shadow ) 
+                {
+                    if ( entry_get_value(guest_pt[i]) != 0 ) 
+                        max = i;
+
+                    if ( !(entry_get_flags(guest_pt[i]) & _PAGE_PRESENT) &&
+                         unlikely(entry_get_value(guest_pt[i]) != 0) &&
+                         !unshadow &&
+                         (frame_table[smfn].u.inuse.type_info & PGT_pinned) )
+                        unshadow = 1;
+                }
+#endif
             }
+
+            if ( d->arch.ops->guest_paging_levels == PAGING_L3
+                 && max == -1 && stype == PGT_l3_shadow )
+                unshadow = 1;
+
+            perfc_incrc(resync_l3);
+            perfc_incr_histo(shm_l3_updates, changed, PT_UPDATES);
             break;
-
-
         }
         case PGT_l4_shadow:
         {
-            int max = -1;
-
             guest_root_pgentry_t *guest_root = guest;
             l4_pgentry_t *shadow4 = shadow;
             guest_root_pgentry_t *snapshot_root = snapshot;
@@ -1547,7 +1617,8 @@
                 if ( root_entry_has_changed(
                         new_root_e, snapshot_root[i], PAGE_FLAG_MASK))
                 {
-                    if (d->arch.ops->guest_paging_levels == PAGING_L4) {
+                    if ( d->arch.ops->guest_paging_levels == PAGING_L4 ) 
+                    {
                         need_flush |= validate_entry_change(
                           d, (pgentry_64_t *)&new_root_e,
                           (pgentry_64_t *)&shadow4[i], 
shadow_type_to_level(stype));
@@ -1563,9 +1634,9 @@
 
                 //  Need a better solution in the long term.
                 if ( !(guest_root_get_flags(new_root_e) & _PAGE_PRESENT) &&
-                  unlikely(guest_root_get_intpte(new_root_e) != 0) &&
-                  !unshadow &&
-                  (frame_table[smfn].u.inuse.type_info & PGT_pinned) )
+                     unlikely(guest_root_get_intpte(new_root_e) != 0) &&
+                     !unshadow &&
+                     (frame_table[smfn].u.inuse.type_info & PGT_pinned) )
                     unshadow = 1;
             }
             if ( max == -1 )
@@ -1575,7 +1646,7 @@
             break;
         }
 
-#endif
+#endif /* CONFIG_PAGING_LEVELS >= 3 */
         default:
             BUG();
         }
@@ -1589,7 +1660,7 @@
         {
             perfc_incrc(unshadow_l2_count);
             shadow_unpin(smfn);
-#if defined (__i386__)
+#if CONFIG_PAGING_LEVELS == 2
             if ( unlikely(shadow_mode_external(d)) )
             {
                 unsigned long hl2mfn;
@@ -1660,19 +1731,24 @@
     // Second, resync all L1 pages, then L2 pages, etc...
     //
     need_flush |= resync_all(d, PGT_l1_shadow);
-#if defined (__i386__)
-    if ( shadow_mode_translate(d) )
+
+#if CONFIG_PAGING_LEVELS == 2
+    if ( d->arch.ops->guest_paging_levels == PAGING_L2 &&
+         shadow_mode_translate(d) )  
+    {
         need_flush |= resync_all(d, PGT_hl2_shadow);
-#endif
-
-    /*
-     * Fixme: for i386 host
-     */
-    if (d->arch.ops->guest_paging_levels == PAGING_L4) {
-        need_flush |= resync_all(d, PGT_l2_shadow);
+    }
+#endif
+
+    need_flush |= resync_all(d, PGT_l2_shadow);
+
+#if CONFIG_PAGING_LEVELS >= 3
+    if (d->arch.ops->guest_paging_levels >= PAGING_L3) 
+    {
         need_flush |= resync_all(d, PGT_l3_shadow);
-    }
-    need_flush |= resync_all(d, PGT_l4_shadow);
+        need_flush |= resync_all(d, PGT_l4_shadow);
+    }
+#endif
 
     if ( need_flush && !unlikely(shadow_mode_external(d)) )
         local_flush_tlb();
@@ -1749,7 +1825,7 @@
 
     return 1;
 }
-#if CONFIG_PAGING_LEVELS <= 3
+#if CONFIG_PAGING_LEVELS == 2
 static int shadow_fault_32(unsigned long va, struct cpu_user_regs *regs)
 {
     l1_pgentry_t gpte, spte, orig_gpte;
@@ -1888,7 +1964,20 @@
     shadow_unlock(d);
     return 0;
 }
-#endif
+#endif /* CONFIG_PAGING_LEVELS == 2 */
+
+static inline unsigned long va_to_l1mfn(struct vcpu *v, unsigned long va)
+{
+    struct domain *d = v->domain;
+    guest_l2_pgentry_t gl2e = {0};
+
+    __guest_get_l2e(v, va, &gl2e);
+    
+    if ( unlikely(!(guest_l2e_get_flags(gl2e) & _PAGE_PRESENT)) )
+        return INVALID_MFN;
+
+    return __gpfn_to_mfn(d, l2e_get_pfn(gl2e));
+}
 
 static int do_update_va_mapping(unsigned long va,
                                 l1_pgentry_t val,
@@ -1899,8 +1988,6 @@
     int rc = 0;
 
     shadow_lock(d);
-
-    //printk("%s(va=%p, val=%p)\n", __func__, (void *)va, (void 
*)l1e_get_intpte(val));
 
     // This is actually overkill - we don't need to sync the L1 itself,
     // just everything involved in getting to this L1 (i.e. we need
@@ -1919,7 +2006,6 @@
     if ( shadow_mode_log_dirty(d) )
         __mark_dirty(d, va_to_l1mfn(v, va));
 
-// out:
     shadow_unlock(d);
 
     return rc;
@@ -1955,7 +2041,7 @@
 static void shadow_update_pagetables(struct vcpu *v)
 {
     struct domain *d = v->domain;
-#if defined (__x86_64__)
+#if CONFIG_PAGING_LEVELS == 4
     unsigned long gmfn = ((v->arch.flags & TF_kernel_mode)?
                           pagetable_get_pfn(v->arch.guest_table) :
                           pagetable_get_pfn(v->arch.guest_table_user));
@@ -1991,7 +2077,8 @@
     /*
      *  arch.shadow_table
      */
-    if ( unlikely(!(smfn = __shadow_status(d, gpfn, PGT_base_page_table))) ) {
+    if ( unlikely(!(smfn = __shadow_status(d, gpfn, PGT_base_page_table))) ) 
+    {
 #if CONFIG_PAGING_LEVELS == 2
         smfn = shadow_l2_table(d, gpfn, gmfn);
 #elif CONFIG_PAGING_LEVELS == 3
@@ -2013,7 +2100,7 @@
      * arch.shadow_vtable
      */
     if ( max_mode == SHM_external
-#if CONFIG_PAGING_LEVELS >=4
+#if CONFIG_PAGING_LEVELS >=3
          || max_mode & SHM_enable
 #endif
         )
@@ -2068,7 +2155,7 @@
         // XXX - maybe this can be optimized somewhat??
         local_flush_tlb();
     }
-#endif
+#endif /* CONFIG_PAGING_LEVELS == 2 */
 
 #if CONFIG_PAGING_LEVELS == 3
     /* FIXME: PAE code to be written */
@@ -2373,7 +2460,7 @@
                l2e_get_intpte(match));
     }
 
-#ifdef __i386__
+#if CONFIG_PAGING_LEVELS == 2
     if ( shadow_mode_external(d) )
         limit = L2_PAGETABLE_ENTRIES;
     else
@@ -2405,7 +2492,7 @@
 int _check_pagetable(struct vcpu *v, char *s)
 {
     struct domain *d = v->domain;
-#if defined (__x86_64__)
+#if CONFIG_PAGING_LEVELS == 4
     pagetable_t pt = ((v->arch.flags & TF_kernel_mode)?
                       v->arch.guest_table : v->arch.guest_table_user);
 #else
@@ -2447,7 +2534,7 @@
     spl2e = (l2_pgentry_t *) map_domain_page(smfn);
 
     /* Go back and recurse. */
-#ifdef __i386__
+#if CONFIG_PAGING_LEVELS == 2
     if ( shadow_mode_external(d) )
         limit = L2_PAGETABLE_ENTRIES;
     else
@@ -2551,59 +2638,108 @@
 
 #if CONFIG_PAGING_LEVELS == 3
 static unsigned long shadow_l3_table(
-  struct domain *d, unsigned long gpfn, unsigned long gmfn)
-{
-    BUG();                      /* not implemenated yet */
-    return 42;
-}
+    struct domain *d, unsigned long gpfn, unsigned long gmfn)
+{
+    unsigned long smfn;
+    l3_pgentry_t *spl3e;
+
+    perfc_incrc(shadow_l3_table_count);
+
+    if ( unlikely(!(smfn = alloc_shadow_page(d, gpfn, gmfn, PGT_l3_shadow))) )
+    {
+        printk("Couldn't alloc an L4 shadow for pfn=%lx mfn=%lx\n", gpfn, 
gmfn);
+        BUG(); /* XXX Deal gracefully with failure. */
+    }
+
+    spl3e = (l3_pgentry_t *)map_domain_page(smfn);
+
+    /* Make the self entry */
+    spl3e[PAE_SHADOW_SELF_ENTRY] = l3e_from_pfn(smfn, __PAGE_HYPERVISOR);
+
+    if ( (PGT_base_page_table == PGT_l3_page_table) &&
+         !shadow_mode_external(d) ) {
+        int i;
+        unsigned long g2mfn, s2mfn;
+        l2_pgentry_t *spl2e;
+        l3_pgentry_t *gpl3e;
+
+        /* Get the top entry */
+        gpl3e = (l3_pgentry_t *)map_domain_page(gmfn);
+
+        if ( !(l3e_get_flags(gpl3e[L3_PAGETABLE_ENTRIES - 1]) & _PAGE_PRESENT) 
)
+        {
+            BUG();
+        }
+
+        g2mfn = l3e_get_pfn(gpl3e[L3_PAGETABLE_ENTRIES - 1]);
+
+        /* NB. g2mfn should be same as g2pfn */
+        if (!(s2mfn = __shadow_status(d, g2mfn, PGT_l2_shadow))) {
+            if ( unlikely(!(s2mfn =
+                    alloc_shadow_page(d, g2mfn, g2mfn, PGT_l2_shadow))) ) {
+                printk("Couldn't alloc an L2 shadow for pfn=%lx mfn=%lx\n",
+                    g2mfn, g2mfn);
+                BUG(); /* XXX Deal gracefully with failure. */
+            }
+
+            if (!get_shadow_ref(s2mfn))
+                BUG();
+        } 
+            
+        /* Map shadow L2 into shadow L3 */
+        spl3e[L3_PAGETABLE_ENTRIES - 1] = l3e_from_pfn(s2mfn, _PAGE_PRESENT);
+        shadow_update_min_max(smfn, L3_PAGETABLE_ENTRIES -1);
+
+        /*  
+         * Xen private mappings. Do the similar things as
+         * create_pae_xen_mappings().
+         */
+        spl2e = (l2_pgentry_t *)map_domain_page(s2mfn);
+
+        /*
+         * When we free L2 pages, we need to tell if the page contains
+         * Xen private mappings. Use the va_mask part.
+         */
+        frame_table[s2mfn].u.inuse.type_info |= 
+            (unsigned long) 3 << PGT_score_shift; 
+
+        memset(spl2e, 0, 
+               (L2_PAGETABLE_FIRST_XEN_SLOT & (L2_PAGETABLE_ENTRIES-1)) * 
sizeof(l2_pgentry_t));
+
+        memcpy(&spl2e[L2_PAGETABLE_FIRST_XEN_SLOT & (L2_PAGETABLE_ENTRIES-1)],
+           &idle_pg_table_l2[L2_PAGETABLE_FIRST_XEN_SLOT],
+           L2_PAGETABLE_XEN_SLOTS * sizeof(l2_pgentry_t));       
+
+        for ( i = 0; i < PDPT_L2_ENTRIES; i++ )
+            spl2e[l2_table_offset(PERDOMAIN_VIRT_START) + i] =
+                l2e_from_page(
+                    
virt_to_page(page_get_owner(&frame_table[gmfn])->arch.mm_perdomain_pt) + i, 
+                    __PAGE_HYPERVISOR);
+        for ( i = 0; i < (LINEARPT_MBYTES >> (L2_PAGETABLE_SHIFT - 20)); i++ )
+            spl2e[l2_table_offset(LINEAR_PT_VIRT_START) + i] =
+                (l3e_get_flags(gpl3e[i]) & _PAGE_PRESENT) ?
+                l2e_from_pfn(l3e_get_pfn(gpl3e[i]), __PAGE_HYPERVISOR) :
+                l2e_empty();
+       
+        unmap_domain_page(spl2e);
+        unmap_domain_page(gpl3e);
+    }
+    unmap_domain_page(spl3e);
+
+    return smfn;
+}
+
 static unsigned long gva_to_gpa_pae(unsigned long gva)
 {
     BUG();
     return 43;
 }
-#endif
-
-#if CONFIG_PAGING_LEVELS >= 4
+#endif /* CONFIG_PAGING_LEVELS == 3 */
+
+#if CONFIG_PAGING_LEVELS == 4
 /****************************************************************************/
 /* 64-bit shadow-mode code testing */
 /****************************************************************************/
-/*
- * validate_bl2e_change()
- * The code is for 32-bit VMX gues on 64-bit host.
- * To sync guest L2.
- */
-static inline void
-validate_bl2e_change(
-  struct domain *d,
-  guest_root_pgentry_t *new_gle_p,
-  pgentry_64_t *shadow_l3,
-  int index)
-{
-    int sl3_idx, sl2_idx;
-    unsigned long sl2mfn, sl1mfn;
-    pgentry_64_t *sl2_p;
-
-    /* Using guest l2 pte index to get shadow l3&l2 index
-     * index: 0 ~ 1023, PAGETABLE_ENTRIES: 512
-     */
-    sl3_idx = index / (PAGETABLE_ENTRIES / 2);
-    sl2_idx = (index % (PAGETABLE_ENTRIES / 2)) * 2;
-
-    sl2mfn = entry_get_pfn(shadow_l3[sl3_idx]);
-    sl2_p = (pgentry_64_t *)map_domain_page(sl2mfn);
-
-    validate_pde_change(
-        d, *(guest_l2_pgentry_t *)new_gle_p, (l2_pgentry_t *)&sl2_p[sl2_idx]);
-
-    /* Mapping the second l1 shadow page */
-    if (entry_get_flags(sl2_p[sl2_idx]) & _PAGE_PRESENT) {
-       sl1mfn = entry_get_pfn(sl2_p[sl2_idx]);
-       sl2_p[sl2_idx + 1] =
-            entry_from_pfn(sl1mfn + 1, entry_get_flags(sl2_p[sl2_idx]));
-    }
-    unmap_domain_page(sl2_p);
-}
-
 /*
  * init_bl2() is for 32-bit VMX guest on 64-bit host
  * Using 1 shadow L4(l3) and 4 shadow L2s to simulate guest L2
@@ -2699,6 +2835,47 @@
     ESH_LOG("shadow_l4_table(%lx -> %lx)", gmfn, smfn);
     return smfn;
 }
+#endif /* CONFIG_PAGING_LEVELS == 4 */
+
+#if CONFIG_PAGING_LEVELS >= 3
+/*
+ * validate_bl2e_change()
+ * The code is for 32-bit VMX gues on 64-bit host.
+ * To sync guest L2.
+ */
+
+static inline void
+validate_bl2e_change(
+    struct domain *d,
+    guest_root_pgentry_t *new_gle_p,
+    pgentry_64_t *shadow_l3,
+    int index)
+{
+    int sl3_idx, sl2_idx;
+    unsigned long sl2mfn, sl1mfn;
+    pgentry_64_t *sl2_p;
+
+    /* Using guest l2 pte index to get shadow l3&l2 index
+     * index: 0 ~ 1023, PAGETABLE_ENTRIES: 512
+     */
+    sl3_idx = index / (PAGETABLE_ENTRIES / 2);
+    sl2_idx = (index % (PAGETABLE_ENTRIES / 2)) * 2;
+
+    sl2mfn = entry_get_pfn(shadow_l3[sl3_idx]);
+    sl2_p = (pgentry_64_t *)map_domain_page(sl2mfn);
+
+    validate_pde_change(
+        d, *(guest_l2_pgentry_t *)new_gle_p, (l2_pgentry_t *)&sl2_p[sl2_idx]);
+
+    /* Mapping the second l1 shadow page */
+    if (entry_get_flags(sl2_p[sl2_idx]) & _PAGE_PRESENT) {
+       sl1mfn = entry_get_pfn(sl2_p[sl2_idx]);
+       sl2_p[sl2_idx + 1] =
+            entry_from_pfn(sl1mfn + 1, entry_get_flags(sl2_p[sl2_idx]));
+    }
+    unmap_domain_page(sl2_p);
+
+}
 
 /*
  * This shadow_mark_va_out_of_sync() is for 2M page shadow
@@ -2714,7 +2891,6 @@
     if ( !get_shadow_ref(writable_pl1e >> L1_PAGETABLE_SHIFT) )
         BUG();
 }
-
 
 static int get_shadow_mfn(struct domain *d, unsigned long gpfn, unsigned long 
*spmfn, u32 flag)
 {
@@ -2764,7 +2940,7 @@
 static void shadow_map_into_current(struct vcpu *v,
   unsigned long va, unsigned int from, unsigned int to)
 {
-    pgentry_64_t gle, sle;
+    pgentry_64_t gle = {0}, sle;
     unsigned long gpfn, smfn;
 
     if (from == PAGING_L1 && to == PAGING_L2) {
@@ -2836,8 +3012,9 @@
 }
 
 
-static void shadow_set_l1e_64(unsigned long va, pgentry_64_t *sl1e_p,
-  int create_l1_shadow)
+static void shadow_set_l1e_64(
+    unsigned long va, pgentry_64_t *sl1e_p,
+    int create_l1_shadow)
 {
     struct vcpu *v = current;
     struct domain *d = v->domain;
@@ -2848,19 +3025,21 @@
     int i;
     unsigned long orig_va = 0;
 
-    if (d->arch.ops->guest_paging_levels == PAGING_L2) {
+    if ( d->arch.ops->guest_paging_levels == PAGING_L2 ) 
+    {
         /* This is for 32-bit VMX guest on 64-bit host */
         orig_va = va;
         va = va & (~((1<<L2_PAGETABLE_SHIFT_32)-1));
     }
 
-    for (i = PAGING_L4; i >= PAGING_L2; i--) {
+    for (i = PAGING_L4; i >= PAGING_L2; i--) 
+    {
         if (!__rw_entry(v, va, &sle, SHADOW_ENTRY | GET_ENTRY | i)) {
             printk("<%s> i = %d\n", __func__, i);
             BUG();
         }
-        if (!(entry_get_flags(sle) & _PAGE_PRESENT)) {
-            if (create_l1_shadow) {
+        if ( !(entry_get_flags(sle) & _PAGE_PRESENT) ) {
+            if ( create_l1_shadow ) {
                 perfc_incrc(shadow_set_l3e_force_map);
                 shadow_map_into_current(v, va, i-1, i);
                 __rw_entry(v, va, &sle, SHADOW_ENTRY | GET_ENTRY | i);
@@ -2870,12 +3049,12 @@
 #endif
             }
         }
-        if(i < PAGING_L4)
+        if( i < PAGING_L4 )
             shadow_update_min_max(entry_get_pfn(sle_up), table_offset_64(va, 
i));
         sle_up = sle;
     }
 
-    if (d->arch.ops->guest_paging_levels == PAGING_L2) {
+    if ( d->arch.ops->guest_paging_levels == PAGING_L2 ) {
         va = orig_va;
     }
 
@@ -2914,7 +3093,7 @@
     l1_pgentry_t sl1e;
     l1_pgentry_t old_sl1e;
     l2_pgentry_t sl2e;
-    unsigned long nx = 0;
+    u64 nx = 0;
     int put_ref_check = 0;
     /* Check if gpfn is 2M aligned */
 
@@ -2929,7 +3108,7 @@
     l2e_remove_flags(tmp_l2e, _PAGE_PSE);
     if (l2e_get_flags(gl2e) & _PAGE_NX) {
         l2e_remove_flags(tmp_l2e, _PAGE_NX);
-        nx = 1UL << 63;
+        nx = 1ULL << 63;
     }
 
 
@@ -3037,114 +3216,161 @@
  * else return 0.
  */
 #if defined( GUEST_PGENTRY_32 )
-static inline int guest_page_fault(struct vcpu *v,
-  unsigned long va, unsigned int error_code,
-  guest_l2_pgentry_t *gpl2e, guest_l1_pgentry_t *gpl1e)
+static inline int guest_page_fault(
+    struct vcpu *v,
+    unsigned long va, unsigned int error_code,
+    guest_l2_pgentry_t *gpl2e, guest_l1_pgentry_t *gpl1e)
 {
     /* The following check for 32-bit guest on 64-bit host */
 
     __guest_get_l2e(v, va, gpl2e);
 
     /* Check the guest L2 page-table entry first*/
-    if (unlikely(!(guest_l2e_get_flags(*gpl2e) & _PAGE_PRESENT)))
+    if ( unlikely(!(guest_l2e_get_flags(*gpl2e) & _PAGE_PRESENT)) )
         return 1;
 
-    if (error_code & ERROR_W) {
-        if (unlikely(!(guest_l2e_get_flags(*gpl2e) & _PAGE_RW)))
+    if ( error_code & ERROR_W ) 
+    {
+        if ( unlikely(!(guest_l2e_get_flags(*gpl2e) & _PAGE_RW)) )
             return 1;
     }
-    if (error_code & ERROR_U) {
-        if (unlikely(!(guest_l2e_get_flags(*gpl2e) & _PAGE_USER)))
+
+    if ( error_code & ERROR_U ) 
+    {
+        if ( unlikely(!(guest_l2e_get_flags(*gpl2e) & _PAGE_USER)) )
             return 1;
     }
 
-    if (guest_l2e_get_flags(*gpl2e) & _PAGE_PSE)
+    if ( guest_l2e_get_flags(*gpl2e) & _PAGE_PSE )
         return 0;
 
     __guest_get_l1e(v, va, gpl1e);
 
     /* Then check the guest L1 page-table entry */
-    if (unlikely(!(guest_l1e_get_flags(*gpl1e) & _PAGE_PRESENT)))
+    if ( unlikely(!(guest_l1e_get_flags(*gpl1e) & _PAGE_PRESENT)) )
         return 1;
 
-    if (error_code & ERROR_W) {
-        if (unlikely(!(guest_l1e_get_flags(*gpl1e) & _PAGE_RW)))
+    if ( error_code & ERROR_W ) 
+    {
+        if ( unlikely(!(guest_l1e_get_flags(*gpl1e) & _PAGE_RW)) )
             return 1;
     }
-    if (error_code & ERROR_U) {
-        if (unlikely(!(guest_l1e_get_flags(*gpl1e) & _PAGE_USER)))
+
+    if ( error_code & ERROR_U ) 
+    {
+        if ( unlikely(!(guest_l1e_get_flags(*gpl1e) & _PAGE_USER)) )
             return 1;
     }
 
     return 0;
 }
 #else
-static inline int guest_page_fault(struct vcpu *v,
-  unsigned long va, unsigned int error_code,
-  guest_l2_pgentry_t *gpl2e, guest_l1_pgentry_t *gpl1e)
+static inline int guest_page_fault(
+    struct vcpu *v,
+    unsigned long va, unsigned int error_code,
+    guest_l2_pgentry_t *gpl2e, guest_l1_pgentry_t *gpl1e)
 {
     struct domain *d = v->domain;
-    pgentry_64_t gle, *lva;
-    unsigned long mfn;
+    pgentry_64_t gle;
+    unsigned long gpfn = 0, mfn;
     int i;
 
-    __rw_entry(v, va, &gle, GUEST_ENTRY | GET_ENTRY | PAGING_L4);
-    if (unlikely(!(entry_get_flags(gle) & _PAGE_PRESENT)))
-        return 1;
-
-    if (error_code & ERROR_W) {
-        if (unlikely(!(entry_get_flags(gle) & _PAGE_RW)))
+    ASSERT( d->arch.ops->guest_paging_levels >= PAGING_L3 );
+
+#if CONFIG_PAGING_LEVELS == 4
+    if ( d->arch.ops->guest_paging_levels == PAGING_L4 ) 
+    {
+        __rw_entry(v, va, &gle, GUEST_ENTRY | GET_ENTRY | PAGING_L4);
+        if ( unlikely(!(entry_get_flags(gle) & _PAGE_PRESENT)) )
             return 1;
-    }
-    if (error_code & ERROR_U) {
-        if (unlikely(!(entry_get_flags(gle) & _PAGE_USER)))
-            return 1;
-    }
-    for (i = PAGING_L3; i >= PAGING_L1; i--) {
+
+        if ( error_code & ERROR_W )
+        {
+            if ( unlikely(!(entry_get_flags(gle) & _PAGE_RW)) )
+                return 1;
+        }
+
+        if ( error_code & ERROR_U )
+        {
+            if ( unlikely(!(entry_get_flags(gle) & _PAGE_USER)) )
+                return 1;
+        }
+        gpfn = entry_get_pfn(gle);
+    }
+#endif
+
+#if CONFIG_PAGING_LEVELS >= 3
+    if ( d->arch.ops->guest_paging_levels == PAGING_L3 ) 
+    {
+        gpfn = pagetable_get_pfn(v->arch.guest_table);
+    }
+#endif
+
+    for ( i = PAGING_L3; i >= PAGING_L1; i-- ) 
+    {
+        pgentry_64_t *lva;
         /*
          * If it's not external mode, then mfn should be machine physical.
          */
-        mfn = __gpfn_to_mfn(d, (entry_get_value(gle) >> PAGE_SHIFT));
-
-        lva = (pgentry_64_t *) phys_to_virt(
-          mfn << PAGE_SHIFT);
+        mfn = __gpfn_to_mfn(d, gpfn);
+
+        lva = (pgentry_64_t *) map_domain_page(mfn);
         gle = lva[table_offset_64(va, i)];
-
-        if (unlikely(!(entry_get_flags(gle) & _PAGE_PRESENT)))
+        unmap_domain_page(lva);
+
+        gpfn = entry_get_pfn(gle);
+
+        if ( unlikely(!(entry_get_flags(gle) & _PAGE_PRESENT)) )
             return 1;
 
-        if (error_code & ERROR_W) {
-            if (unlikely(!(entry_get_flags(gle) & _PAGE_RW)))
-                return 1;
-        }
-        if (error_code & ERROR_U) {
-            if (unlikely(!(entry_get_flags(gle) & _PAGE_USER)))
-                return 1;
-        }
-
-        if (i == PAGING_L2) {
-            if (gpl2e)
+        if ( i < PAGING_L3 ) 
+        {
+            if ( error_code & ERROR_W ) 
+            {
+                if ( unlikely(!(entry_get_flags(gle) & _PAGE_RW)) ) 
+                {
+                    if ( i == PAGING_L1 )
+                        if ( gpl1e )
+                            gpl1e->l1 = gle.lo;
+                    return 1;
+                }
+            }
+            if ( error_code & ERROR_U ) 
+            {
+                if ( unlikely(!(entry_get_flags(gle) & _PAGE_USER)) )
+                    return 1;
+            }
+        }
+
+        if ( i == PAGING_L2 ) 
+        {
+            if ( gpl2e )
                 gpl2e->l2 = gle.lo;
-
-            if (likely(entry_get_flags(gle) & _PAGE_PSE))
+            if ( likely(entry_get_flags(gle) & _PAGE_PSE) )
                 return 0;
-
-        }
-
-        if (i == PAGING_L1)
-            if (gpl1e)
+        }
+
+        if ( i == PAGING_L1 )
+            if ( gpl1e )
                 gpl1e->l1 = gle.lo;
     }
+
     return 0;
-}
-#endif
+
+}
+#endif
+
 static int shadow_fault_64(unsigned long va, struct cpu_user_regs *regs)
 {
     struct vcpu *v = current;
     struct domain *d = v->domain;
     guest_l2_pgentry_t gl2e;
-    guest_l1_pgentry_t gl1e;
+    guest_l1_pgentry_t gl1e, orig_gl1e;
     l1_pgentry_t sl1e;
+
+    gl1e = guest_l1e_empty(); gl2e = guest_l2e_empty();
+
+    sl1e = l1e_empty();
 
     perfc_incrc(shadow_fault_calls);
 
@@ -3156,7 +3382,7 @@
      */
     shadow_lock(d);
 
-    /* XXX - FIX THIS COMMENT!!!
+    /*
      * STEP 1. Check to see if this fault might have been caused by an
      *         out-of-sync table page entry, or if we should pass this
      *         fault onto the guest.
@@ -3166,66 +3392,121 @@
     /*
      * STEP 2. Check if the fault belongs to guest
      */
-    if ( guest_page_fault(
-            v, va, regs->error_code, &gl2e, &gl1e) ) {
+    if ( guest_page_fault(v, va, regs->error_code, &gl2e, &gl1e) ) 
+    {
+        if ( unlikely(shadow_mode_log_dirty(d)) && l1e_get_intpte(gl1e) != 0 )
+            goto check_writeable;
+        
         goto fail;
     }
 
-    if ( unlikely(!(guest_l2e_get_flags(gl2e) & _PAGE_PSE)) ) {
-        /*
-         * Handle 4K pages here
-         */
-
-        /* Write fault? */
-        if ( regs->error_code & 2 ) {
-            if ( !l1pte_write_fault(v, &gl1e, &sl1e, va) ) {
+    if ( unlikely((guest_l2e_get_flags(gl2e) & _PAGE_PSE)) ) 
+        goto pse;
+
+    /*
+     * Handle 4K pages here
+     */
+check_writeable:
+    orig_gl1e = gl1e;
+    
+    /* Write fault? */
+    if ( regs->error_code & 2 ) 
+    {
+        int allow_writes = 0;
+
+        if ( unlikely(!(guest_l1e_get_flags(gl1e) & _PAGE_RW)) )
+        {
+            if ( shadow_mode_page_writable(va, regs, l1e_get_pfn(gl1e)) )
+            {
+                allow_writes = 1;
+                l1e_add_flags(gl1e, _PAGE_RW);
+            }
+            else
+            {
+                /* Write fault on a read-only mapping. */
+                SH_VVLOG("shadow_fault - EXIT: wr fault on RO page (%" PRIpte 
")", 
+                         l1e_get_intpte(gl1e));
+                perfc_incrc(shadow_fault_bail_ro_mapping);
                 goto fail;
             }
-        } else {
-            l1pte_read_fault(d, &gl1e, &sl1e);
-        }
-        /*
-         * STEP 3. Write guest/shadow l2e back
-         */
-        if (unlikely(!__guest_set_l1e(v, va, &gl1e))) {
+        }
+
+        if ( !l1pte_write_fault(v, &gl1e, &sl1e, va) ) 
+        {
+            SH_VVLOG("shadow_fault - EXIT: l1pte_write_fault failed");
+            perfc_incrc(write_fault_bail);
+            shadow_unlock(d);
+            return 0;
+        }
+ 
+        if (allow_writes)
+            l1e_remove_flags(gl1e, _PAGE_RW);
+    }
+    else 
+    {
+        if ( !l1pte_read_fault(d, &gl1e, &sl1e) )
+        {
+            SH_VVLOG("shadow_fault - EXIT: l1pte_read_fault failed");
+            perfc_incrc(read_fault_bail);
+            shadow_unlock(d);
+            return 0;
+        }
+    }
+
+    /*
+     * STEP 3. Write the modified shadow PTE and guest PTE back to the tables
+     */
+    if ( l1e_has_changed(orig_gl1e, gl1e, PAGE_FLAG_MASK) )
+    {
+        if (unlikely(!__guest_set_l1e(v, va, &gl1e))) 
             domain_crash_synchronous();
-        }
-
-        ESH_LOG("gl1e: %lx, sl1e: %lx\n", l1e_get_intpte(gl1e), 
l1e_get_intpte(sl1e));
-        shadow_set_l1e_64(va, (pgentry_64_t *)&sl1e, 1);
-        /*
-         *  if necessary, record the page table page as dirty
-         */
-         if ( unlikely(shadow_mode_log_dirty(d)) )
+
+        // if necessary, record the page table page as dirty
+        if ( unlikely(shadow_mode_log_dirty(d)) )
             __mark_dirty(d, __gpfn_to_mfn(d, l2e_get_pfn(gl2e)));
-
-    } else {
-        /*
-         * Handle 2M pages here
-         */
-        /* Write fault? */
-        if ( regs->error_code & 2 ) {
-            if ( !l2e_rw_fault(v, (l2_pgentry_t *)&gl2e, va, WRITE_FAULT) ) {
-                goto fail;
-            }
-        } else {
-            l2e_rw_fault(v, (l2_pgentry_t *)&gl2e, va, READ_FAULT);
-        }
-
-        /*
-         * STEP 3. Write guest/shadow l2e back
-         */
-
-        if ( unlikely(!__guest_set_l2e(v, va, &gl2e)) ) {
-            domain_crash_synchronous();
-        }
-
-        /*
-         * Todo: if necessary, record the page table page as dirty
-         */
-
-
-    }
+    }
+
+    shadow_set_l1e_64(va, (pgentry_64_t *)&sl1e, 1);
+
+    perfc_incrc(shadow_fault_fixed);
+    d->arch.shadow_fault_count++;
+
+    shadow_unlock(d);
+
+    return EXCRET_fault_fixed;
+
+pse:
+    /*
+     * Handle 2M pages here
+     */
+    if ( unlikely(!shadow_mode_external(d)) )
+        BUG();
+
+    /* Write fault? */
+    if ( regs->error_code & 2 ) 
+    {
+        if ( !l2e_rw_fault(v, (l2_pgentry_t *)&gl2e, va, WRITE_FAULT) ) 
+        {
+            goto fail;
+        }
+    } 
+    else 
+    {
+        l2e_rw_fault(v, (l2_pgentry_t *)&gl2e, va, READ_FAULT);
+    }
+
+    /*
+     * STEP 3. Write guest/shadow l2e back
+     */
+
+    if ( unlikely(!__guest_set_l2e(v, va, &gl2e)) ) 
+    {
+        domain_crash_synchronous();
+    }
+
+    /*
+     * Todo: if necessary, record the page table page as dirty
+     */
 
     perfc_incrc(shadow_fault_fixed);
     d->arch.shadow_fault_count++;
@@ -3257,6 +3538,7 @@
     shadow_unlock(d);
 }
 
+#if CONFIG_PAGING_LEVELS == 4
 static unsigned long gva_to_gpa_64(unsigned long gva)
 {
     struct vcpu *v = current;
@@ -3273,13 +3555,11 @@
         gpa = guest_l1e_get_paddr(gl1e) + (gva & ~PAGE_MASK);
 
     return gpa;
-
 }
 
 #ifndef GUEST_PGENTRY_32
-
 struct shadow_ops MODE_F_HANDLER = {
-    .guest_paging_levels              = 4,
+    .guest_paging_levels        = 4,
     .invlpg                     = shadow_invlpg_64,
     .fault                      = shadow_fault_64,
     .update_pagetables          = shadow_update_pagetables,
@@ -3290,9 +3570,11 @@
     .is_out_of_sync             = is_out_of_sync,
     .gva_to_gpa                 = gva_to_gpa_64,
 };
-#endif
-
-#endif
+#endif /* GUEST_PGENTRY_32 */
+#endif /* CONFIG_PAGING_LEVELS == 4 */
+
+#endif /* CONFIG_PAGING_LEVELS >= 3 */
+
 
 #if CONFIG_PAGING_LEVELS == 2
 struct shadow_ops MODE_A_HANDLER = {
@@ -3309,10 +3591,11 @@
 };
 
 #elif CONFIG_PAGING_LEVELS == 3
+
 struct shadow_ops MODE_B_HANDLER = {
-    .guest_paging_levels              = 3,
-    .invlpg                     = shadow_invlpg_32,
-    .fault                      = shadow_fault_32,
+    .guest_paging_levels        = 3,
+    .invlpg                     = shadow_invlpg_64,
+    .fault                      = shadow_fault_64,
     .update_pagetables          = shadow_update_pagetables,
     .sync_all                   = sync_all,
     .remove_all_write_access    = remove_all_write_access,
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/shadow32.c
--- a/xen/arch/x86/shadow32.c   Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/shadow32.c   Sat Nov 19 05:16:29 2005
@@ -31,6 +31,8 @@
 #include <xen/trace.h>
 
 #define MFN_PINNED(_x) (frame_table[_x].u.inuse.type_info & PGT_pinned)
+#define va_to_l1mfn(_ed, _va) \
+    (l2e_get_pfn(linear_l2_table(_ed)[_va>>L2_PAGETABLE_SHIFT]))
 
 static void shadow_free_snapshot(struct domain *d,
                                  struct out_of_sync_entry *entry);
@@ -997,7 +999,8 @@
     if ( new_modes & SHM_log_dirty )
     {
         ASSERT( !d->arch.shadow_dirty_bitmap );
-        d->arch.shadow_dirty_bitmap_size = (d->max_pages + 63) & ~63;
+        d->arch.shadow_dirty_bitmap_size = 
+            (d->shared_info->arch.max_pfn +  63) & ~63;
         d->arch.shadow_dirty_bitmap = 
             xmalloc_array(unsigned long, d->arch.shadow_dirty_bitmap_size /
                                          (8 * sizeof(unsigned long)));
@@ -1287,34 +1290,28 @@
         d->arch.shadow_dirty_net_count   = 0;
         d->arch.shadow_dirty_block_count = 0;
  
-        if ( (d->max_pages > sc->pages) || 
-             (sc->dirty_bitmap == NULL) || 
+        if ( (sc->dirty_bitmap == NULL) || 
              (d->arch.shadow_dirty_bitmap == NULL) )
         {
             rc = -EINVAL;
             break;
         }
- 
-        sc->pages = d->max_pages;
+
+        if(sc->pages > d->arch.shadow_dirty_bitmap_size)
+            sc->pages = d->arch.shadow_dirty_bitmap_size; 
 
 #define chunk (8*1024) /* Transfer and clear in 1kB chunks for L1 cache. */
-        for ( i = 0; i < d->max_pages; i += chunk )
-        {
-            int bytes = ((((d->max_pages - i) > chunk) ?
-                          chunk : (d->max_pages - i)) + 7) / 8;
+        for ( i = 0; i < sc->pages; i += chunk )
+        {
+            int bytes = ((((sc->pages - i) > chunk) ?
+                          chunk : (sc->pages - i)) + 7) / 8;
      
             if (copy_to_user(
                     sc->dirty_bitmap + (i/(8*sizeof(unsigned long))),
                     d->arch.shadow_dirty_bitmap +(i/(8*sizeof(unsigned long))),
                     bytes))
             {
-                // copy_to_user can fail when copying to guest app memory.
-                // app should zero buffer after mallocing, and pin it
                 rc = -EINVAL;
-                memset(
-                    d->arch.shadow_dirty_bitmap + 
-                    (i/(8*sizeof(unsigned long))),
-                    0, (d->max_pages/8) - (i/(8*sizeof(unsigned long))));
                 break;
             }
 
@@ -1331,17 +1328,19 @@
         sc->stats.dirty_net_count   = d->arch.shadow_dirty_net_count;
         sc->stats.dirty_block_count = d->arch.shadow_dirty_block_count;
  
-        if ( (d->max_pages > sc->pages) || 
-             (sc->dirty_bitmap == NULL) || 
+
+        if ( (sc->dirty_bitmap == NULL) || 
              (d->arch.shadow_dirty_bitmap == NULL) )
         {
             rc = -EINVAL;
             break;
         }
  
-        sc->pages = d->max_pages;
-        if (copy_to_user(
-            sc->dirty_bitmap, d->arch.shadow_dirty_bitmap, (d->max_pages+7)/8))
+        if(sc->pages > d->arch.shadow_dirty_bitmap_size)
+            sc->pages = d->arch.shadow_dirty_bitmap_size; 
+
+        if (copy_to_user(sc->dirty_bitmap, 
+                         d->arch.shadow_dirty_bitmap, (sc->pages+7)/8))
         {
             rc = -EINVAL;
             break;
@@ -1827,7 +1826,7 @@
 }
 
 struct out_of_sync_entry *
-shadow_mark_mfn_out_of_sync(struct vcpu *v, unsigned long gpfn,
+__shadow_mark_mfn_out_of_sync(struct vcpu *v, unsigned long gpfn,
                              unsigned long mfn)
 {
     struct domain *d = v->domain;
@@ -1863,7 +1862,6 @@
     entry->v = v;
     entry->gpfn = gpfn;
     entry->gmfn = mfn;
-    entry->snapshot_mfn = shadow_make_snapshot(d, gpfn, mfn);
     entry->writable_pl1e = -1;
 
 #if SHADOW_DEBUG
@@ -1875,6 +1873,18 @@
     //
     get_page(page, d);
 
+    return entry;
+}
+
+struct out_of_sync_entry *
+shadow_mark_mfn_out_of_sync(struct vcpu *v, unsigned long gpfn,
+                             unsigned long mfn)
+{
+    struct out_of_sync_entry *entry =
+      __shadow_mark_mfn_out_of_sync(v, gpfn, mfn);
+    struct domain *d = v->domain;
+
+    entry->snapshot_mfn = shadow_make_snapshot(d, gpfn, mfn);
     // Add to the out-of-sync list
     //
     entry->next = d->arch.out_of_sync;
@@ -1887,8 +1897,9 @@
     struct vcpu *v, unsigned long gpfn, unsigned long mfn, unsigned long va)
 {
     struct out_of_sync_entry *entry =
-        shadow_mark_mfn_out_of_sync(v, gpfn, mfn);
+        __shadow_mark_mfn_out_of_sync(v, gpfn, mfn);
     l2_pgentry_t sl2e;
+    struct domain *d = v->domain;
 
     // We need the address of shadow PTE that maps @va.
     // It might not exist yet.  Make sure it's there.
@@ -1903,6 +1914,7 @@
     }
     ASSERT(l2e_get_flags(sl2e) & _PAGE_PRESENT);
 
+    entry->snapshot_mfn = shadow_make_snapshot(d, gpfn, mfn);
     // NB: this is stored as a machine address.
     entry->writable_pl1e =
         l2e_get_paddr(sl2e) | (sizeof(l1_pgentry_t) * l1_table_offset(va));
@@ -1914,6 +1926,11 @@
     //
     if ( !get_shadow_ref(l2e_get_pfn(sl2e)) )
         BUG();
+
+    // Add to the out-of-sync list
+    //
+    entry->next = d->arch.out_of_sync;
+    d->arch.out_of_sync = entry;
 
     FSH_LOG("mark_out_of_sync(va=%lx -> writable_pl1e=%lx)",
             va, entry->writable_pl1e);
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/shadow_public.c
--- a/xen/arch/x86/shadow_public.c      Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/shadow_public.c      Sat Nov 19 05:16:29 2005
@@ -64,6 +64,9 @@
 #if CONFIG_PAGING_LEVELS == 2
         if ( d->arch.ops != &MODE_A_HANDLER )
             d->arch.ops = &MODE_A_HANDLER;
+#elif CONFIG_PAGING_LEVELS == 3
+        if ( d->arch.ops != &MODE_B_HANDLER )
+            d->arch.ops = &MODE_B_HANDLER;
 #elif CONFIG_PAGING_LEVELS == 4
         if ( d->arch.ops != &MODE_D_HANDLER )
             d->arch.ops = &MODE_D_HANDLER;
@@ -138,7 +141,92 @@
 }
 /****************************************************************************/
 /****************************************************************************/
-#if CONFIG_PAGING_LEVELS >= 4
+#if CONFIG_PAGING_LEVELS >= 3
+
+static void inline
+free_shadow_fl1_table(struct domain *d, unsigned long smfn)
+{
+    l1_pgentry_t *pl1e = map_domain_page(smfn);
+    int i;
+
+    for (i = 0; i < L1_PAGETABLE_ENTRIES; i++)
+        put_page_from_l1e(pl1e[i], d);
+}
+
+/*
+ * Free l2, l3, l4 shadow tables
+ */
+
+void free_fake_shadow_l2(struct domain *d,unsigned long smfn);
+
+static void inline
+free_shadow_tables(struct domain *d, unsigned long smfn, u32 level)
+{
+    pgentry_64_t *ple = map_domain_page(smfn);
+    int i, external = shadow_mode_external(d);
+
+#if CONFIG_PAGING_LEVELS >=3
+    if ( d->arch.ops->guest_paging_levels == PAGING_L2 )
+    {
+        struct pfn_info *page = &frame_table[smfn];
+        for ( i = 0; i < PDP_ENTRIES; i++ )
+        {
+            if ( entry_get_flags(ple[i]) & _PAGE_PRESENT )
+                free_fake_shadow_l2(d,entry_get_pfn(ple[i]));
+        }
+
+        page = &frame_table[entry_get_pfn(ple[0])];
+        free_domheap_pages(page, SL2_ORDER);
+        unmap_domain_page(ple);
+    }
+    else
+#endif
+    {
+        /*
+         * No Xen mappings in external pages
+         */
+        if ( external )
+        {
+            for ( i = 0; i < PAGETABLE_ENTRIES; i++ )
+                if ( entry_get_flags(ple[i]) & _PAGE_PRESENT )
+                    put_shadow_ref(entry_get_pfn(ple[i]));
+        } 
+        else
+        {
+            for ( i = 0; i < PAGETABLE_ENTRIES; i++ )
+            {
+                /* 
+                 * List the skip/break conditions to avoid freeing
+                 * Xen private mappings.
+                 */
+#if CONFIG_PAGING_LEVELS == 2
+                if ( level == PAGING_L2 && !is_guest_l2_slot(0, i) )
+                    continue;
+#endif
+#if CONFIG_PAGING_LEVELS == 3
+                if ( level == PAGING_L3 && i == L3_PAGETABLE_ENTRIES )
+                    break;
+                if ( level == PAGING_L2 )
+                {
+                    struct pfn_info *page = &frame_table[smfn]; 
+                    if ( is_xen_l2_slot(page->u.inuse.type_info, i) )
+                        continue;
+                }
+#endif
+#if CONFIG_PAGING_LEVELS == 4
+                if ( level == PAGING_L4 && !is_guest_l4_slot(i))
+                    continue;
+#endif
+                if ( entry_get_flags(ple[i]) & _PAGE_PRESENT )
+                    put_shadow_ref(entry_get_pfn(ple[i]));
+            }
+        }
+        unmap_domain_page(ple);
+    }
+}
+#endif
+
+#if CONFIG_PAGING_LEVELS == 4
 /*
  * Convert PAE 3-level page-table to 4-level page-table
  */
@@ -151,13 +239,13 @@
     
     l4page = alloc_domheap_page(NULL);
     if (l4page == NULL)
-        domain_crash();
+        domain_crash(d);
     l4 = map_domain_page(page_to_pfn(l4page));
     memset(l4, 0, PAGE_SIZE);
 
     l3page = alloc_domheap_page(NULL);
     if (l3page == NULL)
-        domain_crash();
+        domain_crash(d);
     l3 =  map_domain_page(page_to_pfn(l3page));
     memset(l3, 0, PAGE_SIZE);
 
@@ -202,55 +290,6 @@
     v->arch.monitor_table = mk_pagetable(mmfn << PAGE_SHIFT);
     v->arch.monitor_vtable = (l2_pgentry_t *) mpl4e;
 }
-
-static void inline
-free_shadow_fl1_table(struct domain *d, unsigned long smfn)
-{
-    l1_pgentry_t *pl1e = map_domain_page(smfn);
-    int i;
-
-    for (i = 0; i < L1_PAGETABLE_ENTRIES; i++)
-        put_page_from_l1e(pl1e[i], d);
-}
-
-/*
- * Free l2, l3, l4 shadow tables
- */
-
-void free_fake_shadow_l2(struct domain *d,unsigned long smfn);
-
-static void inline
-free_shadow_tables(struct domain *d, unsigned long smfn, u32 level)
-{
-    pgentry_64_t *ple = map_domain_page(smfn);
-    int i, external = shadow_mode_external(d);
-    struct pfn_info *page = &frame_table[smfn];
-
-    if (d->arch.ops->guest_paging_levels == PAGING_L2)
-    {
-#if CONFIG_PAGING_LEVELS >=4
-        for ( i = 0; i < PDP_ENTRIES; i++ )
-        {
-            if (entry_get_flags(ple[i]) & _PAGE_PRESENT )
-                free_fake_shadow_l2(d,entry_get_pfn(ple[i]));
-        }
-   
-        page = &frame_table[entry_get_pfn(ple[0])];
-        free_domheap_pages(page, SL2_ORDER);
-        unmap_domain_page(ple);
-#endif
-    }
-    else
-    {
-        for ( i = 0; i < PAGETABLE_ENTRIES; i++ )
-            if ( external || is_guest_l4_slot(i) )
-                if ( entry_get_flags(ple[i]) & _PAGE_PRESENT )
-                    put_shadow_ref(entry_get_pfn(ple[i]));
-
-        unmap_domain_page(ple);
-    }
-}
-
 
 void free_monitor_pagetable(struct vcpu *v)
 {
@@ -299,11 +338,9 @@
     mpl2e = (l2_pgentry_t *)map_domain_page(mmfn);
     memset(mpl2e, 0, PAGE_SIZE);
 
-#ifdef __i386__ /* XXX screws x86/64 build */
     memcpy(&mpl2e[DOMAIN_ENTRIES_PER_L2_PAGETABLE], 
            &idle_pg_table[DOMAIN_ENTRIES_PER_L2_PAGETABLE],
            HYPERVISOR_ENTRIES_PER_L2_PAGETABLE * sizeof(l2_pgentry_t));
-#endif
 
     mpl2e[l2_table_offset(PERDOMAIN_VIRT_START)] =
         l2e_from_paddr(__pa(d->arch.mm_perdomain_pt),
@@ -333,7 +370,7 @@
     unsigned long mfn;
 
     ASSERT( pagetable_get_paddr(v->arch.monitor_table) );
-    
+
     mpl2e = v->arch.monitor_vtable;
 
     /*
@@ -517,13 +554,11 @@
 
     SH_VVLOG("%s: smfn=%lx freed", __func__, smfn);
 
-#ifdef __i386__
+#if CONFIG_PAGING_LEVELS == 2
     if ( shadow_mode_external(d) )
         limit = L2_PAGETABLE_ENTRIES;
     else
         limit = DOMAIN_ENTRIES_PER_L2_PAGETABLE;
-#else
-    limit = 0; /* XXX x86/64 XXX */
 #endif
 
     for ( i = 0; i < limit; i++ )
@@ -584,10 +619,11 @@
 
     ASSERT( ! IS_INVALID_M2P_ENTRY(gpfn) );
 #if CONFIG_PAGING_LEVELS >=4
-    if (type == PGT_fl1_shadow) {
+    if ( type == PGT_fl1_shadow ) 
+    {
         unsigned long mfn;
         mfn = __shadow_status(d, gpfn, PGT_fl1_shadow);
-        if (!mfn)
+        if ( !mfn )
             gpfn |= (1UL << 63);
     }
 #endif
@@ -602,7 +638,7 @@
         free_shadow_l1_table(d, smfn);
         d->arch.shadow_page_count--;
         break;
-#if defined (__i386__)
+#if CONFIG_PAGING_LEVELS == 2
     case PGT_l2_shadow:
         perfc_decr(shadow_l2_pages);
         shadow_demote(d, gpfn, gmfn);
@@ -616,7 +652,8 @@
         free_shadow_hl2_table(d, smfn);
         d->arch.hl2_page_count--;
         break;
-#else
+#endif
+#if CONFIG_PAGING_LEVELS >= 3
     case PGT_l2_shadow:
     case PGT_l3_shadow:
     case PGT_l4_shadow:
@@ -630,7 +667,6 @@
         d->arch.shadow_page_count--;
         break;
 #endif
-
     case PGT_snapshot:
         perfc_decr(apshot_pages);
         break;
@@ -782,7 +818,7 @@
         }
     }
 
-#if defined (__i386__)
+#if CONFIG_PAGING_LEVELS == 2
     // For external shadows, remove the monitor table's refs
     //
     if ( shadow_mode_external(d) )
@@ -928,7 +964,7 @@
     ASSERT(!(d->arch.shadow_mode & ~mode));
 
 #if defined(CONFIG_PAGING_LEVELS)
-    if(!shadow_set_guest_paging_levels(d, 
+    if(!shadow_set_guest_paging_levels(d,
                                        CONFIG_PAGING_LEVELS)) {
         printk("Unsupported guest paging levels\n");
         domain_crash_synchronous(); /* need to take a clean path */
@@ -968,7 +1004,7 @@
         else
             v->arch.shadow_vtable = NULL;
         
-#if defined (__i386__)
+#if CONFIG_PAGING_LEVELS == 2
         /*
          * arch.hl2_vtable
          */
@@ -1009,7 +1045,8 @@
     if ( new_modes & SHM_log_dirty )
     {
         ASSERT( !d->arch.shadow_dirty_bitmap );
-        d->arch.shadow_dirty_bitmap_size = (d->max_pages + 63) & ~63;
+        d->arch.shadow_dirty_bitmap_size = 
+            (d->shared_info->arch.max_pfn +  63) & ~63;
         d->arch.shadow_dirty_bitmap = 
             xmalloc_array(unsigned long, d->arch.shadow_dirty_bitmap_size /
                           (8 * sizeof(unsigned long)));
@@ -1163,34 +1200,29 @@
         d->arch.shadow_dirty_net_count   = 0;
         d->arch.shadow_dirty_block_count = 0;
  
-        if ( (d->max_pages > sc->pages) || 
-             (sc->dirty_bitmap == NULL) || 
+
+        if ( (sc->dirty_bitmap == NULL) || 
              (d->arch.shadow_dirty_bitmap == NULL) )
         {
             rc = -EINVAL;
             break;
         }
- 
-        sc->pages = d->max_pages;
+
+        if(sc->pages > d->arch.shadow_dirty_bitmap_size)
+            sc->pages = d->arch.shadow_dirty_bitmap_size; 
 
 #define chunk (8*1024) /* Transfer and clear in 1kB chunks for L1 cache. */
-        for ( i = 0; i < d->max_pages; i += chunk )
-        {
-            int bytes = ((((d->max_pages - i) > chunk) ?
-                          chunk : (d->max_pages - i)) + 7) / 8;
+        for ( i = 0; i < sc->pages; i += chunk )
+        {
+            int bytes = ((((sc->pages - i) > chunk) ?
+                          chunk : (sc->pages - i)) + 7) / 8;
 
             if (copy_to_user(
                 sc->dirty_bitmap + (i/(8*sizeof(unsigned long))),
                 d->arch.shadow_dirty_bitmap +(i/(8*sizeof(unsigned long))),
                 bytes))
             {
-                // copy_to_user can fail when copying to guest app memory.
-                // app should zero buffer after mallocing, and pin it
                 rc = -EINVAL;
-                memset(
-                    d->arch.shadow_dirty_bitmap + 
-                    (i/(8*sizeof(unsigned long))),
-                    0, (d->max_pages/8) - (i/(8*sizeof(unsigned long))));
                 break;
             }
             memset(
@@ -1206,17 +1238,18 @@
         sc->stats.dirty_net_count   = d->arch.shadow_dirty_net_count;
         sc->stats.dirty_block_count = d->arch.shadow_dirty_block_count;
  
-        if ( (d->max_pages > sc->pages) || 
-             (sc->dirty_bitmap == NULL) || 
+        if ( (sc->dirty_bitmap == NULL) || 
              (d->arch.shadow_dirty_bitmap == NULL) )
         {
             rc = -EINVAL;
             break;
         }
  
-        sc->pages = d->max_pages;
-        if (copy_to_user(
-            sc->dirty_bitmap, d->arch.shadow_dirty_bitmap, (d->max_pages+7)/8))
+        if(sc->pages > d->arch.shadow_dirty_bitmap_size)
+            sc->pages = d->arch.shadow_dirty_bitmap_size; 
+
+        if (copy_to_user(sc->dirty_bitmap, 
+                         d->arch.shadow_dirty_bitmap, (sc->pages+7)/8))
         {
             rc = -EINVAL;
             break;
@@ -1411,7 +1444,7 @@
     sl1mfn = __shadow_status(current->domain, pa >> PAGE_SHIFT, PGT_l1_shadow);
     if ( sl1mfn )
     {
-        SH_VVLOG("shadow_l1_normal_pt_update pa=%p, gpte=%" PRIpte,
+        SH_VVLOG("shadow_l1_normal_pt_update pa=%p, gpde=%" PRIpte,
                  (void *)pa, l1e_get_intpte(gpte));
         l1pte_propagate_from_guest(current->domain, gpte, &spte);
 
@@ -1450,7 +1483,7 @@
 #if CONFIG_PAGING_LEVELS >= 3
 void shadow_l3_normal_pt_update(
     struct domain *d,
-    unsigned long pa, l3_pgentry_t gpde,
+    unsigned long pa, l3_pgentry_t l3e,
     struct domain_mmap_cache *cache)
 {
     unsigned long sl3mfn;
@@ -1461,11 +1494,10 @@
     sl3mfn = __shadow_status(current->domain, pa >> PAGE_SHIFT, PGT_l3_shadow);
     if ( sl3mfn )
     {
-        SH_VVLOG("shadow_l3_normal_pt_update pa=%p, gpde=%" PRIpte,
-                 (void *)pa, l3e_get_intpte(gpde));
-
+        SH_VVLOG("shadow_l3_normal_pt_update pa=%p, l3e=%" PRIpte,
+                 (void *)pa, l3e_get_intpte(l3e));
         spl3e = (pgentry_64_t *) map_domain_page_with_cache(sl3mfn, cache);
-        validate_entry_change(d, (pgentry_64_t *) &gpde,
+        validate_entry_change(d, (pgentry_64_t *) &l3e,
                               &spl3e[(pa & ~PAGE_MASK) / 
sizeof(l3_pgentry_t)], 
                               shadow_type_to_level(PGT_l3_shadow));
         unmap_domain_page_with_cache(spl3e, cache);
@@ -1478,7 +1510,7 @@
 #if CONFIG_PAGING_LEVELS >= 4
 void shadow_l4_normal_pt_update(
     struct domain *d,
-    unsigned long pa, l4_pgentry_t gpde,
+    unsigned long pa, l4_pgentry_t l4e,
     struct domain_mmap_cache *cache)
 {
     unsigned long sl4mfn;
@@ -1489,11 +1521,10 @@
     sl4mfn = __shadow_status(current->domain, pa >> PAGE_SHIFT, PGT_l4_shadow);
     if ( sl4mfn )
     {
-        SH_VVLOG("shadow_l4_normal_pt_update pa=%p, gpde=%" PRIpte,
-                 (void *)pa, l4e_get_intpte(gpde));
-
+        SH_VVLOG("shadow_l4_normal_pt_update pa=%p, l4e=%" PRIpte,
+                 (void *)pa, l4e_get_intpte(l4e));
         spl4e = (pgentry_64_t *)map_domain_page_with_cache(sl4mfn, cache);
-        validate_entry_change(d, (pgentry_64_t *)&gpde,
+        validate_entry_change(d, (pgentry_64_t *)&l4e,
                               &spl4e[(pa & ~PAGE_MASK) / 
sizeof(l4_pgentry_t)], 
                               shadow_type_to_level(PGT_l4_shadow));
         unmap_domain_page_with_cache(spl4e, cache);
@@ -1557,8 +1588,6 @@
 remove_shadow(struct domain *d, unsigned long gpfn, u32 stype)
 {
     unsigned long smfn;
-
-    //printk("%s(gpfn=%lx, type=%x)\n", __func__, gpfn, stype);
 
     shadow_lock(d);
 
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/traps.c
--- a/xen/arch/x86/traps.c      Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/traps.c      Sat Nov 19 05:16:29 2005
@@ -412,16 +412,16 @@
     struct vcpu *v = current;
     struct trap_bounce *tb = &v->arch.trap_bounce;
 
+    v->arch.guest_context.ctrlreg[2] = addr;
+    v->vcpu_info->arch.cr2           = addr;
+
     ti = &v->arch.guest_context.trap_ctxt[TRAP_page_fault];
-    tb->flags = TBF_EXCEPTION | TBF_EXCEPTION_ERRCODE | TBF_EXCEPTION_CR2;
-    tb->cr2        = addr;
+    tb->flags = TBF_EXCEPTION | TBF_EXCEPTION_ERRCODE;
     tb->error_code = error_code;
     tb->cs         = ti->cs;
     tb->eip        = ti->address;
     if ( TI_GET_IF(ti) )
         tb->flags |= TBF_INTERRUPT;
-
-    v->arch.guest_context.ctrlreg[2] = addr;
 }
 
 static int handle_perdomain_mapping_fault(
@@ -931,6 +931,7 @@
 
         case 2: /* Write CR2 */
             v->arch.guest_context.ctrlreg[2] = *reg;
+            v->vcpu_info->arch.cr2           = *reg;
             break;
             
         case 3: /* Write CR3 */
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/vmx.c
--- a/xen/arch/x86/vmx.c        Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/vmx.c        Sat Nov 19 05:16:29 2005
@@ -191,12 +191,12 @@
     case MSR_FS_BASE:
         if (!(VMX_LONG_GUEST(vc)))
             /* XXX should it be GP fault */
-            domain_crash();
+            domain_crash(vc->domain);
         __vmread(GUEST_FS_BASE, &msr_content);
         break;
     case MSR_GS_BASE:
         if (!(VMX_LONG_GUEST(vc)))
-            domain_crash();
+            domain_crash(vc->domain);
         __vmread(GUEST_GS_BASE, &msr_content);
         break;
     case MSR_SHADOW_GS_BASE:
@@ -260,7 +260,7 @@
     case MSR_FS_BASE:
     case MSR_GS_BASE:
         if (!(VMX_LONG_GUEST(vc)))
-            domain_crash();
+            domain_crash(vc->domain);
         if (!IS_CANO_ADDRESS(msr_content)){
             VMX_DBG_LOG(DBG_LEVEL_1, "Not cano address of msr write\n");
             vmx_inject_exception(vc, TRAP_gp_fault, 0);
@@ -273,7 +273,7 @@
 
     case MSR_SHADOW_GS_BASE:
         if (!(VMX_LONG_GUEST(vc)))
-            domain_crash();
+            domain_crash(vc->domain);
         vc->arch.arch_vmx.msr_content.shadow_gs = msr_content;
         wrmsrl(MSR_SHADOW_GS_BASE, msr_content);
         break;
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/vmx_io.c
--- a/xen/arch/x86/vmx_io.c     Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/vmx_io.c     Sat Nov 19 05:16:29 2005
@@ -459,14 +459,56 @@
         }
         break;
 
-    case INSTR_MOVZ:
+    case INSTR_MOVZX:
         if (dst & REGISTER) {
+            switch (size) {
+            case BYTE:
+                p->u.data &= 0xFFULL;
+                break;
+
+            case WORD:
+                p->u.data &= 0xFFFFULL;
+                break;
+
+            case LONG:
+                p->u.data &= 0xFFFFFFFFULL;
+                break;
+
+            default:
+                printk("Impossible source operand size of movzx instr: %d\n", 
size);
+                domain_crash_synchronous();
+            }
             index = operand_index(dst);
+            set_reg_value(operand_size(dst), index, 0, regs, p->u.data);
+        }
+        break;
+
+    case INSTR_MOVSX:
+        if (dst & REGISTER) {
             switch (size) {
-            case BYTE: p->u.data = p->u.data & 0xFFULL; break;
-            case WORD: p->u.data = p->u.data & 0xFFFFULL; break;
-            case LONG: p->u.data = p->u.data & 0xFFFFFFFFULL; break;
+            case BYTE:
+                p->u.data &= 0xFFULL;
+                if ( p->u.data & 0x80ULL )
+                    p->u.data |= 0xFFFFFFFFFFFFFF00ULL;
+                break;
+
+            case WORD:
+                p->u.data &= 0xFFFFULL;
+                if ( p->u.data & 0x8000ULL )
+                    p->u.data |= 0xFFFFFFFFFFFF0000ULL;
+                break;
+
+            case LONG:
+                p->u.data &= 0xFFFFFFFFULL;
+                if ( p->u.data & 0x80000000ULL )
+                    p->u.data |= 0xFFFFFFFF00000000ULL;
+                break;
+
+            default:
+                printk("Impossible source operand size of movsx instr: %d\n", 
size);
+                domain_crash_synchronous();
             }
+            index = operand_index(dst);
             set_reg_value(operand_size(dst), index, 0, regs, p->u.data);
         }
         break;
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/vmx_platform.c
--- a/xen/arch/x86/vmx_platform.c       Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/vmx_platform.c       Sat Nov 19 05:16:29 2005
@@ -581,25 +581,39 @@
     }
 
     switch (*++opcode) {
-    case 0xB6: /* movz m8, r16/r32 */
-        instr->instr = INSTR_MOVZ;
+    case 0xB6: /* movzx m8, r16/r32/r64 */
+        instr->instr = INSTR_MOVZX;
         GET_OP_SIZE_FOR_NONEBYTE(instr->op_size);
         index = get_index(opcode + 1, rex);
         instr->operand[0] = mk_operand(BYTE, 0, 0, MEMORY);
         instr->operand[1] = mk_operand(instr->op_size, index, 0, REGISTER);
         return DECODE_success;
 
-    case 0xB7: /* movz m16/m32, r32/r64 */
-        instr->instr = INSTR_MOVZ;
+    case 0xB7: /* movzx m16/m32, r32/r64 */
+        instr->instr = INSTR_MOVZX;
+        GET_OP_SIZE_FOR_NONEBYTE(instr->op_size);
         index = get_index(opcode + 1, rex);
-        if (rex & 0x8) {
-            instr->op_size = LONG;
-            instr->operand[1] = mk_operand(QUAD, index, 0, REGISTER);
-        } else {
-            instr->op_size = WORD;
-            instr->operand[1] = mk_operand(LONG, index, 0, REGISTER);
-        }
-        instr->operand[0] = mk_operand(instr->op_size, 0, 0, MEMORY);
+        if (rex & 0x8)
+            instr->operand[0] = mk_operand(LONG, 0, 0, MEMORY);
+        else
+            instr->operand[0] = mk_operand(WORD, 0, 0, MEMORY);
+        instr->operand[1] = mk_operand(instr->op_size, index, 0, REGISTER);
+        return DECODE_success;
+
+    case 0xBE: /* movsx m8, r16/r32/r64 */
+        instr->instr = INSTR_MOVSX;
+        GET_OP_SIZE_FOR_NONEBYTE(instr->op_size);
+        index = get_index(opcode + 1, rex);
+        instr->operand[0] = mk_operand(BYTE, 0, 0, MEMORY);
+        instr->operand[1] = mk_operand(instr->op_size, index, 0, REGISTER);
+        return DECODE_success;
+
+    case 0xBF: /* movsx m16, r32/r64 */
+        instr->instr = INSTR_MOVSX;
+        GET_OP_SIZE_FOR_NONEBYTE(instr->op_size);
+        index = get_index(opcode + 1, rex);
+        instr->operand[0] = mk_operand(WORD, 0, 0, MEMORY);
+        instr->operand[1] = mk_operand(instr->op_size, index, 0, REGISTER);
         return DECODE_success;
 
     case 0xA3: /* bt r32, m32 */
@@ -702,7 +716,7 @@
         send_mmio_req(type, gpa, 1, inst->op_size, value, IOREQ_WRITE, 0);
     } else if (inst->operand[0] & MEMORY) { /* dest is register */
         /* send the request and wait for the value */
-        if (inst->instr == INSTR_MOVZ)
+        if ( (inst->instr == INSTR_MOVZX) || (inst->instr == INSTR_MOVSX) )
             send_mmio_req(type, gpa, 1, size_reg, 0, IOREQ_READ, 0);
         else
             send_mmio_req(type, gpa, 1, inst->op_size, 0, IOREQ_READ, 0);
@@ -827,7 +841,8 @@
         break;
     }
 
-    case INSTR_MOVZ:
+    case INSTR_MOVZX:
+    case INSTR_MOVSX:
         mmio_operands(IOREQ_TYPE_COPY, gpa, &mmio_inst, mmio_opp, regs);
         break;
 
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/vmx_vlapic.c
--- a/xen/arch/x86/vmx_vlapic.c Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/vmx_vlapic.c Sat Nov 19 05:16:29 2005
@@ -28,7 +28,7 @@
 #include <asm/vmx.h>
 #include <asm/vmx_platform.h>
 #include <asm/vmx_vlapic.h>
-
+#include <asm/vmx_vioapic.h>
 #include <xen/lib.h>
 #include <xen/sched.h>
 #include <asm/current.h>
@@ -119,22 +119,35 @@
 }
 
 /* This only for fixed delivery mode */
-int vlapic_match_dest(struct vlapic *target, struct vlapic *source,
-                      int short_hand, int dest, int dest_mode,
-                      int delivery_mode)
+static int vlapic_match_dest(struct vcpu *v, struct vlapic *source,
+                             int short_hand, int dest, int dest_mode,
+                             int delivery_mode)
 {
     int result = 0;
+    struct vlapic *target = VLAPIC(v);
 
     VMX_DBG_LOG(DBG_LEVEL_VLAPIC, "vlapic_match_dest: "
                 "target %p source %p dest %x dest_mode %x short_hand %x "
                 "delivery_mode %x",
                 target, source, dest, dest_mode, short_hand, delivery_mode);
 
+    if ( unlikely(!target) &&
+         ( (delivery_mode != VLAPIC_DELIV_MODE_INIT) &&
+           (delivery_mode != VLAPIC_DELIV_MODE_STARTUP) &&
+           (delivery_mode != VLAPIC_DELIV_MODE_NMI) )) {
+        VMX_DBG_LOG(DBG_LEVEL_VLAPIC, "vlapic_match_dest "
+                    "uninitialized target v %p delivery_mode %x dest %x\n",
+                    v, delivery_mode, dest);
+        return result;
+    }
+
     switch (short_hand) {
     case VLAPIC_NO_SHORTHAND:
         if (!dest_mode) {   /* Physical */
-            result = (target->id == dest);
+            result = ((target ? target->id : v->vcpu_id ) == dest);
         } else {            /* Logical */
+            if (!target)
+                break;
             if (((target->dest_format >> 28) & 0xf) == 0xf) {   /* Flat mode */
                 result = (target->logical_dest >> 24) & dest;
             } else {
@@ -176,17 +189,18 @@
  * Add a pending IRQ into lapic.
  * Return 1 if successfully added and 0 if discarded.
  */
-int vlapic_accept_irq(struct vlapic *vlapic, int delivery_mode,
-                      int vector, int level, int trig_mode)
-{
-    int        result = 1;
+static int vlapic_accept_irq(struct vcpu *v, int delivery_mode,
+                             int vector, int level, int trig_mode)
+{
+    int        result = 0;
+    struct vlapic *vlapic = VLAPIC(v);
 
     switch (delivery_mode) {
     case VLAPIC_DELIV_MODE_FIXED:
     case VLAPIC_DELIV_MODE_LPRI:
         /* FIXME add logic for vcpu on reset */
-        if (!vlapic->vcpu || !vlapic_enabled(vlapic))
-            return 0;
+        if (unlikely(!vlapic || !vlapic_enabled(vlapic)))
+            return result;
 
         if (test_and_set_bit(vector, &vlapic->irr[0])) {
             printk("<vlapic_accept_irq>"
@@ -199,6 +213,7 @@
             }
         }
         evtchn_set_pending(vlapic->vcpu, iopacket_port(vlapic->domain));
+        result = 1;
         break;
 
     case VLAPIC_DELIV_MODE_RESERVED:
@@ -269,15 +284,12 @@
 
     old = next = d->arch.vmx_platform.round_info[vector];
 
-    next++;
-    if (next == MAX_VIRT_CPUS || !d->vcpu[next])
-        next = 0;
-
     do {
         /* the vcpu array is arranged according to vcpu_id */
         if (test_bit(next, &bitmap)) {
             target = d->vcpu[next]->arch.arch_vmx.vlapic;
-            if (!vlapic_enabled(target)) {
+
+            if (!target || !vlapic_enabled(target)) {
                 printk("warning: targe round robin local apic disabled\n");
                 /* XXX should we domain crash?? Or should we return NULL */
             }
@@ -285,7 +297,9 @@
         }
 
         next ++;
-        if (next == MAX_VIRT_CPUS || !d->vcpu[next])
+        if (!d->vcpu[next] ||
+            !test_bit(_VCPUF_initialised, &d->vcpu[next]->vcpu_flags) ||
+            next == MAX_VIRT_CPUS)
             next = 0;
     }while(next != old);
 
@@ -308,10 +322,8 @@
     vlapic_clear_isr(vlapic, vector);
     vlapic_update_ppr(vlapic);
 
-    if (test_and_clear_bit(vector, &vlapic->tmr[0])) {
-        extern void ioapic_update_EOI(struct domain *d, int vector);
+    if (test_and_clear_bit(vector, &vlapic->tmr[0]))
         ioapic_update_EOI(vlapic->domain, vector);
-    }
 }
 
 int vlapic_check_vector(struct vlapic *vlapic,
@@ -319,7 +331,7 @@
 {
     if ((dm == VLAPIC_DELIV_MODE_FIXED) && (vector < 16)) {
         vlapic->err_status |= 0x40;
-        vlapic_accept_irq(vlapic, VLAPIC_DELIV_MODE_FIXED,
+        vlapic_accept_irq(vlapic->vcpu, VLAPIC_DELIV_MODE_FIXED,
           vlapic_lvt_vector(vlapic, VLAPIC_LVT_ERROR), 0, 0);
         printk("<vlapic_check_vector>: check fail\n");
         return 0;
@@ -340,7 +352,6 @@
 
     struct vlapic *target;
     struct vcpu *v = NULL;
-    int result = 0;
     uint32_t lpr_map;
 
     VMX_DBG_LOG(DBG_LEVEL_VLAPIC, "vlapic_ipi: "
@@ -352,32 +363,27 @@
                 delivery_mode, vector);
 
     for_each_vcpu ( vlapic->domain, v ) {
-        target = VLAPIC(v);
-        if (vlapic_match_dest(target, vlapic, short_hand,
+        if (vlapic_match_dest(v, vlapic, short_hand,
                               dest, dest_mode, delivery_mode)) {
             if (delivery_mode == VLAPIC_DELIV_MODE_LPRI) {
                 set_bit(v->vcpu_id, &lpr_map);
-            }else
-                result = vlapic_accept_irq(target, delivery_mode,
-                  vector, level, trig_mode);
+            } else
+                vlapic_accept_irq(v, delivery_mode,
+                                  vector, level, trig_mode);
         }
     }
 
     if (delivery_mode == VLAPIC_DELIV_MODE_LPRI) {
-        extern struct vlapic*
-          apic_round_robin(struct domain *d,
-            uint8_t dest_mode, uint8_t vector, uint32_t bitmap);
-
         v = vlapic->vcpu;
         target = apic_round_robin(v->domain, dest_mode, vector, lpr_map);
 
         if (target)
-            vlapic_accept_irq(target, delivery_mode,
-              vector, level, trig_mode);
-    }
-}
-
-void vlapic_begin_timer(struct vlapic *vlapic)
+            vlapic_accept_irq(target->vcpu, delivery_mode,
+                              vector, level, trig_mode);
+    }
+}
+
+static void vlapic_begin_timer(struct vlapic *vlapic)
 {
     s_time_t cur = NOW(), offset;
 
@@ -559,7 +565,9 @@
 
     if ( len != 4) {
         /* some bugs on kernel cause read this with byte*/
-        printk("Local APIC read with len = %lx, should be 4 instead\n", len);
+        VMX_DBG_LOG(DBG_LEVEL_VLAPIC,
+                    "Local APIC read with len = %lx, should be 4 instead\n",
+                    len);
     }
 
     alignment = offset & 0x3;
@@ -737,12 +745,13 @@
         vlapic->timer_current = val;
         vlapic->timer_current_update = NOW();
 
+        vlapic_begin_timer(vlapic);
+
         VMX_DBG_LOG(DBG_LEVEL_VLAPIC, "timer_init %x timer_current %x"
                     "timer_current_update %08x%08x",
                     vlapic->timer_initial, vlapic->timer_current,
                     (uint32_t)(vlapic->timer_current_update >> 32),
                     (uint32_t)vlapic->timer_current_update);
-                    vlapic_begin_timer(vlapic);
         break;
 
     case APIC_TDCR:
@@ -827,6 +836,7 @@
         }
         else
             vlapic->intr_pending_count[vlapic_lvt_vector(vlapic, 
VLAPIC_LVT_TIMER)]++;
+        evtchn_set_pending(vlapic->vcpu, iopacket_port(vlapic->domain));
     }
 
     vlapic->timer_current_update = NOW();
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/vmx_vmcs.c
--- a/xen/arch/x86/vmx_vmcs.c   Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/vmx_vmcs.c   Sat Nov 19 05:16:29 2005
@@ -157,13 +157,13 @@
     mpfn = get_mfn_from_pfn(E820_MAP_PAGE >> PAGE_SHIFT);
     if (mpfn == INVALID_MFN) {
         printk("Can not find E820 memory map page for VMX domain.\n");
-        domain_crash();
+        domain_crash(d);
     }
 
     p = map_domain_page(mpfn);
     if (p == NULL) {
         printk("Can not map E820 memory map page for VMX domain.\n");
-        domain_crash();
+        domain_crash(d);
     }
 
     e820_map_nr = *(p + E820_MAP_NR_OFFSET);
@@ -182,7 +182,7 @@
         printk("Can not get io request shared page"
                " from E820 memory map for VMX domain.\n");
         unmap_domain_page(p);
-        domain_crash();
+        domain_crash(d);
     }
     unmap_domain_page(p);
 
@@ -190,13 +190,13 @@
     mpfn = get_mfn_from_pfn(gpfn);
     if (mpfn == INVALID_MFN) {
         printk("Can not find io request shared page for VMX domain.\n");
-        domain_crash();
+        domain_crash(d);
     }
 
     p = map_domain_page(mpfn);
     if (p == NULL) {
         printk("Can not map io request shared page for VMX domain.\n");
-        domain_crash();
+        domain_crash(d);
     }
     d->arch.vmx_platform.shared_page_va = (unsigned long)p;
 
@@ -332,7 +332,7 @@
     error |= __vmwrite(GUEST_TR_BASE, 0);
     error |= __vmwrite(GUEST_TR_LIMIT, 0xff);
 
-    __vmwrite(GUEST_CR3, pagetable_get_paddr(v->arch.guest_table));
+    __vmwrite(GUEST_CR3, pagetable_get_paddr(v->domain->arch.phys_table));
     __vmwrite(HOST_CR3, pagetable_get_paddr(v->arch.monitor_table));
     __vmwrite(HOST_RSP, (unsigned long)get_stack_bottom());
 
@@ -564,19 +564,14 @@
 
 void destroy_vmcs(struct arch_vmx_struct *arch_vmx)
 {
-    if(arch_vmx->vmcs != NULL)
-        free_vmcs(arch_vmx->vmcs);
-    if(arch_vmx->io_bitmap_a != 0) {
-        free_xenheap_pages(
-            arch_vmx->io_bitmap_a, get_order_from_bytes(0x1000));
-        arch_vmx->io_bitmap_a = 0;
-    }
-    if(arch_vmx->io_bitmap_b != 0) {
-        free_xenheap_pages(
-            arch_vmx->io_bitmap_b, get_order_from_bytes(0x1000));
-        arch_vmx->io_bitmap_b = 0;
-    }
-    arch_vmx->vmcs = 0;
+    free_vmcs(arch_vmx->vmcs);
+    arch_vmx->vmcs = NULL;
+
+    free_xenheap_pages(arch_vmx->io_bitmap_a, get_order_from_bytes(0x1000));
+    arch_vmx->io_bitmap_a = NULL;
+
+    free_xenheap_pages(arch_vmx->io_bitmap_b, get_order_from_bytes(0x1000));
+    arch_vmx->io_bitmap_b = NULL;
 }
 
 /*
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/x86_32/asm-offsets.c
--- a/xen/arch/x86/x86_32/asm-offsets.c Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/x86_32/asm-offsets.c Sat Nov 19 05:16:29 2005
@@ -75,7 +75,6 @@
     BLANK();
 
     OFFSET(TRAPBOUNCE_error_code, struct trap_bounce, error_code);
-    OFFSET(TRAPBOUNCE_cr2, struct trap_bounce, cr2);
     OFFSET(TRAPBOUNCE_flags, struct trap_bounce, flags);
     OFFSET(TRAPBOUNCE_cs, struct trap_bounce, cs);
     OFFSET(TRAPBOUNCE_eip, struct trap_bounce, eip);
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/x86_32/entry.S
--- a/xen/arch/x86/x86_32/entry.S       Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/x86_32/entry.S       Sat Nov 19 05:16:29 2005
@@ -156,7 +156,7 @@
          * By this time, all the setups in the VMCS must be complete.
          */
         .if \launch
-        /* VMLUANCH */
+        /* VMLAUNCH */
         .byte 0x0f,0x01,0xc2
         pushf
         call vm_launch_fail
@@ -394,37 +394,37 @@
         shll $16,%eax                    # Bits 16-23: saved_upcall_mask
         movw UREGS_cs+4(%esp),%ax        # Bits  0-15: CS
 FLT15:  movl %eax,%gs:4(%esi) 
+        test $0x00FF0000,%eax            # Bits 16-23: saved_upcall_mask
+        setz %ch                         # %ch == !saved_upcall_mask
         movl UREGS_eflags+4(%esp),%eax
+        andl $~X86_EFLAGS_IF,%eax
+        shlb $1,%ch                      # Bit 9 (EFLAGS.IF)
+        orb  %ch,%ah                     # Fold EFLAGS.IF into %eax
 FLT16:  movl %eax,%gs:8(%esi)
         test $TBF_EXCEPTION_ERRCODE,%cl
         jz   1f
         subl $4,%esi                    # push error_code onto guest frame
         movl TRAPBOUNCE_error_code(%edx),%eax
 FLT17:  movl %eax,%gs:(%esi)
-        testb $TBF_EXCEPTION_CR2,%cl
-        jz   2f
-        subl $4,%esi                    # push %cr2 onto guest frame
-        movl TRAPBOUNCE_cr2(%edx),%eax
-FLT18:  movl %eax,%gs:(%esi)
 1:      testb $TBF_FAILSAFE,%cl
         jz   2f
         subl $16,%esi                # add DS/ES/FS/GS to failsafe stack frame
         testl $X86_EFLAGS_VM,UREGS_eflags+4(%esp)
         jz   nvm86_2
         xorl %eax,%eax               # VM86: we write zero selector values
-FLT19:  movl %eax,%gs:(%esi) 
-FLT20:  movl %eax,%gs:4(%esi)
-FLT21:  movl %eax,%gs:8(%esi) 
-FLT22:  movl %eax,%gs:12(%esi)
+FLT18:  movl %eax,%gs:(%esi) 
+FLT19:  movl %eax,%gs:4(%esi)
+FLT20:  movl %eax,%gs:8(%esi) 
+FLT21:  movl %eax,%gs:12(%esi)
         jmp  2f
 nvm86_2:movl UREGS_ds+4(%esp),%eax   # non-VM86: write real selector values
-FLT23:  movl %eax,%gs:(%esi) 
+FLT22:  movl %eax,%gs:(%esi) 
         movl UREGS_es+4(%esp),%eax
-FLT24:  movl %eax,%gs:4(%esi)
+FLT23:  movl %eax,%gs:4(%esi)
         movl UREGS_fs+4(%esp),%eax
-FLT25:  movl %eax,%gs:8(%esi) 
+FLT24:  movl %eax,%gs:8(%esi) 
         movl UREGS_gs+4(%esp),%eax
-FLT26:  movl %eax,%gs:12(%esi)
+FLT25:  movl %eax,%gs:12(%esi)
 2:      testl $X86_EFLAGS_VM,UREGS_eflags+4(%esp)
         jz   nvm86_3
         xorl %eax,%eax      /* zero DS-GS, just as a real CPU would */
@@ -456,7 +456,6 @@
         .long FLT20,domain_crash_synchronous , FLT21,domain_crash_synchronous
         .long FLT22,domain_crash_synchronous , FLT23,domain_crash_synchronous
         .long FLT24,domain_crash_synchronous , FLT25,domain_crash_synchronous
-        .long FLT26,domain_crash_synchronous
 .previous
 
         ALIGN
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/x86_32/traps.c
--- a/xen/arch/x86/x86_32/traps.c       Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/x86_32/traps.c       Sat Nov 19 05:16:29 2005
@@ -84,32 +84,37 @@
 
 void show_page_walk(unsigned long addr)
 {
-    unsigned long pfn = read_cr3() >> PAGE_SHIFT;
+    unsigned long mfn = read_cr3() >> PAGE_SHIFT;
     intpte_t *ptab, ent;
+    unsigned long pfn; 
 
     printk("Pagetable walk from %08lx:\n", addr);
 
 #ifdef CONFIG_X86_PAE
-    ptab = map_domain_page(pfn);
-    ent = ptab[l3_table_offset(addr)];
-    printk(" L3 = %"PRIpte"\n", ent);
+    ptab = map_domain_page(mfn);
+    ent  = ptab[l3_table_offset(addr)];
+    pfn  = machine_to_phys_mapping[(u32)(ent >> PAGE_SHIFT)]; 
+    printk(" L3 = %"PRIpte" %08lx\n", ent, pfn);
     unmap_domain_page(ptab);
     if ( !(ent & _PAGE_PRESENT) )
         return;
-    pfn = ent >> PAGE_SHIFT;
+    mfn = ent >> PAGE_SHIFT;
 #endif
 
-    ptab = map_domain_page(pfn);
-    ent = ptab[l2_table_offset(addr)];
-    printk("  L2 = %"PRIpte" %s\n", ent, (ent & _PAGE_PSE) ? "(PSE)" : "");
+    ptab = map_domain_page(mfn);
+    ent  = ptab[l2_table_offset(addr)];
+    pfn  = machine_to_phys_mapping[(u32)(ent >> PAGE_SHIFT)]; 
+    printk("  L2 = %"PRIpte" %08lx %s\n", ent, pfn, 
+           (ent & _PAGE_PSE) ? "(PSE)" : "");
     unmap_domain_page(ptab);
     if ( !(ent & _PAGE_PRESENT) || (ent & _PAGE_PSE) )
         return;
-    pfn = ent >> PAGE_SHIFT;
+    mfn = ent >> PAGE_SHIFT;
 
     ptab = map_domain_page(ent >> PAGE_SHIFT);
-    ent = ptab[l2_table_offset(addr)];
-    printk("   L1 = %"PRIpte"\n", ent);
+    ent  = ptab[l1_table_offset(addr)];
+    pfn  = machine_to_phys_mapping[(u32)(ent >> PAGE_SHIFT)]; 
+    printk("   L1 = %"PRIpte" %08lx\n", ent, pfn);
     unmap_domain_page(ptab);
 }
 
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/x86_64/asm-offsets.c
--- a/xen/arch/x86/x86_64/asm-offsets.c Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/x86_64/asm-offsets.c Sat Nov 19 05:16:29 2005
@@ -75,7 +75,6 @@
     BLANK();
 
     OFFSET(TRAPBOUNCE_error_code, struct trap_bounce, error_code);
-    OFFSET(TRAPBOUNCE_cr2, struct trap_bounce, cr2);
     OFFSET(TRAPBOUNCE_flags, struct trap_bounce, flags);
     OFFSET(TRAPBOUNCE_cs, struct trap_bounce, cs);
     OFFSET(TRAPBOUNCE_eip, struct trap_bounce, eip);
diff -r e62c54ab862f -r 878a9891b056 xen/arch/x86/x86_64/entry.S
--- a/xen/arch/x86/x86_64/entry.S       Sat Nov 19 05:06:09 2005
+++ b/xen/arch/x86/x86_64/entry.S       Sat Nov 19 05:16:29 2005
@@ -352,8 +352,6 @@
 FLT2:   movq  %rax,32(%rsi)             # SS
         movq  UREGS_rsp+8(%rsp),%rax
 FLT3:   movq  %rax,24(%rsi)             # RSP
-        movq  UREGS_eflags+8(%rsp),%rax
-FLT4:   movq  %rax,16(%rsi)             # RFLAGS
         movq  VCPU_vcpu_info(%rbx),%rax
         pushq VCPUINFO_upcall_mask(%rax)
         testb $TBF_INTERRUPT,%cl
@@ -362,7 +360,15 @@
         popq  %rax
         shlq  $32,%rax                  # Bits 32-39: saved_upcall_mask
         movw  UREGS_cs+8(%rsp),%ax      # Bits  0-15: CS
-FLT5:   movq  %rax,8(%rsi)              # CS/saved_upcall_mask
+FLT4:   movq  %rax,8(%rsi)              # CS / saved_upcall_mask
+        shrq  $32,%rax
+        testb $0xFF,%al                 # Bits 0-7: saved_upcall_mask
+        setz  %ch                       # %ch == !saved_upcall_mask
+        movq  UREGS_eflags+8(%rsp),%rax
+        andq  $~X86_EFLAGS_IF,%rax
+        shlb  $1,%ch                    # Bit 9 (EFLAGS.IF)
+        orb   %ch,%ah                   # Fold EFLAGS.IF into %eax
+FLT5:   movq  %rax,16(%rsi)             # RFLAGS
         movq  UREGS_rip+8(%rsp),%rax
 FLT6:   movq  %rax,(%rsi)               # RIP
         testb $TBF_EXCEPTION_ERRCODE,%cl
@@ -370,27 +376,22 @@
         subq  $8,%rsi
         movl  TRAPBOUNCE_error_code(%rdx),%eax
 FLT7:   movq  %rax,(%rsi)               # ERROR CODE
-        testb $TBF_EXCEPTION_CR2,%cl
-        jz    2f
-        subq  $8,%rsi
-        movq  TRAPBOUNCE_cr2(%rdx),%rax
-FLT8:   movq  %rax,(%rsi)               # CR2
 1:      testb $TBF_FAILSAFE,%cl
         jz    2f
         subq  $32,%rsi
         movl  %gs,%eax
-FLT9:   movq  %rax,24(%rsi)             # GS
+FLT8:   movq  %rax,24(%rsi)             # GS
         movl  %fs,%eax
-FLT10:  movq  %rax,16(%rsi)             # FS
+FLT9:   movq  %rax,16(%rsi)             # FS
         movl  %es,%eax
-FLT11:  movq  %rax,8(%rsi)              # ES
+FLT10:  movq  %rax,8(%rsi)              # ES
         movl  %ds,%eax
-FLT12:  movq  %rax,(%rsi)               # DS
+FLT11:  movq  %rax,(%rsi)               # DS
 2:      subq  $16,%rsi
         movq  UREGS_r11+8(%rsp),%rax
-FLT13:  movq  %rax,8(%rsi)              # R11
+FLT12:  movq  %rax,8(%rsi)              # R11
         movq  UREGS_rcx+8(%rsp),%rax
-FLT14:  movq  %rax,(%rsi)               # RCX
+FLT13:  movq  %rax,(%rsi)               # RCX
         /* Rewrite our stack frame and return to guest-OS mode. */
         /* IA32 Ref. Vol. 3: TF, VM, RF and NT flags are cleared on trap. */
         movl  $TRAP_syscall,UREGS_entry_vector+8(%rsp)
@@ -411,7 +412,6 @@
         .quad  FLT8,domain_crash_synchronous ,  FLT9,domain_crash_synchronous
         .quad FLT10,domain_crash_synchronous , FLT11,domain_crash_synchronous
         .quad FLT12,domain_crash_synchronous , FLT13,domain_crash_synchronous
-        .quad FLT14,domain_crash_synchronous
 .previous
 
         ALIGN
diff -r e62c54ab862f -r 878a9891b056 xen/common/domain.c
--- a/xen/common/domain.c       Sat Nov 19 05:06:09 2005
+++ b/xen/common/domain.c       Sat Nov 19 05:16:29 2005
@@ -125,18 +125,27 @@
 }
 
 
-void domain_crash(void)
-{
-    printk("Domain %d (vcpu#%d) crashed on cpu#%d:\n",
-           current->domain->domain_id, current->vcpu_id, smp_processor_id());
-    show_registers(guest_cpu_user_regs());
-    domain_shutdown(SHUTDOWN_crash);
+void domain_crash(struct domain *d)
+{
+    if ( d == current->domain )
+    {
+        printk("Domain %d (vcpu#%d) crashed on cpu#%d:\n",
+               d->domain_id, current->vcpu_id, smp_processor_id());
+        show_registers(guest_cpu_user_regs());
+    }
+    else
+    {
+        printk("Domain %d reported crashed by domain %d on cpu#%d:\n",
+               d->domain_id, current->domain->domain_id, smp_processor_id());
+    }
+
+    domain_shutdown(d, SHUTDOWN_crash);
 }
 
 
 void domain_crash_synchronous(void)
 {
-    domain_crash();
+    domain_crash(current->domain);
     for ( ; ; )
         do_softirq();
 }
@@ -178,10 +187,9 @@
 __initcall(domain_shutdown_finaliser_init);
 
 
-void domain_shutdown(u8 reason)
-{
-    struct domain *d = current->domain;
-    struct vcpu   *v;
+void domain_shutdown(struct domain *d, u8 reason)
+{
+    struct vcpu *v;
 
     if ( d->domain_id == 0 )
     {
@@ -417,7 +425,9 @@
         break;
 
     case VCPUOP_up:
-        if ( test_and_clear_bit(_VCPUF_down, &v->vcpu_flags) )
+        if ( !test_bit(_VCPUF_initialised, &v->vcpu_flags) )
+            rc = -EINVAL;
+        else if ( test_and_clear_bit(_VCPUF_down, &v->vcpu_flags) )
             vcpu_wake(v);
         break;
 
diff -r e62c54ab862f -r 878a9891b056 xen/common/event_channel.c
--- a/xen/common/event_channel.c        Sat Nov 19 05:06:09 2005
+++ b/xen/common/event_channel.c        Sat Nov 19 05:16:29 2005
@@ -621,8 +621,7 @@
             (void)__evtchn_close(d, i);
 
     for ( i = 0; i < NR_EVTCHN_BUCKETS; i++ )
-        if ( d->evtchn[i] != NULL )
-            xfree(d->evtchn[i]);
+        xfree(d->evtchn[i]);
 }
 
 /*
diff -r e62c54ab862f -r 878a9891b056 xen/common/grant_table.c
--- a/xen/common/grant_table.c  Sat Nov 19 05:06:09 2005
+++ b/xen/common/grant_table.c  Sat Nov 19 05:16:29 2005
@@ -29,6 +29,7 @@
 #include <xen/shadow.h>
 #include <xen/mm.h>
 #include <acm/acm_hooks.h>
+#include <xen/trace.h>
 
 #if defined(CONFIG_X86_64)
 #define GRANT_PTE_FLAGS (_PAGE_PRESENT|_PAGE_ACCESSED|_PAGE_DIRTY|_PAGE_USER)
@@ -379,6 +380,8 @@
         }
     }
 
+    TRACE_1D(TRC_MEM_PAGE_GRANT_MAP, dom);
+
     ld->grant_table->maptrack[handle].domid         = dom;
     ld->grant_table->maptrack[handle].ref_and_flags =
         (ref << MAPTRACK_REF_SHIFT) |
@@ -462,6 +465,8 @@
         (void)__put_user(GNTST_bad_domain, &uop->status);
         return GNTST_bad_domain;
     }
+
+    TRACE_1D(TRC_MEM_PAGE_GRANT_UNMAP, dom);
 
     act = &rd->grant_table->active[ref];
     sha = &rd->grant_table->shared[ref];
@@ -802,6 +807,8 @@
         page_set_owner(page, e);
         
         spin_unlock(&e->page_alloc_lock);
+
+        TRACE_1D(TRC_MEM_PAGE_GRANT_TRANSFER, e->domain_id);
         
         /* Tell the guest about its new page frame. */
         sha = &e->grant_table->shared[gop->ref];
@@ -1107,8 +1114,7 @@
     if ( t != NULL )
     {
         xfree(t->active);
-        if ( t->maptrack != NULL )
-            free_xenheap_page(t->maptrack);
+        free_xenheap_page(t->maptrack);
         xfree(t);
     }
     return -ENOMEM;
diff -r e62c54ab862f -r 878a9891b056 xen/common/kernel.c
--- a/xen/common/kernel.c       Sat Nov 19 05:06:09 2005
+++ b/xen/common/kernel.c       Sat Nov 19 05:16:29 2005
@@ -124,10 +124,12 @@
         return 0;
     }
     
-    case XENVER_parameters:
+    case XENVER_platform_parameters:
     {
-        xen_parameters_info_t info = { .virt_start = HYPERVISOR_VIRT_START };
-        if ( copy_to_user(arg, &info, sizeof(info)) )
+        xen_platform_parameters_t params = {
+            .virt_start = HYPERVISOR_VIRT_START
+        };
+        if ( copy_to_user(arg, &params, sizeof(params)) )
             return -EFAULT;
         return 0;
         
diff -r e62c54ab862f -r 878a9891b056 xen/common/page_alloc.c
--- a/xen/common/page_alloc.c   Sat Nov 19 05:06:09 2005
+++ b/xen/common/page_alloc.c   Sat Nov 19 05:16:29 2005
@@ -470,6 +470,9 @@
 {
     unsigned long flags;
 
+    if ( v == NULL )
+        return;
+
     memguard_guard_range(v, 1 << (order + PAGE_SHIFT));    
 
     local_irq_save(flags);
diff -r e62c54ab862f -r 878a9891b056 xen/common/schedule.c
--- a/xen/common/schedule.c     Sat Nov 19 05:06:09 2005
+++ b/xen/common/schedule.c     Sat Nov 19 05:16:29 2005
@@ -12,15 +12,6 @@
  *              implements support functionality for the Xen scheduler API.
  *
  */
-
-/*#define WAKE_HISTO*/
-/*#define BLOCKTIME_HISTO*/
-
-#if defined(WAKE_HISTO)
-#define BUCKETS 31
-#elif defined(BLOCKTIME_HISTO)
-#define BUCKETS 200
-#endif
 
 #include <xen/config.h>
 #include <xen/init.h>
@@ -45,6 +36,8 @@
 static char opt_sched[10] = "sedf";
 string_param("sched", opt_sched);
 
+/*#define WAKE_HISTO*/
+/*#define BLOCKTIME_HISTO*/
 #if defined(WAKE_HISTO)
 #define BUCKETS 31
 #elif defined(BLOCKTIME_HISTO)
@@ -205,9 +198,7 @@
     if ( likely(domain_runnable(v)) )
     {
         SCHED_OP(wake, v);
-#ifdef WAKE_HISTO
         v->wokenup = NOW();
-#endif
     }
     clear_bit(_VCPUF_cpu_migrated, &v->vcpu_flags);
     spin_unlock_irqrestore(&schedule_data[v->processor].schedule_lock, flags);
@@ -267,7 +258,7 @@
     {
         TRACE_3D(TRC_SCHED_SHUTDOWN,
                  current->domain->domain_id, current->vcpu_id, arg);
-        domain_shutdown((u8)arg);
+        domain_shutdown(current->domain, (u8)arg);
         break;
     }
 
@@ -416,10 +407,25 @@
         return continue_running(prev);
     }
 
+    TRACE_2D(TRC_SCHED_SWITCH_INFPREV,
+             prev->domain->domain_id, now - prev->lastschd);
+    TRACE_3D(TRC_SCHED_SWITCH_INFNEXT,
+             next->domain->domain_id, now - next->wokenup, r_time);
+
     clear_bit(_VCPUF_running, &prev->vcpu_flags);
     set_bit(_VCPUF_running, &next->vcpu_flags);
 
     perfc_incrc(sched_ctx);
+
+    /*
+     * Logic of wokenup field in domain struct:
+     * Used to calculate "waiting time", which is the time that a domain
+     * spends being "runnable", but not actually running. wokenup is set
+     * set whenever a domain wakes from sleeping. However, if wokenup is not
+     * also set here then a preempted runnable domain will get a screwed up
+     * "waiting time" value next time it is scheduled.
+     */
+    prev->wokenup = NOW();
 
 #if defined(WAKE_HISTO)
     if ( !is_idle_task(next->domain) && next->wokenup )
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-ia64/vmx_vpd.h
--- a/xen/include/asm-ia64/vmx_vpd.h    Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-ia64/vmx_vpd.h    Sat Nov 19 05:16:29 2005
@@ -122,7 +122,7 @@
     do {                                                        \
         printk("__vmx_bug at %s:%d\n", __FILE__, __LINE__);     \
         show_registers(regs);                                   \
-        domain_crash();                                         \
+        domain_crash(current->domain);                          \
     } while (0)
 
 #endif //__ASSEMBLY__
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/config.h
--- a/xen/include/asm-x86/config.h      Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/config.h      Sat Nov 19 05:16:29 2005
@@ -291,6 +291,9 @@
 
 #define PDPT_VCPU_SHIFT       5
 #define PDPT_VCPU_VA_SHIFT    (PDPT_VCPU_SHIFT + PAGE_SHIFT)
+#define PDPT_L1_ENTRIES       (MAX_VIRT_CPUS << PDPT_VCPU_SHIFT)
+#define PDPT_L2_ENTRIES       \
+    ((PDPT_L1_ENTRIES + (1 << PAGETABLE_ORDER) - 1) >> PAGETABLE_ORDER)
 
 #if defined(__x86_64__)
 #define ELFSIZE 64
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/domain.h
--- a/xen/include/asm-x86/domain.h      Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/domain.h      Sat Nov 19 05:16:29 2005
@@ -8,7 +8,6 @@
 
 struct trap_bounce {
     unsigned long  error_code;
-    unsigned long  cr2;
     unsigned short flags; /* TBF_ */
     unsigned short cs;
     unsigned long  eip;
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/msr.h
--- a/xen/include/asm-x86/msr.h Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/msr.h Sat Nov 19 05:16:29 2005
@@ -133,35 +133,28 @@
 #define MSR_IA32_SYSENTER_ESP          0x175
 #define MSR_IA32_SYSENTER_EIP          0x176
 
-#define MSR_IA32_MCG_CAP       0x179
-#define MSR_IA32_MCG_STATUS        0x17a
-#define MSR_IA32_MCG_CTL       0x17b
-
-#define MSR_MTRRfix64K_00000   0x250
-#define MSR_MTRRfix16K_80000   0x258
-#define MSR_MTRRfix16K_A0000   0x259
-#define MSR_MTRRfix4K_C0000    0x268
-#define MSR_MTRRfix4K_C8000    0x269
-#define MSR_MTRRfix4K_D0000    0x26a
-#define MSR_MTRRfix4K_D8000    0x26b
-#define MSR_MTRRfix4K_E0000    0x26c
-#define MSR_MTRRfix4K_E8000    0x26d
-#define MSR_MTRRfix4K_F0000    0x26e
-#define MSR_MTRRfix4K_F8000    0x26f
-#define MSR_MTRRdefType                0x2ff
-
-#define MSR_IA32_MC0_CTL       0x400
-#define MSR_IA32_MC0_STATUS        0x401
-#define MSR_IA32_MC0_ADDR      0x402
-#define MSR_IA32_MC0_MISC      0x403
-
-#define MSR_IA32_DS_AREA       0x600
-
-#define MSR_IA32_BBL_CR_CTL            0x119
-
 #define MSR_IA32_MCG_CAP               0x179
 #define MSR_IA32_MCG_STATUS            0x17a
 #define MSR_IA32_MCG_CTL               0x17b
+
+/* P4/Xeon+ specific */
+#define MSR_IA32_MCG_EAX               0x180
+#define MSR_IA32_MCG_EBX               0x181
+#define MSR_IA32_MCG_ECX               0x182
+#define MSR_IA32_MCG_EDX               0x183
+#define MSR_IA32_MCG_ESI               0x184
+#define MSR_IA32_MCG_EDI               0x185
+#define MSR_IA32_MCG_EBP               0x186
+#define MSR_IA32_MCG_ESP               0x187
+#define MSR_IA32_MCG_EFLAGS            0x188
+#define MSR_IA32_MCG_EIP               0x189
+#define MSR_IA32_MCG_RESERVED          0x18A
+
+#define MSR_P6_EVNTSEL0                        0x186
+#define MSR_P6_EVNTSEL1                        0x187
+
+#define MSR_IA32_PERF_STATUS           0x198
+#define MSR_IA32_PERF_CTL              0x199
 
 #define MSR_IA32_THERM_CONTROL         0x19a
 #define MSR_IA32_THERM_INTERRUPT       0x19b
@@ -173,47 +166,101 @@
 #define MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL (1<<12)
 
 #define MSR_IA32_DEBUGCTLMSR           0x1d9
-#define MSR_IA32_DEBUGCTLMSR_LBR        (1<<0)
-#define MSR_IA32_DEBUGCTLMSR_BTF        (1<<1)
-#define MSR_IA32_DEBUGCTLMSR_TR                (1<<2)
-#define MSR_IA32_DEBUGCTLMSR_BTS        (1<<3)
-#define MSR_IA32_DEBUGCTLMSR_BTINT      (1<<4)
-
-#define MSR_IA32_LASTBRANCH_TOS         0x1da
-#define MSR_IA32_LASTBRANCH_0          0x1db
-#define MSR_IA32_LASTBRANCH_1          0x1dc
-#define MSR_IA32_LASTBRANCH_2          0x1dd
-#define MSR_IA32_LASTBRANCH_3          0x1de
+#define MSR_IA32_LASTBRANCHFROMIP      0x1db
+#define MSR_IA32_LASTBRANCHTOIP                0x1dc
+#define MSR_IA32_LASTINTFROMIP         0x1dd
+#define MSR_IA32_LASTINTTOIP           0x1de
 
 #define MSR_IA32_MC0_CTL               0x400
 #define MSR_IA32_MC0_STATUS            0x401
 #define MSR_IA32_MC0_ADDR              0x402
 #define MSR_IA32_MC0_MISC              0x403
 
-#define MSR_P6_PERFCTR0                        0xc1
-#define MSR_P6_PERFCTR1                        0xc2
-#define MSR_P6_EVNTSEL0                        0x186
-#define MSR_P6_EVNTSEL1                        0x187
-
-
-/* K7/K8 MSRs. Not complete. See the architecture manual for a more complete 
list. */
-#define MSR_K7_EVNTSEL0            0xC0010000
-#define MSR_K7_PERFCTR0            0xC0010004
-#define MSR_K7_EVNTSEL1            0xC0010001
-#define MSR_K7_PERFCTR1            0xC0010005
-#define MSR_K7_EVNTSEL2            0xC0010002
-#define MSR_K7_PERFCTR2            0xC0010006
-#define MSR_K7_EVNTSEL3            0xC0010003
-#define MSR_K7_PERFCTR3            0xC0010007
-#define MSR_K8_TOP_MEM1                   0xC001001A
-#define MSR_K8_TOP_MEM2                   0xC001001D
-#define MSR_K8_SYSCFG             0xC0000010   
-#define MSR_K7_HWCR                    0xC0010015
-#define MSR_K7_CLK_CTL                 0xC001001b
-#define MSR_K7_FID_VID_CTL             0xC0010041
-#define MSR_K7_VID_STATUS              0xC0010042
-
-/* K6 MSRs */
+/* Pentium IV performance counter MSRs */
+#define MSR_P4_BPU_PERFCTR0            0x300
+#define MSR_P4_BPU_PERFCTR1            0x301
+#define MSR_P4_BPU_PERFCTR2            0x302
+#define MSR_P4_BPU_PERFCTR3            0x303
+#define MSR_P4_MS_PERFCTR0             0x304
+#define MSR_P4_MS_PERFCTR1             0x305
+#define MSR_P4_MS_PERFCTR2             0x306
+#define MSR_P4_MS_PERFCTR3             0x307
+#define MSR_P4_FLAME_PERFCTR0          0x308
+#define MSR_P4_FLAME_PERFCTR1          0x309
+#define MSR_P4_FLAME_PERFCTR2          0x30a
+#define MSR_P4_FLAME_PERFCTR3          0x30b
+#define MSR_P4_IQ_PERFCTR0             0x30c
+#define MSR_P4_IQ_PERFCTR1             0x30d
+#define MSR_P4_IQ_PERFCTR2             0x30e
+#define MSR_P4_IQ_PERFCTR3             0x30f
+#define MSR_P4_IQ_PERFCTR4             0x310
+#define MSR_P4_IQ_PERFCTR5             0x311
+#define MSR_P4_BPU_CCCR0               0x360
+#define MSR_P4_BPU_CCCR1               0x361
+#define MSR_P4_BPU_CCCR2               0x362
+#define MSR_P4_BPU_CCCR3               0x363
+#define MSR_P4_MS_CCCR0                0x364
+#define MSR_P4_MS_CCCR1                0x365
+#define MSR_P4_MS_CCCR2                0x366
+#define MSR_P4_MS_CCCR3                0x367
+#define MSR_P4_FLAME_CCCR0             0x368
+#define MSR_P4_FLAME_CCCR1             0x369
+#define MSR_P4_FLAME_CCCR2             0x36a
+#define MSR_P4_FLAME_CCCR3             0x36b
+#define MSR_P4_IQ_CCCR0                0x36c
+#define MSR_P4_IQ_CCCR1                0x36d
+#define MSR_P4_IQ_CCCR2                0x36e
+#define MSR_P4_IQ_CCCR3                0x36f
+#define MSR_P4_IQ_CCCR4                0x370
+#define MSR_P4_IQ_CCCR5                0x371
+#define MSR_P4_ALF_ESCR0               0x3ca
+#define MSR_P4_ALF_ESCR1               0x3cb
+#define MSR_P4_BPU_ESCR0               0x3b2
+#define MSR_P4_BPU_ESCR1               0x3b3
+#define MSR_P4_BSU_ESCR0               0x3a0
+#define MSR_P4_BSU_ESCR1               0x3a1
+#define MSR_P4_CRU_ESCR0               0x3b8
+#define MSR_P4_CRU_ESCR1               0x3b9
+#define MSR_P4_CRU_ESCR2               0x3cc
+#define MSR_P4_CRU_ESCR3               0x3cd
+#define MSR_P4_CRU_ESCR4               0x3e0
+#define MSR_P4_CRU_ESCR5               0x3e1
+#define MSR_P4_DAC_ESCR0               0x3a8
+#define MSR_P4_DAC_ESCR1               0x3a9
+#define MSR_P4_FIRM_ESCR0              0x3a4
+#define MSR_P4_FIRM_ESCR1              0x3a5
+#define MSR_P4_FLAME_ESCR0             0x3a6
+#define MSR_P4_FLAME_ESCR1             0x3a7
+#define MSR_P4_FSB_ESCR0               0x3a2
+#define MSR_P4_FSB_ESCR1               0x3a3
+#define MSR_P4_IQ_ESCR0                0x3ba
+#define MSR_P4_IQ_ESCR1                0x3bb
+#define MSR_P4_IS_ESCR0                0x3b4
+#define MSR_P4_IS_ESCR1                0x3b5
+#define MSR_P4_ITLB_ESCR0              0x3b6
+#define MSR_P4_ITLB_ESCR1              0x3b7
+#define MSR_P4_IX_ESCR0                0x3c8
+#define MSR_P4_IX_ESCR1                0x3c9
+#define MSR_P4_MOB_ESCR0               0x3aa
+#define MSR_P4_MOB_ESCR1               0x3ab
+#define MSR_P4_MS_ESCR0                0x3c0
+#define MSR_P4_MS_ESCR1                0x3c1
+#define MSR_P4_PMH_ESCR0               0x3ac
+#define MSR_P4_PMH_ESCR1               0x3ad
+#define MSR_P4_RAT_ESCR0               0x3bc
+#define MSR_P4_RAT_ESCR1               0x3bd
+#define MSR_P4_SAAT_ESCR0              0x3ae
+#define MSR_P4_SAAT_ESCR1              0x3af
+#define MSR_P4_SSU_ESCR0               0x3be
+#define MSR_P4_SSU_ESCR1               0x3bf    /* guess: not defined in 
manual */
+#define MSR_P4_TBPU_ESCR0              0x3c2
+#define MSR_P4_TBPU_ESCR1              0x3c3
+#define MSR_P4_TC_ESCR0                0x3c4
+#define MSR_P4_TC_ESCR1                0x3c5
+#define MSR_P4_U2L_ESCR0               0x3b0
+#define MSR_P4_U2L_ESCR1               0x3b1
+
+/* AMD Defined MSRs */
 #define MSR_K6_EFER                    0xC0000080
 #define MSR_K6_STAR                    0xC0000081
 #define MSR_K6_WHCR                    0xC0000082
@@ -221,6 +268,19 @@
 #define MSR_K6_EPMR                    0xC0000086
 #define MSR_K6_PSOR                    0xC0000087
 #define MSR_K6_PFIR                    0xC0000088
+
+#define MSR_K7_EVNTSEL0                        0xC0010000
+#define MSR_K7_EVNTSEL1                        0xC0010001
+#define MSR_K7_EVNTSEL2                        0xC0010002
+#define MSR_K7_EVNTSEL3                        0xC0010003
+#define MSR_K7_PERFCTR0                        0xC0010004
+#define MSR_K7_PERFCTR1                        0xC0010005
+#define MSR_K7_PERFCTR2                        0xC0010006
+#define MSR_K7_PERFCTR3                        0xC0010007
+#define MSR_K7_HWCR                    0xC0010015
+#define MSR_K7_CLK_CTL                 0xC001001b
+#define MSR_K7_FID_VID_CTL             0xC0010041
+#define MSR_K7_FID_VID_STATUS          0xC0010042
 
 /* Centaur-Hauls/IDT defined MSRs. */
 #define MSR_IDT_FCR1                   0x107
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/page.h
--- a/xen/include/asm-x86/page.h        Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/page.h        Sat Nov 19 05:16:29 2005
@@ -232,9 +232,6 @@
 #define linear_l3_table(_ed) ((_ed)->arch.guest_vl3table)
 #define linear_l4_table(_ed) ((_ed)->arch.guest_vl4table)
 
-#define va_to_l1mfn(_ed, _va) \
-    (l2e_get_pfn(linear_l2_table(_ed)[_va>>L2_PAGETABLE_SHIFT]))
-
 #ifndef __ASSEMBLY__
 #if CONFIG_PAGING_LEVELS == 3
 extern root_pgentry_t idle_pg_table[ROOT_PAGETABLE_ENTRIES];
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/processor.h
--- a/xen/include/asm-x86/processor.h   Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/processor.h   Sat Nov 19 05:16:29 2005
@@ -121,7 +121,6 @@
 /* 'trap_bounce' flags values */
 #define TBF_EXCEPTION          1
 #define TBF_EXCEPTION_ERRCODE  2
-#define TBF_EXCEPTION_CR2      4
 #define TBF_INTERRUPT          8
 #define TBF_FAILSAFE          16
 
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/shadow.h
--- a/xen/include/asm-x86/shadow.h      Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/shadow.h      Sat Nov 19 05:16:29 2005
@@ -138,6 +138,14 @@
                                        struct domain_mmap_cache *cache);
 #if CONFIG_PAGING_LEVELS >= 3
 #include <asm/page-guest32.h>
+/*
+ * va_mask cannot be used because it's used by the shadow hash.
+ * Use the score area for for now.
+ */
+#define is_xen_l2_slot(t,s)                                                    
\
+    ( ((((t) & PGT_score_mask) >> PGT_score_shift) == 3) &&                    
\
+      ((s) >= (L2_PAGETABLE_FIRST_XEN_SLOT & (L2_PAGETABLE_ENTRIES - 1))) )
+
 extern unsigned long gva_to_gpa(unsigned long gva);
 extern void shadow_l3_normal_pt_update(struct domain *d,
                                        unsigned long pa, l3_pgentry_t l3e,
@@ -458,7 +466,7 @@
 
 /************************************************************************/
 
-static inline int __mark_dirty(struct domain *d, unsigned int mfn)
+static inline int __mark_dirty(struct domain *d, unsigned long mfn)
 {
     unsigned long pfn;
     int           rc = 0;
@@ -906,7 +914,7 @@
         guest_l2e_add_flags(gpde, _PAGE_ACCESSED);
 
         *gpde_p = gpde;
-    }
+    } 
 
     if ( l2e_get_intpte(spde) || l2e_get_intpte(gpde) )
         SH_VVLOG("%s: gpde=%" PRIpte ", new spde=%" PRIpte, __func__,
@@ -1355,7 +1363,7 @@
 }
 
 
-static inline void delete_shadow_status( 
+static inline void delete_shadow_status(
     struct domain *d, unsigned long gpfn, unsigned long gmfn, unsigned int 
stype)
 {
     struct shadow_status *p, *x, *n, *head;
@@ -1454,7 +1462,7 @@
     ASSERT(stype && !(stype & ~PGT_type_mask));
 
     x = head = hash_bucket(d, gpfn);
-   
+
     SH_VLOG("set gpfn=%lx smfn=%lx t=%lx bucket=%p(%p)",
              gpfn, smfn, stype, x, x->next);
     shadow_audit(d, 0);
@@ -1584,7 +1592,7 @@
 {
     struct vcpu *v = current;
     struct domain *d = v->domain;
-    l2_pgentry_t sl2e;
+    l2_pgentry_t sl2e = {0};
 
     __shadow_get_l2e(v, va, &sl2e);
     if ( !(l2e_get_flags(sl2e) & _PAGE_PRESENT) )
@@ -1731,7 +1739,7 @@
 #ifdef CONFIG_VMX
     if ( VMX_DOMAIN(v) )
         paging_enabled = vmx_paging_enabled(v);
-            
+
     else
 #endif
         // HACK ALERT: there's currently no easy way to figure out if a domU
@@ -1757,7 +1765,7 @@
         if ( shadow_mode_enabled(d) )
             v->arch.monitor_table = v->arch.shadow_table;
         else
-#ifdef __x86_64__
+#if CONFIG_PAGING_LEVELS == 4
         if ( !(v->arch.flags & TF_kernel_mode) )
             v->arch.monitor_table = v->arch.guest_table_user;
         else
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/shadow_64.h
--- a/xen/include/asm-x86/shadow_64.h   Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/shadow_64.h   Sat Nov 19 05:16:29 2005
@@ -29,6 +29,15 @@
 #include <asm/shadow.h>
 #include <asm/shadow_ops.h>
 
+extern struct shadow_ops MODE_B_HANDLER;
+
+#if CONFIG_PAGING_LEVELS == 3
+#define L4_PAGETABLE_SHIFT      39
+#define L4_PAGETABLE_ENTRIES    (1<<PAGETABLE_ORDER)
+typedef struct { intpte_t l4; } l4_pgentry_t;
+#define is_guest_l4_slot(_s) (1)
+#endif
+
 #define READ_FAULT  0
 #define WRITE_FAULT 1
 
@@ -94,6 +103,11 @@
             return  (((va) >> L2_PAGETABLE_SHIFT) & (L2_PAGETABLE_ENTRIES - 
1));
         case 3:
             return  (((va) >> L3_PAGETABLE_SHIFT) & (L3_PAGETABLE_ENTRIES - 
1));
+#if CONFIG_PAGING_LEVELS == 3
+        case 4:
+            return PAE_SHADOW_SELF_ENTRY;
+#endif
+
 #if CONFIG_PAGING_LEVELS >= 4
 #ifndef GUEST_PGENTRY_32
         case 4:
@@ -127,57 +141,73 @@
     }
 }
 
-static inline pgentry_64_t *__entry(
-    struct vcpu *v, u64 va, u32 flag)
+static inline int __entry(
+    struct vcpu *v, u64 va, pgentry_64_t *e_p, u32 flag)
 {
     int i;
     pgentry_64_t *le_e;
-    pgentry_64_t *le_p;
+    pgentry_64_t *le_p = NULL;
     unsigned long mfn;
     int index;
     u32 level = flag & L_MASK;
     struct domain *d = v->domain;
-
-    index = table_offset_64(va, ROOT_LEVEL_64);
-    if (flag & SHADOW_ENTRY)
+    int root_level;
+
+    if ( flag & SHADOW_ENTRY )
+    {
+       root_level =  ROOT_LEVEL_64;
+       index = table_offset_64(va, root_level);
         le_e = (pgentry_64_t *)&v->arch.shadow_vtable[index];
-    else
+    }
+    else /* guest entry */  
+    {
+        root_level = v->domain->arch.ops->guest_paging_levels;
+       index = table_offset_64(va, root_level);
         le_e = (pgentry_64_t *)&v->arch.guest_vtable[index];
-
+    }
     /*
      * If it's not external mode, then mfn should be machine physical.
      */
-    for (i = ROOT_LEVEL_64 - level; i > 0; i--) {
-        if (unlikely(!(entry_get_flags(*le_e) & _PAGE_PRESENT)))
-            return NULL;
-        mfn = entry_get_value(*le_e) >> PAGE_SHIFT;
-        if ((flag & GUEST_ENTRY) && shadow_mode_translate(d))
+    for (i = root_level - level; i > 0; i--) {
+        if ( unlikely(!(entry_get_flags(*le_e) & _PAGE_PRESENT)) ) {
+            if ( le_p )
+                unmap_domain_page(le_p);
+            return 0;
+        }
+        mfn = entry_get_pfn(*le_e);
+        if ( (flag & GUEST_ENTRY) && shadow_mode_translate(d) )
             mfn = get_mfn_from_pfn(mfn);
-        le_p = (pgentry_64_t *)phys_to_virt(mfn << PAGE_SHIFT);
+        if ( le_p )
+            unmap_domain_page(le_p);
+        le_p = (pgentry_64_t *)map_domain_page(mfn);
         index = table_offset_64(va, (level + i - 1));
         le_e = &le_p[index];
-
-    }
-    return le_e;
-
-}
-
-static inline pgentry_64_t *__rw_entry(
-    struct vcpu *ed, u64 va, void *e_p, u32 flag)
-{
-    pgentry_64_t *le_e = __entry(ed, va, flag);
+    }
+
+    if ( flag & SET_ENTRY )
+        *le_e = *e_p;
+    else
+        *e_p = *le_e;
+
+    if ( le_p )
+        unmap_domain_page(le_p);
+
+    return 1;
+
+}
+
+static inline int __rw_entry(
+    struct vcpu *v, u64 va, void *e_p, u32 flag)
+{
     pgentry_64_t *e = (pgentry_64_t *)e_p;
-    if (le_e == NULL)
-        return NULL;
 
     if (e) {
-        if (flag & SET_ENTRY)
-            *le_e = *e;
-        else
-            *e = *le_e;
-    }
-    return le_e;
-}
+        return __entry(v, va, e, flag);
+    }
+
+    return 0;
+}
+
 #define __shadow_set_l4e(v, va, value) \
   __rw_entry(v, va, value, SHADOW_ENTRY | SET_ENTRY | PAGING_L4)
 #define __shadow_get_l4e(v, va, sl4e) \
@@ -204,7 +234,7 @@
 #define __guest_get_l3e(v, va, sl3e) \
   __rw_entry(v, va, gl3e, GUEST_ENTRY | GET_ENTRY | PAGING_L3)
 
-static inline void *  __guest_set_l2e(
+static inline int  __guest_set_l2e(
     struct vcpu *v, u64 va, void *value, int size)
 {
     switch(size) {
@@ -216,21 +246,21 @@
                 l2va = (l2_pgentry_32_t *)v->arch.guest_vtable;
                 if (value)
                     l2va[l2_table_offset_32(va)] = *(l2_pgentry_32_t *)value;
-                return &l2va[l2_table_offset_32(va)];
+                return 1;
             }
         case 8:
             return __rw_entry(v, va, value, GUEST_ENTRY | SET_ENTRY | 
PAGING_L2);
         default:
             BUG();
-            return NULL;
-    }
-    return NULL;
+            return 0;
+    }
+    return 0;
 }
 
 #define __guest_set_l2e(v, va, value) \
-  ( __typeof__(value) )__guest_set_l2e(v, (u64)va, value, sizeof(*value))
-
-static inline void * __guest_get_l2e(
+    __guest_set_l2e(v, (u64)va, value, sizeof(*value))
+
+static inline int  __guest_get_l2e(
   struct vcpu *v, u64 va, void *gl2e, int size)
 {
     switch(size) {
@@ -241,21 +271,21 @@
                 l2va = (l2_pgentry_32_t *)v->arch.guest_vtable;
                 if (gl2e)
                     *(l2_pgentry_32_t *)gl2e = l2va[l2_table_offset_32(va)];
-                return &l2va[l2_table_offset_32(va)];
+                return 1;
             }
         case 8:
             return __rw_entry(v, va, gl2e, GUEST_ENTRY | GET_ENTRY | 
PAGING_L2);
         default:
             BUG();
-            return NULL;
-    }
-    return NULL;
+            return 0;
+    }
+    return 0;
 }
 
 #define __guest_get_l2e(v, va, gl2e) \
-  (__typeof__ (gl2e))__guest_get_l2e(v, (u64)va, gl2e, sizeof(*gl2e))
-
-static inline void *  __guest_set_l1e(
+    __guest_get_l2e(v, (u64)va, gl2e, sizeof(*gl2e))
+
+static inline int  __guest_set_l1e(
   struct vcpu *v, u64 va, void *value, int size)
 {
     switch(size) {
@@ -267,34 +297,34 @@
                 unsigned long l1mfn;
 
                 if (!__guest_get_l2e(v, va, &gl2e))
-                    return NULL;
+                    return 0;
                 if (unlikely(!(l2e_get_flags_32(gl2e) & _PAGE_PRESENT)))
-                    return NULL;
+                    return 0;
 
                 l1mfn = get_mfn_from_pfn(
                   l2e_get_pfn(gl2e));
 
-                l1va = (l1_pgentry_32_t *)
-                  phys_to_virt(l1mfn << L1_PAGETABLE_SHIFT);
+                l1va = (l1_pgentry_32_t *)map_domain_page(l1mfn);
                 if (value)
                     l1va[l1_table_offset_32(va)] = *(l1_pgentry_32_t *)value;
-
-                return &l1va[l1_table_offset_32(va)];
+                unmap_domain_page(l1va);
+
+                return 1;
             }
 
         case 8:
             return __rw_entry(v, va, value, GUEST_ENTRY | SET_ENTRY | 
PAGING_L1);
         default:
             BUG();
-            return NULL;
-    }
-    return NULL;
+            return 0;
+    }
+    return 0;
 }
 
 #define __guest_set_l1e(v, va, value) \
-  ( __typeof__(value) )__guest_set_l1e(v, (u64)va, value, sizeof(*value))
-
-static inline void *  __guest_get_l1e(
+     __guest_set_l1e(v, (u64)va, value, sizeof(*value))
+
+static inline int  __guest_get_l1e(
   struct vcpu *v, u64 va, void *gl1e, int size)
 {
     switch(size) {
@@ -306,34 +336,33 @@
                 unsigned long l1mfn;
 
                 if (!(__guest_get_l2e(v, va, &gl2e)))
-                    return NULL;
+                    return 0;
 
 
                 if (unlikely(!(l2e_get_flags_32(gl2e) & _PAGE_PRESENT)))
-                    return NULL;
+                    return 0;
 
 
                 l1mfn = get_mfn_from_pfn(
                   l2e_get_pfn(gl2e));
-                l1va = (l1_pgentry_32_t *) phys_to_virt(
-                  l1mfn << L1_PAGETABLE_SHIFT);
+                l1va = (l1_pgentry_32_t *) map_domain_page(l1mfn);
                 if (gl1e)
                     *(l1_pgentry_32_t *)gl1e = l1va[l1_table_offset_32(va)];
-
-                return &l1va[l1_table_offset_32(va)];
+                unmap_domain_page(l1va);
+                return 1;
             }
         case 8:
             // 64-bit guest
             return __rw_entry(v, va, gl1e, GUEST_ENTRY | GET_ENTRY | 
PAGING_L1);
         default:
             BUG();
-            return NULL;
-    }
-    return NULL;
+            return 0;
+    }
+    return 0;
 }
 
 #define __guest_get_l1e(v, va, gl1e) \
-  ( __typeof__(gl1e) )__guest_get_l1e(v, (u64)va, gl1e, sizeof(*gl1e))
+    __guest_get_l1e(v, (u64)va, gl1e, sizeof(*gl1e))
 
 static inline void entry_general(
   struct domain *d,
@@ -365,10 +394,16 @@
                 unmap_domain_page(l1_p);
             }
         } else {
-            sle = entry_from_pfn(
-                smfn,
-                (entry_get_flags(gle) | _PAGE_RW | _PAGE_ACCESSED) & 
~_PAGE_AVAIL);
-            entry_add_flags(gle, _PAGE_ACCESSED);
+            if (d->arch.ops->guest_paging_levels <= PAGING_L3
+                    && level == PAGING_L3) {
+                sle = entry_from_pfn(smfn, entry_get_flags(gle));
+            } else {
+
+                sle = entry_from_pfn(
+                  smfn,
+                  (entry_get_flags(gle) | _PAGE_RW | _PAGE_ACCESSED) & 
~_PAGE_AVAIL);
+                entry_add_flags(gle, _PAGE_ACCESSED);
+            }
         }
         // XXX mafetter: Hmm...
         //     Shouldn't the dirty log be checked/updated here?
@@ -392,7 +427,7 @@
 
     if ( entry_get_flags(gle) & _PAGE_PRESENT ) {
         if ((entry_get_flags(gle) & _PAGE_PSE) && level == PAGING_L2) {
-            smfn =  __shadow_status(d, entry_get_value(gle) >> PAGE_SHIFT, 
PGT_fl1_shadow);
+            smfn =  __shadow_status(d, entry_get_pfn(gle), PGT_fl1_shadow);
         } else {
             smfn =  __shadow_status(d, entry_get_pfn(gle), 
               shadow_level_to_type((level -1 )));
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/vmx_platform.h
--- a/xen/include/asm-x86/vmx_platform.h        Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/vmx_platform.h        Sat Nov 19 05:16:29 2005
@@ -55,17 +55,18 @@
 #define REPNZ   0x2
 #define OVERLAP 0x4
 
-#define INSTR_PIO 1
-#define INSTR_OR 2
-#define INSTR_AND 3
-#define INSTR_XOR 4
-#define INSTR_CMP 5
-#define INSTR_MOV 6
-#define INSTR_MOVS 7
-#define INSTR_MOVZ 8
-#define INSTR_STOS 9
-#define INSTR_TEST 10
-#define INSTR_BT 11
+#define INSTR_PIO   1
+#define INSTR_OR    2
+#define INSTR_AND   3
+#define INSTR_XOR   4
+#define INSTR_CMP   5
+#define INSTR_MOV   6
+#define INSTR_MOVS  7
+#define INSTR_MOVZX 8
+#define INSTR_MOVSX 9
+#define INSTR_STOS  10
+#define INSTR_TEST  11
+#define INSTR_BT    12
 
 struct instruction {
     __s8    instr; /* instruction type */
diff -r e62c54ab862f -r 878a9891b056 xen/include/asm-x86/vmx_vioapic.h
--- a/xen/include/asm-x86/vmx_vioapic.h Sat Nov 19 05:06:09 2005
+++ b/xen/include/asm-x86/vmx_vioapic.h Sat Nov 19 05:16:29 2005
@@ -92,9 +92,10 @@
 #define MAX_LAPIC_NUM        32
 
 typedef struct vmx_vioapic {
-    uint32_t ioregsel;
     uint32_t irr;
     uint32_t isr;           /* This is used for level trigger */
+    uint32_t imr;
+    uint32_t ioregsel;
     uint32_t flags;
     uint32_t lapic_count;
     uint32_t id;
@@ -113,6 +114,8 @@
 
 int vmx_vioapic_add_lapic(struct vlapic *vlapic, struct vcpu *v);
 
+void ioapic_update_EOI(struct domain *d, int vector);
+
 #ifdef VMX_DOMAIN_SAVE_RESTORE
 void ioapic_save(QEMUFile* f, void* opaque);
 int ioapic_load(QEMUFile* f, void* opaque, int version_id);
diff -r e62c54ab862f -r 878a9891b056 xen/include/public/arch-ia64.h
--- a/xen/include/public/arch-ia64.h    Sat Nov 19 05:06:09 2005
+++ b/xen/include/public/arch-ia64.h    Sat Nov 19 05:16:29 2005
@@ -271,12 +271,10 @@
 
 typedef mapped_regs_t vpd_t;
 
-#define __ARCH_HAS_VCPU_INFO
-
 typedef struct {
     unsigned int flags;
     unsigned long start_info_pfn;
-} arch_shared_info_t;  // DON'T PACK 
+} arch_shared_info_t;
 
 typedef struct vcpu_guest_context {
 #define VGCF_FPU_VALID (1<<0)
diff -r e62c54ab862f -r 878a9891b056 xen/include/public/arch-x86_32.h
--- a/xen/include/public/arch-x86_32.h  Sat Nov 19 05:06:09 2005
+++ b/xen/include/public/arch-x86_32.h  Sat Nov 19 05:16:29 2005
@@ -90,7 +90,7 @@
     uint16_t cs;
     uint8_t  saved_upcall_mask;
     uint8_t  _pad0;
-    uint32_t eflags;
+    uint32_t eflags;        /* eflags.IF == !saved_upcall_mask */
     uint32_t esp;
     uint16_t ss, _pad1;
     uint16_t es, _pad2;
@@ -132,6 +132,11 @@
     unsigned long pfn_to_mfn_frame_list_list; 
 } arch_shared_info_t;
 
+typedef struct {
+    unsigned long cr2;
+    unsigned long pad; /* sizeof(vcpu_info_t) == 16 */
+} arch_vcpu_info_t;
+
 #endif
 
 #endif
diff -r e62c54ab862f -r 878a9891b056 xen/include/public/arch-x86_64.h
--- a/xen/include/public/arch-x86_64.h  Sat Nov 19 05:06:09 2005
+++ b/xen/include/public/arch-x86_64.h  Sat Nov 19 05:16:29 2005
@@ -154,7 +154,7 @@
     uint16_t cs, _pad0[1];
     uint8_t  saved_upcall_mask;
     uint8_t  _pad1[3];
-    __DECL_REG(flags);
+    __DECL_REG(flags);      /* rflags.IF == !saved_upcall_mask */
     __DECL_REG(sp);
     uint16_t ss, _pad2[3];
     uint16_t es, _pad3[3];
@@ -201,6 +201,11 @@
     unsigned long pfn_to_mfn_frame_list_list; 
 } arch_shared_info_t;
 
+typedef struct {
+    unsigned long cr2;
+    unsigned long pad; /* sizeof(vcpu_info_t) == 32 */
+} arch_vcpu_info_t;
+
 #endif /* !__ASSEMBLY__ */
 
 #endif
diff -r e62c54ab862f -r 878a9891b056 xen/include/public/dom0_ops.h
--- a/xen/include/public/dom0_ops.h     Sat Nov 19 05:06:09 2005
+++ b/xen/include/public/dom0_ops.h     Sat Nov 19 05:16:29 2005
@@ -19,7 +19,7 @@
  * This makes sure that old versions of dom0 tools will stop working in a
  * well-defined way (rather than crashing the machine, for instance).
  */
-#define DOM0_INTERFACE_VERSION   0xAAAA1011
+#define DOM0_INTERFACE_VERSION   0xAAAA1012
 
 /************************************************************************/
 
diff -r e62c54ab862f -r 878a9891b056 xen/include/public/trace.h
--- a/xen/include/public/trace.h        Sat Nov 19 05:06:09 2005
+++ b/xen/include/public/trace.h        Sat Nov 19 05:16:29 2005
@@ -14,6 +14,7 @@
 #define TRC_SCHED   0x0002f000    /* Xen Scheduler trace      */
 #define TRC_DOM0OP  0x0004f000    /* Xen DOM0 operation trace */
 #define TRC_VMX     0x0008f000    /* Xen VMX trace            */
+#define TRC_MEM     0x000af000    /* Xen memory trace         */
 #define TRC_ALL     0xfffff000
 
 /* Trace subclasses */
@@ -40,6 +41,12 @@
 #define TRC_SCHED_S_TIMER_FN    (TRC_SCHED + 11)
 #define TRC_SCHED_T_TIMER_FN    (TRC_SCHED + 12)
 #define TRC_SCHED_DOM_TIMER_FN  (TRC_SCHED + 13)
+#define TRC_SCHED_SWITCH_INFPREV (TRC_SCHED + 14)
+#define TRC_SCHED_SWITCH_INFNEXT (TRC_SCHED + 15)
+
+#define TRC_MEM_PAGE_GRANT_MAP      (TRC_MEM + 1)
+#define TRC_MEM_PAGE_GRANT_UNMAP    (TRC_MEM + 2)
+#define TRC_MEM_PAGE_GRANT_TRANSFER (TRC_MEM + 3)
 
 /* trace events per subclass */
 #define TRC_VMX_VMEXIT          (TRC_VMXEXIT + 1)
diff -r e62c54ab862f -r 878a9891b056 xen/include/public/version.h
--- a/xen/include/public/version.h      Sat Nov 19 05:06:09 2005
+++ b/xen/include/public/version.h      Sat Nov 19 05:16:29 2005
@@ -34,10 +34,10 @@
 #define XENVER_changeset 4
 typedef char xen_changeset_info_t[64];
 
-#define XENVER_parameters 5
-typedef struct xen_parameters_info {
+#define XENVER_platform_parameters 5
+typedef struct xen_platform_parameters {
     unsigned long virt_start;
-} xen_parameters_info_t;
+} xen_platform_parameters_t;
 
 #endif /* __XEN_PUBLIC_VERSION_H__ */
 
diff -r e62c54ab862f -r 878a9891b056 xen/include/public/xen.h
--- a/xen/include/public/xen.h  Sat Nov 19 05:06:09 2005
+++ b/xen/include/public/xen.h  Sat Nov 19 05:16:29 2005
@@ -299,9 +299,7 @@
     uint8_t evtchn_upcall_pending;
     uint8_t evtchn_upcall_mask;
     unsigned long evtchn_pending_sel;
-#ifdef __ARCH_HAS_VCPU_INFO
     arch_vcpu_info_t arch;
-#endif
 } vcpu_info_t;
 
 typedef struct vcpu_time_info {
@@ -410,7 +408,7 @@
 #define MAX_GUEST_CMDLINE 1024
 typedef struct start_info {
     /* THE FOLLOWING ARE FILLED IN BOTH ON INITIAL BOOT AND ON RESUME.    */
-    char magic[32];             /* "Xen-<version>.<subversion>". */
+    char magic[32];             /* "xen-<version>-<platform>".            */
     unsigned long nr_pages;     /* Total pages allocated to this domain.  */
     unsigned long shared_info;  /* MACHINE address of shared info struct. */
     uint32_t flags;             /* SIF_xxx flags.                         */
diff -r e62c54ab862f -r 878a9891b056 xen/include/xen/event.h
--- a/xen/include/xen/event.h   Sat Nov 19 05:06:09 2005
+++ b/xen/include/xen/event.h   Sat Nov 19 05:16:29 2005
@@ -60,7 +60,7 @@
 
 /* Note: Bitwise operations result in fast code with no branches. */
 #define event_pending(v)                        \
-    ((v)->vcpu_info->evtchn_upcall_pending &    \
-     ~(v)->vcpu_info->evtchn_upcall_mask)
+    (!!(v)->vcpu_info->evtchn_upcall_pending &  \
+      !(v)->vcpu_info->evtchn_upcall_mask)
 
 #endif /* __XEN_EVENT_H__ */
diff -r e62c54ab862f -r 878a9891b056 xen/include/xen/sched.h
--- a/xen/include/xen/sched.h   Sat Nov 19 05:06:09 2005
+++ b/xen/include/xen/sched.h   Sat Nov 19 05:16:29 2005
@@ -220,14 +220,15 @@
 struct domain *find_domain_by_id(domid_t dom);
 extern void domain_destruct(struct domain *d);
 extern void domain_kill(struct domain *d);
-extern void domain_shutdown(u8 reason);
+extern void domain_shutdown(struct domain *d, u8 reason);
 extern void domain_pause_for_debugger(void);
 
 /*
- * Mark current domain as crashed. This function returns: the domain is not
- * synchronously descheduled from any processor.
- */
-extern void domain_crash(void);
+ * Mark specified domain as crashed. This function always returns, even if the
+ * caller is the specified domain. The domain is not synchronously descheduled
+ * from any processor.
+ */
+extern void domain_crash(struct domain *d);
 
 /*
  * Mark current domain as crashed and synchronously deschedule from the local
diff -r e62c54ab862f -r 878a9891b056 docs/src/user/securing_xen.tex
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/docs/src/user/securing_xen.tex    Sat Nov 19 05:16:29 2005
@@ -0,0 +1,85 @@
+\chapter{Securing Xen}
+
+This chapter describes how to secure a Xen system. It describes a number
+of scenarios and provides a corresponding set of best practices. It
+begins with a section devoted to understanding the security implications
+of a Xen system.
+
+
+\section{Xen Security Considerations}
+
+When deploying a Xen system, one must be sure to secure the management
+domain (Domain-0) as much as possible. If the management domain is
+compromised, all other domains are also vulnerable. The following are a
+set of best practices for Domain-0:
+
+\begin{enumerate}
+\item \textbf{Run the smallest number of necessary services.} The less
+  things that are present in a management partition, the better.
+  Remember, a service running as root in the management domain has full
+  access to all other domains on the system.
+\item \textbf{Use a firewall to restrict the traffic to the management
+    domain.} A firewall with default-reject rules will help prevent
+  attacks on the management domain.
+\item \textbf{Do not allow users to access Domain-0.} The Linux kernel
+  has been known to have local-user root exploits. If you allow normal
+  users to access Domain-0 (even as unprivileged users) you run the risk
+  of a kernel exploit making all of your domains vulnerable.
+\end{enumerate}
+
+\section{Security Scenarios}
+
+
+\subsection{The Isolated Management Network}
+
+In this scenario, each node has two network cards in the cluster. One
+network card is connected to the outside world and one network card is a
+physically isolated management network specifically for Xen instances to
+use.
+
+As long as all of the management partitions are trusted equally, this is
+the most secure scenario. No additional configuration is needed other
+than forcing Xend to bind to the management interface for relocation.
+
+\textbf{FIXME:} What is the option to allow for this?
+
+
+\subsection{A Subnet Behind a Firewall}
+
+In this scenario, each node has only one network card but the entire
+cluster sits behind a firewall. This firewall should do at least the
+following:
+
+\begin{enumerate}
+\item Prevent IP spoofing from outside of the subnet.
+\item Prevent access to the relocation port of any of the nodes in the
+  cluster except from within the cluster.
+\end{enumerate}
+
+The following iptables rules can be used on each node to prevent
+migrations to that node from outside the subnet assuming the main
+firewall does not do this for you:
+
+\begin{verbatim}
+# this command disables all access to the Xen relocation
+# port:
+iptables -A INPUT -p tcp --destination-port 8002 -j REJECT
+
+# this command enables Xen relocations only from the specific
+# subnet:
+iptables -I INPUT -p tcp -{}-source 192.168.1.1/8 \
+    --destination-port 8002 -j ACCEPT
+\end{verbatim}
+
+\subsection{Nodes on an Untrusted Subnet}
+
+Migration on an untrusted subnet is not safe in current versions of Xen.
+It may be possible to perform migrations through a secure tunnel via an
+VPN or SSH. The only safe option in the absence of a secure tunnel is to
+disable migration completely. The easiest way to do this is with
+iptables:
+
+\begin{verbatim}
+# this command disables all access to the Xen relocation port
+iptables -A INPUT -p tcp -{}-destination-port 8002 -j REJECT
+\end{verbatim}
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/net_driver_util.c
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/net_driver_util.c        Sat Nov 19 
05:16:29 2005
@@ -0,0 +1,67 @@
+/*****************************************************************************
+ *
+ * Utility functions for Xen network devices.
+ *
+ * Copyright (c) 2005 XenSource Ltd.
+ * 
+ * This file may be distributed separately from the Linux kernel, or
+ * incorporated into other software packages, subject to the following
+ * license:
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this source file (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy, modify,
+ * merge, publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so, subject
+ * to the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+
+#include <linux/if_ether.h>
+#include <linux/err.h>
+#include <asm-xen/net_driver_util.h>
+
+
+int xen_net_read_mac(struct xenbus_device *dev, u8 mac[])
+{
+       char *s;
+       int i;
+       char *e;
+       char *macstr = xenbus_read(NULL, dev->nodename, "mac", NULL);
+       if (IS_ERR(macstr)) {
+               return PTR_ERR(macstr);
+       }
+       s = macstr;
+       for (i = 0; i < ETH_ALEN; i++) {
+               mac[i] = simple_strtoul(s, &e, 16);
+               if (s == e || (e[0] != ':' && e[0] != 0)) {
+                       kfree(macstr);
+                       return -ENOENT;
+               }
+               s = &e[1];
+       }
+       kfree(macstr);
+       return 0;
+}
+
+
+/*
+ * Local variables:
+ *  c-file-style: "linux"
+ *  indent-tabs-mode: t
+ *  c-indent-level: 8
+ *  c-basic-offset: 8
+ *  tab-width: 8
+ * End:
+ */
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_client.c
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/drivers/xen/xenbus/xenbus_client.c   Sat Nov 19 
05:16:29 2005
@@ -0,0 +1,253 @@
+/******************************************************************************
+ * Client-facing interface for the Xenbus driver.  In other words, the
+ * interface between the Xenbus and the device-specific code, be it the
+ * frontend or the backend of that driver.
+ *
+ * Copyright (C) 2005 XenSource Ltd
+ * 
+ * This file may be distributed separately from the Linux kernel, or
+ * incorporated into other software packages, subject to the following license:
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this source file (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy, modify,
+ * merge, publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+
+#if 0
+#define DPRINTK(fmt, args...) \
+    printk("xenbus_client (%s:%d) " fmt ".\n", __FUNCTION__, __LINE__, ##args)
+#else
+#define DPRINTK(fmt, args...) ((void)0)
+#endif
+
+
+#include <asm-xen/evtchn.h>
+#include <asm-xen/gnttab.h>
+#include <asm-xen/xenbus.h>
+
+
+int xenbus_watch_path(struct xenbus_device *dev, const char *path,
+                     struct xenbus_watch *watch, 
+                     void (*callback)(struct xenbus_watch *,
+                                      const char **, unsigned int))
+{
+       int err;
+
+       watch->node = path;
+       watch->callback = callback;
+
+       err = register_xenbus_watch(watch);
+
+       if (err) {
+               watch->node = NULL;
+               watch->callback = NULL;
+               xenbus_dev_fatal(dev, err, "adding watch on %s", path);
+       }
+
+       return err;
+}
+EXPORT_SYMBOL(xenbus_watch_path);
+
+
+int xenbus_watch_path2(struct xenbus_device *dev, const char *path,
+                      const char *path2, struct xenbus_watch *watch, 
+                      void (*callback)(struct xenbus_watch *,
+                                       const char **, unsigned int))
+{
+       int err;
+       char *state =
+               kmalloc(strlen(path) + 1 + strlen(path2) + 1, GFP_KERNEL);
+       if (!state) {
+               xenbus_dev_fatal(dev, -ENOMEM, "allocating path for watch");
+               return -ENOMEM;
+       }
+       strcpy(state, path);
+       strcat(state, "/");
+       strcat(state, path2);
+
+       err = xenbus_watch_path(dev, state, watch, callback);
+
+       if (err) {
+               kfree(state);
+       }
+       return err;
+}
+EXPORT_SYMBOL(xenbus_watch_path2);
+
+
+int xenbus_switch_state(struct xenbus_device *dev,
+                       struct xenbus_transaction *xbt,
+                       XenbusState state)
+{
+       /* We check whether the state is currently set to the given value, and
+          if not, then the state is set.  We don't want to unconditionally
+          write the given state, because we don't want to fire watches
+          unnecessarily.
+        */
+
+       int current_state;
+
+       int err = xenbus_scanf(xbt, dev->nodename, "state", "%d",
+                              &current_state);
+       if (err == 1 && (XenbusState)current_state == state)
+               return 0;
+
+       err = xenbus_printf(xbt, dev->nodename, "state", "%d", state);
+       if (err) {
+               xenbus_dev_fatal(dev, err, "writing new state");
+               return err;
+       }
+       return 0;
+}
+EXPORT_SYMBOL(xenbus_switch_state);
+
+
+/**
+ * Return the path to the error node for the given device, or NULL on failure.
+ * If the value returned is non-NULL, then it is the caller's to kfree.
+ */
+static char *error_path(struct xenbus_device *dev)
+{
+       char *path_buffer = kmalloc(strlen("error/") + strlen(dev->nodename) +
+                                   1, GFP_KERNEL);
+       if (path_buffer == NULL) {
+               return NULL;
+       }
+
+       strcpy(path_buffer, "error/");
+       strcpy(path_buffer + strlen("error/"), dev->nodename);
+
+       return path_buffer;
+}
+
+
+void _dev_error(struct xenbus_device *dev, int err, const char *fmt,
+               va_list ap)
+{
+       int ret;
+       unsigned int len;
+       char *printf_buffer = NULL, *path_buffer = NULL;
+
+#define PRINTF_BUFFER_SIZE 4096
+       printf_buffer = kmalloc(PRINTF_BUFFER_SIZE, GFP_KERNEL);
+       if (printf_buffer == NULL)
+               goto fail;
+
+       len = sprintf(printf_buffer, "%i ", -err);
+       ret = vsnprintf(printf_buffer+len, PRINTF_BUFFER_SIZE-len, fmt, ap);
+
+       BUG_ON(len + ret > PRINTF_BUFFER_SIZE-1);
+       dev->has_error = 1;
+
+       path_buffer = error_path(dev);
+
+       if (path_buffer == NULL) {
+               printk("xenbus: failed to write error node for %s (%s)\n",
+                      dev->nodename, printf_buffer);
+               goto fail;
+       }
+
+       if (xenbus_write(NULL, path_buffer, "error", printf_buffer) != 0) {
+               printk("xenbus: failed to write error node for %s (%s)\n",
+                      dev->nodename, printf_buffer);
+               goto fail;
+       }
+
+fail:
+       if (printf_buffer)
+               kfree(printf_buffer);
+       if (path_buffer)
+               kfree(path_buffer);
+}
+
+
+void xenbus_dev_error(struct xenbus_device *dev, int err, const char *fmt,
+                     ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _dev_error(dev, err, fmt, ap);
+       va_end(ap);
+}
+EXPORT_SYMBOL(xenbus_dev_error);
+
+
+void xenbus_dev_fatal(struct xenbus_device *dev, int err, const char *fmt,
+                     ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _dev_error(dev, err, fmt, ap);
+       va_end(ap);
+       
+       xenbus_switch_state(dev, NULL, XenbusStateClosing);
+}
+EXPORT_SYMBOL(xenbus_dev_fatal);
+
+
+int xenbus_grant_ring(struct xenbus_device *dev, unsigned long ring_mfn)
+{
+       int err = gnttab_grant_foreign_access(dev->otherend_id, ring_mfn, 0);
+       if (err < 0)
+               xenbus_dev_fatal(dev, err, "granting access to ring page");
+       return err;
+}
+EXPORT_SYMBOL(xenbus_grant_ring);
+
+
+int xenbus_alloc_evtchn(struct xenbus_device *dev, int *port)
+{
+       evtchn_op_t op = {
+               .cmd = EVTCHNOP_alloc_unbound,
+               .u.alloc_unbound.dom = DOMID_SELF,
+               .u.alloc_unbound.remote_dom = dev->otherend_id };
+
+       int err = HYPERVISOR_event_channel_op(&op);
+       if (err)
+               xenbus_dev_fatal(dev, err, "allocating event channel");
+       else
+               *port = op.u.alloc_unbound.port;
+       return err;
+}
+EXPORT_SYMBOL(xenbus_alloc_evtchn);
+
+
+XenbusState xenbus_read_driver_state(const char *path)
+{
+       XenbusState result;
+
+       int err = xenbus_gather(NULL, path, "state", "%d", &result, NULL);
+       if (err)
+               result = XenbusStateClosed;
+
+       return result;
+}
+EXPORT_SYMBOL(xenbus_read_driver_state);
+
+
+/*
+ * Local variables:
+ *  c-file-style: "linux"
+ *  indent-tabs-mode: t
+ *  c-indent-level: 8
+ *  c-basic-offset: 8
+ *  tab-width: 8
+ * End:
+ */
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/net_driver_util.h
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/net_driver_util.h    Sat Nov 19 
05:16:29 2005
@@ -0,0 +1,56 @@
+/*****************************************************************************
+ *
+ * Utility functions for Xen network devices.
+ *
+ * Copyright (c) 2005 XenSource Ltd.
+ * 
+ * This file may be distributed separately from the Linux kernel, or
+ * incorporated into other software packages, subject to the following
+ * license:
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this source file (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy, modify,
+ * merge, publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so, subject
+ * to the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef _ASM_XEN_NET_DRIVER_UTIL_H
+#define _ASM_XEN_NET_DRIVER_UTIL_H
+
+
+#include <asm-xen/xenbus.h>
+
+
+/**
+ * Read the 'mac' node at the given device's node in the store, and parse that
+ * as colon-separated octets, placing result the given mac array.  mac must be
+ * a preallocated array of length ETH_ALEN (as declared in linux/if_ether.h).
+ * Return 0 on success, or -errno on error.
+ */
+int xen_net_read_mac(struct xenbus_device *dev, u8 mac[]);
+
+
+#endif /* _ASM_XEN_NET_DRIVER_UTIL_H */
+
+/*
+ * Local variables:
+ *  c-file-style: "linux"
+ *  indent-tabs-mode: t
+ *  c-indent-level: 8
+ *  c-basic-offset: 8
+ *  tab-width: 8
+ * End:
+ */
diff -r e62c54ab862f -r 878a9891b056 
linux-2.6-xen-sparse/include/asm-xen/xencons.h
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/linux-2.6-xen-sparse/include/asm-xen/xencons.h    Sat Nov 19 05:16:29 2005
@@ -0,0 +1,7 @@
+#ifndef __ASM_XENCONS_H__
+#define __ASM_XENCONS_H__
+
+void xencons_force_flush(void);
+void xencons_resume(void);
+
+#endif /* __ASM_XENCONS_H__ */
diff -r e62c54ab862f -r 878a9891b056 tools/python/xen/xm/tests/__init__.py
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/python/xen/xm/tests/__init__.py     Sat Nov 19 05:16:29 2005
@@ -0,0 +1,2 @@
+
+
diff -r e62c54ab862f -r 878a9891b056 tools/xenmon/COPYING
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xenmon/COPYING      Sat Nov 19 05:16:29 2005
@@ -0,0 +1,340 @@
+                   GNU GENERAL PUBLIC LICENSE
+                      Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                   GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                           NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+
+           How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program 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 General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff -r e62c54ab862f -r 878a9891b056 tools/xenmon/Makefile
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xenmon/Makefile     Sat Nov 19 05:16:29 2005
@@ -0,0 +1,51 @@
+# Copyright (C) HP Labs, Palo Alto and Fort Collins, 2005
+# Author: Diwaker Gupta <diwaker.gupta@xxxxxx>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; under version 2 of the License.
+#
+# This program 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 General Public License for more details.
+
+INSTALL         = install
+INSTALL_PROG    = $(INSTALL) -m0755
+INSTALL_DIR     = $(INSTALL) -d -m0755
+INSTALL_DATA    = $(INSTALL) -m064
+
+prefix=/usr/local
+mandir=$(prefix)/share/man
+man1dir=$(mandir)/man1
+sbindir=$(prefix)/sbin
+
+XEN_ROOT=../..
+include $(XEN_ROOT)/tools/Rules.mk
+
+CFLAGS += -Wall -Werror -g
+CFLAGS  += -I $(XEN_XC)
+CFLAGS  += -I $(XEN_LIBXC)
+LDFLAGS += -L $(XEN_LIBXC)
+
+BIN = setmask xenbaked
+SCRIPTS = xenmon.py
+
+all: build
+
+build: $(BIN)
+
+install: xenbaked setmask
+       [ -d $(DESTDIR)$(sbindir) ] || $(INSTALL_DIR) $(DESTDIR)$(sbindir)
+       $(INSTALL_PROG) xenbaked $(DESTDIR)$(sbindir)/xenbaked
+       $(INSTALL_PROG) setmask  $(DESTDIR)$(sbindir)/setmask
+       $(INSTALL_PROG) xenmon.py  $(DESTDIR)$(sbindir)/xenmon.py
+
+clean:
+       rm -f $(BIN)
+
+
+%: %.c Makefile
+       $(CC) $(CFLAGS) $(LDFLAGS) -lxenctrl -o $@ $<
+
+
diff -r e62c54ab862f -r 878a9891b056 tools/xenmon/README
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xenmon/README       Sat Nov 19 05:16:29 2005
@@ -0,0 +1,104 @@
+Xen Performance Monitor
+-----------------------
+
+The xenmon tools make use of the existing xen tracing feature to provide fine
+grained reporting of various domain related metrics. It should be stressed that
+the xenmon.py script included here is just an example of the data that may be
+displayed. The xenbake demon keeps a large amount of history in a shared memory
+area that may be accessed by tools such as xenmon.
+
+For each domain, xenmon reports various metrics. One part of the display is a
+group of metrics that have been accumulated over the last second, while another
+part of the display shows data measured over 10 seconds. Other measurement
+intervals are possible, but we have just chosen 1s and 10s as an example.
+
+
+Execution Count
+---------------
+ o The number of times that a domain was scheduled to run (ie, dispatched) over
+ the measurement interval
+
+
+CPU usage
+---------
+ o Total time used over the measurement interval
+ o Usage expressed as a percentage of the measurement interval
+ o Average cpu time used during each execution of the domain
+
+
+Waiting time
+------------
+This is how much time the domain spent waiting to run, or put another way, the
+amount of time the domain spent in the "runnable" state (or on the run queue)
+but not actually running. Xenmon displays:
+
+ o Total time waiting over the measurement interval
+ o Wait time expressed as a percentage of the measurement interval
+ o Average waiting time for each execution of the domain
+
+Blocked time
+------------
+This is how much time the domain spent blocked (or sleeping); Put another way,
+the amount of time the domain spent not needing/wanting the cpu because it was
+waiting for some event (ie, I/O). Xenmon reports:
+
+ o Total time blocked over the measurement interval
+ o Blocked time expressed as a percentage of the measurement interval
+ o Blocked time per I/O (see I/O count below)
+
+Allocation time
+---------------
+This is how much cpu time was allocated to the domain by the scheduler; This is
+distinct from cpu usage since the "time slice" given to a domain is frequently
+cut short for one reason or another, ie, the domain requests I/O and blocks.
+Xenmon reports:
+
+ o Average allocation time per execution (ie, time slice)
+ o Min and Max allocation times
+
+I/O Count
+---------
+This is a rough measure of I/O requested by the domain. The number of page
+exchanges (or page "flips") between the domain and dom0 are counted. The
+number of pages exchanged may not accurately reflect the number of bytes
+transferred to/from a domain due to partial pages being used by the network
+protocols, etc. But it does give a good sense of the magnitude of I/O being
+requested by a domain. Xenmon reports:
+
+ o Total number of page exchanges during the measurement interval
+ o Average number of page exchanges per execution of the domain
+
+
+Usage Notes and issues
+----------------------
+ - Start xenmon by simply running xenmon.py; The xenbake demon is started and
+   stopped automatically by xenmon.
+ - To see the various options for xenmon, run xenmon -h. Ditto for xenbaked.
+ - xenmon also has an option (-n) to output log data to a file instead of the
+   curses interface.
+ - NDOMAINS is defined to be 32, but can be changed by recompiling xenbaked
+ - Xenmon.py appears to create 1-2% cpu overhead; Part of this is just the
+   overhead of the python interpreter. Part of it may be the number of trace
+   records being generated. The number of trace records generated can be
+   limited by setting the trace mask (with a dom0 Op), which controls which
+   events cause a trace record to be emitted.
+ - To exit xenmon, type 'q'
+ - To cycle the display to other physical cpu's, type 'c'
+
+Future Work
+-----------
+o RPC interface to allow external entities to programmatically access 
processed data
+o I/O Count batching to reduce number of trace records generated
+
+Case Study
+----------
+We have written a case study which demonstrates some of the usefulness of
+this tool and the metrics reported. It is available at:
+http://www.hpl.hp.com/techreports/2005/HPL-2005-187.html
+
+Authors
+-------
+Diwaker Gupta   <diwaker.gupta@xxxxxx>
+Rob Gardner     <rob.gardner@xxxxxx>
+Lucy Cherkasova <lucy.cherkasova.hp.com>
+
diff -r e62c54ab862f -r 878a9891b056 tools/xenmon/setmask.c
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xenmon/setmask.c    Sat Nov 19 05:16:29 2005
@@ -0,0 +1,90 @@
+/******************************************************************************
+ * tools/xenmon/setmask.c
+ * 
+ * Simple utility for getting/setting the event mask
+ *
+ * Copyright (C) 2005 by Hewlett-Packard, Palo Alto and Fort Collins
+ *
+ * Authors: Lucy Cherkasova, lucy.cherkasova.hp.com
+ *          Rob Gardner, rob.gardner@xxxxxx
+ *          Diwaker Gupta, diwaker.gupta@xxxxxx
+ * Date:   August, 2005
+ * 
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; under version 2 of the License.
+ *
+ *  This program 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 General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <getopt.h>
+#include <xenctrl.h>
+#include <xen/xen.h>
+typedef struct { int counter; } atomic_t;
+#include <xen/trace.h>
+
+#define XENMON (TRC_SCHED_DOM_ADD | TRC_SCHED_DOM_REM | 
TRC_SCHED_SWITCH_INFPREV | TRC_SCHED_SWITCH_INFNEXT | TRC_SCHED_BLOCK | 
TRC_SCHED_SLEEP | TRC_SCHED_WAKE | TRC_MEM_PAGE_GRANT_TRANSFER)
+
+int main(int argc, char * argv[])
+{
+
+    dom0_op_t op; 
+    int ret;
+
+    int xc_handle = xc_interface_open();
+    op.cmd = DOM0_TBUFCONTROL;
+    op.interface_version = DOM0_INTERFACE_VERSION;
+    op.u.tbufcontrol.op  = DOM0_TBUF_GET_INFO;
+    ret = xc_dom0_op(xc_handle, &op);
+    if ( ret != 0 )
+    {
+        perror("Failure to get event mask from Xen");
+        exit(1);
+    }
+    else
+    {
+        printf("Current event mask: 0x%.8x\n", op.u.tbufcontrol.evt_mask);
+    }
+
+    op.cmd = DOM0_TBUFCONTROL;
+    op.interface_version = DOM0_INTERFACE_VERSION;
+    op.u.tbufcontrol.op  = DOM0_TBUF_SET_EVT_MASK;
+    op.u.tbufcontrol.evt_mask = XENMON;
+
+    ret = xc_dom0_op(xc_handle, &op);
+    printf("Setting mask to 0x%.8x\n", op.u.tbufcontrol.evt_mask);
+    if ( ret != 0 )
+    {
+        perror("Failure to get scheduler ID from Xen");
+        exit(1);
+    }
+
+    op.cmd = DOM0_TBUFCONTROL;
+    op.interface_version = DOM0_INTERFACE_VERSION;
+    op.u.tbufcontrol.op  = DOM0_TBUF_GET_INFO;
+    ret = xc_dom0_op(xc_handle, &op);
+    if ( ret != 0 )
+    {
+        perror("Failure to get event mask from Xen");
+        exit(1);
+    }
+    else
+    {
+        printf("Current event mask: 0x%.8x\n", op.u.tbufcontrol.evt_mask);
+    }
+    xc_interface_close(xc_handle);
+    return 0;
+}
diff -r e62c54ab862f -r 878a9891b056 tools/xenmon/xenbaked.c
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xenmon/xenbaked.c   Sat Nov 19 05:16:29 2005
@@ -0,0 +1,1029 @@
+/******************************************************************************
+ * tools/xenbaked.c
+ *
+ * Tool for collecting raw trace buffer data from Xen and 
+ *  performing some accumulation operations and other processing
+ *  on it.
+ *
+ * Copyright (C) 2004 by Intel Research Cambridge
+ * Copyright (C) 2005 by Hewlett Packard, Palo Alto and Fort Collins
+ *
+ * Authors: Diwaker Gupta, diwaker.gupta@xxxxxx
+ *          Rob Gardner, rob.gardner@xxxxxx
+ *          Lucy Cherkasova, lucy.cherkasova.hp.com
+ * Much code based on xentrace, authored by Mark Williamson, 
mark.a.williamson@xxxxxxxxx
+ * Date:   November, 2005
+ * 
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; under version 2 of the License.
+ *
+ *  This program 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 General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#include <time.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <argp.h>
+#include <signal.h>
+#include <xenctrl.h>
+#include <xen/xen.h>
+#include <string.h>
+
+#include "xc_private.h"
+typedef struct { int counter; } atomic_t;
+#define _atomic_read(v)                ((v).counter)
+
+#include <xen/trace.h>
+#include "xenbaked.h"
+
+extern FILE *stderr;
+
+/***** Compile time configuration of defaults ********************************/
+
+/* when we've got more records than this waiting, we log it to the output */
+#define NEW_DATA_THRESH 1
+
+/* sleep for this long (milliseconds) between checking the trace buffers */
+#define POLL_SLEEP_MILLIS 100
+
+/* Size of time period represented by each sample */
+#define MS_PER_SAMPLE 100
+
+/* CPU Frequency */
+#define MHZ
+#define CPU_FREQ 2660 MHZ
+
+/***** The code **************************************************************/
+
+typedef struct settings_st {
+    char *outfile;
+    struct timespec poll_sleep;
+    unsigned long new_data_thresh;
+    unsigned long ms_per_sample;
+    double cpu_freq;
+} settings_t;
+
+settings_t opts;
+
+int interrupted = 0; /* gets set if we get a SIGHUP */
+int rec_count = 0;
+time_t start_time;
+int dom0_flips = 0;
+
+_new_qos_data *new_qos;
+_new_qos_data **cpu_qos_data;
+
+
+#define ID(X) ((X>NDOMAINS-1)?(NDOMAINS-1):X)
+
+// array of currently running domains, indexed by cpu
+int *running = NULL;
+
+// number of cpu's on this platform
+int NCPU = 0;
+
+
+void init_current(int ncpu)
+{
+  running = calloc(ncpu, sizeof(int));
+  NCPU = ncpu;
+  printf("Initialized with %d %s\n", ncpu, (ncpu == 1) ? "cpu" : "cpu's");
+}
+
+int is_current(int domain, int cpu)
+{
+  //  int i;
+  
+  //  for (i=0; i<NCPU; i++)
+    if (running[cpu] == domain)
+      return 1;
+  return 0;
+}
+
+
+// return the domain that's currently running on the given cpu
+int current(int cpu)
+{
+  return running[cpu];
+}
+
+void set_current(int cpu, int domain)
+{
+  running[cpu] = domain;
+}
+
+
+
+void close_handler(int signal)
+{
+    interrupted = 1;
+}
+
+#if 0
+void dump_record(int cpu, struct t_rec *x)
+{
+    printf("record: cpu=%x, tsc=%lx, event=%x, d1=%lx\n", 
+            cpu, x->cycles, x->event, x->data[0]);
+}
+#endif
+
+/**
+ * millis_to_timespec - convert a time in milliseconds to a struct timespec
+ * @millis:             time interval in milliseconds
+ */
+struct timespec millis_to_timespec(unsigned long millis)
+{
+    struct timespec spec;
+
+    spec.tv_sec = millis / 1000;
+    spec.tv_nsec = (millis % 1000) * 1000;
+
+    return spec;
+}
+
+
+typedef struct 
+{
+    int event_count;
+    int event_id;
+    char *text;
+} stat_map_t;
+
+stat_map_t stat_map[] = {
+    { 0,       0,          "Other" },
+    { 0, TRC_SCHED_DOM_ADD, "Add Domain" },
+    { 0, TRC_SCHED_DOM_REM, "Remove Domain" },
+    { 0, TRC_SCHED_SLEEP, "Sleep" },
+    { 0, TRC_SCHED_WAKE,  "Wake" },
+    { 0, TRC_SCHED_BLOCK,  "Block" },
+    { 0, TRC_SCHED_SWITCH,  "Switch" },
+    { 0, TRC_SCHED_S_TIMER_FN, "Timer Func"},
+    { 0, TRC_SCHED_SWITCH_INFPREV,  "Switch Prev" },
+    { 0, TRC_SCHED_SWITCH_INFNEXT,  "Switch Next" },
+    { 0, TRC_MEM_PAGE_GRANT_MAP,  "Page Map" },
+    { 0, TRC_MEM_PAGE_GRANT_UNMAP,  "Page Unmap" },
+    { 0, TRC_MEM_PAGE_GRANT_TRANSFER,  "Page Transfer" },
+    { 0,      0,                0  }
+};
+
+
+void check_gotten_sum(void)
+{
+#if 0
+    uint64_t sum, ns;
+    extern uint64_t total_ns_gotten(uint64_t*);
+    double percent;
+    int i;
+
+    for (i=0; i<NCPU; i++) {
+      new_qos = cpu_qos_data[i];
+      ns = billion;
+      sum = total_ns_gotten(&ns);
+
+      printf("[cpu%d] ns_gotten over all domains = %lldns, over %lldns\n",
+             i, sum, ns);
+      percent = (double) sum;
+      percent = (100.0*percent) / (double)ns;
+      printf(" ==> ns_gotten = %7.3f%%\n", percent);
+    }
+#endif
+}
+
+
+
+void dump_stats(void) 
+{
+    stat_map_t *smt = stat_map;
+    time_t end_time, run_time;
+
+    time(&end_time);
+
+    run_time = end_time - start_time;
+
+    printf("Event counts:\n");
+    while (smt->text != NULL) {
+        printf("%08d\t%s\n", smt->event_count, smt->text);
+        smt++;
+    }
+
+    printf("processed %d total records in %d seconds (%ld per second)\n",
+            rec_count, (int)run_time, rec_count/run_time);
+
+    check_gotten_sum();
+}
+
+void log_event(int event_id) 
+{
+    stat_map_t *smt = stat_map;
+
+    //  printf("event_id = 0x%x\n", event_id);
+
+    while (smt->text != NULL) {
+        if (smt->event_id == event_id) {
+            smt->event_count++;
+            return;
+        }
+        smt++;
+    }
+    if (smt->text == NULL)
+        stat_map[0].event_count++;     // other
+}
+
+
+
+/**
+ * get_tbufs - get pointer to and size of the trace buffers
+ * @mfn:  location to store mfn of the trace buffers to
+ * @size: location to store the size of a trace buffer to
+ *
+ * Gets the machine address of the trace pointer area and the size of the
+ * per CPU buffers.
+ */
+void get_tbufs(unsigned long *mfn, unsigned long *size)
+{
+    int ret;
+    dom0_op_t op;                        /* dom0 op we'll build             */
+    int xc_handle = xc_interface_open(); /* for accessing control interface */
+
+    op.cmd = DOM0_TBUFCONTROL;
+    op.interface_version = DOM0_INTERFACE_VERSION;
+    op.u.tbufcontrol.op  = DOM0_TBUF_GET_INFO;
+
+    ret = do_dom0_op(xc_handle, &op);
+
+    xc_interface_close(xc_handle);
+
+    if ( ret != 0 )
+    {
+        PERROR("Failure to get trace buffer pointer from Xen");
+        exit(EXIT_FAILURE);
+    }
+
+    *mfn  = op.u.tbufcontrol.buffer_mfn;
+    *size = op.u.tbufcontrol.size;
+}
+
+/**
+ * map_tbufs - memory map Xen trace buffers into user space
+ * @tbufs_mfn: mfn of the trace buffers
+ * @num:       number of trace buffers to map
+ * @size:      size of each trace buffer
+ *
+ * Maps the Xen trace buffers them into process address space.
+ */
+struct t_buf *map_tbufs(unsigned long tbufs_mfn, unsigned int num,
+                        unsigned long size)
+{
+    int xc_handle;                  /* file descriptor for /proc/xen/privcmd */
+    struct t_buf *tbufs_mapped;
+
+    xc_handle = xc_interface_open();
+
+    if ( xc_handle < 0 ) 
+    {
+        PERROR("Open /proc/xen/privcmd when mapping trace buffers\n");
+        exit(EXIT_FAILURE);
+    }
+
+    tbufs_mapped = xc_map_foreign_range(xc_handle, 0 /* Dom 0 ID */,
+                                        size * num, PROT_READ | PROT_WRITE,
+                                        tbufs_mfn);
+
+    xc_interface_close(xc_handle);
+
+    if ( tbufs_mapped == 0 ) 
+    {
+        PERROR("Failed to mmap trace buffers");
+        exit(EXIT_FAILURE);
+    }
+
+    return tbufs_mapped;
+}
+
+/**
+ * init_bufs_ptrs - initialises an array of pointers to the trace buffers
+ * @bufs_mapped:    the userspace address where the trace buffers are mapped
+ * @num:            number of trace buffers
+ * @size:           trace buffer size
+ *
+ * Initialises an array of pointers to individual trace buffers within the
+ * mapped region containing all trace buffers.
+ */
+struct t_buf **init_bufs_ptrs(void *bufs_mapped, unsigned int num,
+        unsigned long size)
+{
+    int i;
+    struct t_buf **user_ptrs;
+
+    user_ptrs = (struct t_buf **)calloc(num, sizeof(struct t_buf *));
+    if ( user_ptrs == NULL )
+    {
+        PERROR( "Failed to allocate memory for buffer pointers\n");
+        exit(EXIT_FAILURE);
+    }
+
+    /* initialise pointers to the trace buffers - given the size of a trace
+     * buffer and the value of bufs_maped, we can easily calculate these */
+    for ( i = 0; i<num; i++ )
+        user_ptrs[i] = (struct t_buf *)((unsigned long)bufs_mapped + size * i);
+
+    return user_ptrs;
+}
+
+
+/**
+ * init_rec_ptrs - initialises data area pointers to locations in user space
+ * @tbufs_mfn:     base mfn of the trace buffer area
+ * @tbufs_mapped:  user virtual address of base of trace buffer area
+ * @meta:          array of user-space pointers to struct t_buf's of metadata
+ * @num:           number of trace buffers
+ *
+ * Initialises data area pointers to the locations that data areas have been
+ * mapped in user space.  Note that the trace buffer metadata contains machine
+ * pointers - the array returned allows more convenient access to them.
+ */
+struct t_rec **init_rec_ptrs(struct t_buf **meta, unsigned int num)
+{
+    int i;
+    struct t_rec **data;
+    
+    data = calloc(num, sizeof(struct t_rec *));
+    if ( data == NULL )
+    {
+        PERROR("Failed to allocate memory for data pointers\n");
+        exit(EXIT_FAILURE);
+    }
+
+    for ( i = 0; i < num; i++ )
+        data[i] = (struct t_rec *)(meta[i] + 1);
+
+    return data;
+}
+
+
+
+/**
+ * get_num_cpus - get the number of logical CPUs
+ */
+unsigned int get_num_cpus()
+{
+    dom0_op_t op;
+    int xc_handle = xc_interface_open();
+    int ret;
+
+    op.cmd = DOM0_PHYSINFO;
+    op.interface_version = DOM0_INTERFACE_VERSION;
+
+    ret = xc_dom0_op(xc_handle, &op);
+
+    if ( ret != 0 )
+    {
+        PERROR("Failure to get logical CPU count from Xen");
+        exit(EXIT_FAILURE);
+    }
+
+    xc_interface_close(xc_handle);
+    opts.cpu_freq = (double)op.u.physinfo.cpu_khz/1000.0;
+
+    return (op.u.physinfo.threads_per_core *
+            op.u.physinfo.cores_per_socket *
+            op.u.physinfo.sockets_per_node *
+            op.u.physinfo.nr_nodes);
+}
+
+
+/**
+ * monitor_tbufs - monitor the contents of tbufs
+ */
+int monitor_tbufs()
+{
+    int i;
+    extern void process_record(int, struct t_rec *);
+    extern void alloc_qos_data(int ncpu);
+
+    void *tbufs_mapped;          /* pointer to where the tbufs are mapped    */
+    struct t_buf **meta;         /* pointers to the trace buffer metadata    */
+    struct t_rec **data;         /* pointers to the trace buffer data areas
+                                  * where they are mapped into user space.   */
+    unsigned long tbufs_mfn;     /* mfn of the tbufs                         */
+    unsigned int  num;           /* number of trace buffers / logical CPUS   */
+    unsigned long size;          /* size of a single trace buffer            */
+
+    int size_in_recs;
+
+    /* get number of logical CPUs (and therefore number of trace buffers) */
+    num = get_num_cpus();
+
+    init_current(num);
+    alloc_qos_data(num);
+
+    printf("CPU Frequency = %7.2f\n", opts.cpu_freq);
+    
+    /* setup access to trace buffers */
+    get_tbufs(&tbufs_mfn, &size);
+
+    //    printf("from dom0op: %ld, t_buf: %d, t_rec: %d\n",
+    //            size, sizeof(struct t_buf), sizeof(struct t_rec));
+
+    tbufs_mapped = map_tbufs(tbufs_mfn, num, size);
+
+    size_in_recs = (size - sizeof(struct t_buf)) / sizeof(struct t_rec);
+    //    fprintf(stderr, "size_in_recs = %d\n", size_in_recs);
+
+    /* build arrays of convenience ptrs */
+    meta  = init_bufs_ptrs (tbufs_mapped, num, size);
+    data  = init_rec_ptrs(meta, num);
+
+    /* now, scan buffers for events */
+    while ( !interrupted )
+    {
+        for ( i = 0; ( i < num ) && !interrupted; i++ )
+            while ( meta[i]->cons != meta[i]->prod )
+            {
+                rmb(); /* read prod, then read item. */
+                process_record(i, data[i] + meta[i]->cons % size_in_recs);
+                mb(); /* read item, then update cons. */
+                meta[i]->cons++;
+            }
+
+        nanosleep(&opts.poll_sleep, NULL);
+    }
+
+    /* cleanup */
+    free(meta);
+    free(data);
+    /* don't need to munmap - cleanup is automatic */
+
+    return 0;
+}
+
+
+/******************************************************************************
+ * Various declarations / definitions GNU argp needs to do its work
+ *****************************************************************************/
+
+
+/* command parser for GNU argp - see GNU docs for more info */
+error_t cmd_parser(int key, char *arg, struct argp_state *state)
+{
+    settings_t *setup = (settings_t *)state->input;
+
+    switch ( key )
+    {
+        case 't': /* set new records threshold for logging */
+            {
+                char *inval;
+                setup->new_data_thresh = strtol(arg, &inval, 0);
+                if ( inval == arg )
+                    argp_usage(state);
+            }
+            break;
+
+        case 's': /* set sleep time (given in milliseconds) */
+            {
+                char *inval;
+                setup->poll_sleep = millis_to_timespec(strtol(arg, &inval, 0));
+                if ( inval == arg )
+                    argp_usage(state);
+            }
+            break;
+
+        case 'm': /* set ms_per_sample */
+            {
+                char *inval;
+                setup->ms_per_sample = strtol(arg, &inval, 0);
+                if ( inval == arg )
+                    argp_usage(state);
+            }
+            break;
+
+        case ARGP_KEY_ARG:
+            {
+                if ( state->arg_num == 0 )
+                    setup->outfile = arg;
+                else
+                    argp_usage(state);
+            }
+            break;
+
+        default:
+            return ARGP_ERR_UNKNOWN;
+    }
+
+    return 0;
+}
+
+#define SHARED_MEM_FILE "/tmp/xenq-shm"
+void alloc_qos_data(int ncpu)
+{
+    int i, n, pgsize, off=0;
+    char *dummy;
+    int qos_fd;
+    void advance_next_datapoint(uint64_t);
+
+    cpu_qos_data = (_new_qos_data **) calloc(ncpu, sizeof(_new_qos_data *));
+
+
+    qos_fd = open(SHARED_MEM_FILE, O_RDWR|O_CREAT|O_TRUNC, 0777);
+    if (qos_fd < 0) {
+        PERROR(SHARED_MEM_FILE);
+        exit(2);
+    }
+    pgsize = getpagesize();
+    dummy = malloc(pgsize);
+
+    for (n=0; n<ncpu; n++) {
+
+      for (i=0; i<sizeof(_new_qos_data); i=i+pgsize)
+        write(qos_fd, dummy, pgsize);
+
+      new_qos = (_new_qos_data *) mmap(0, sizeof(_new_qos_data), 
PROT_READ|PROT_WRITE, 
+                                      MAP_SHARED, qos_fd, off);
+      off += i;
+      if (new_qos == NULL) {
+        PERROR("mmap");
+        exit(3);
+      }
+      //  printf("new_qos = %p\n", new_qos);
+      memset(new_qos, 0, sizeof(_new_qos_data));
+      new_qos->next_datapoint = 0;
+      advance_next_datapoint(0);
+      new_qos->structlen = i;
+      new_qos->ncpu = ncpu;
+      //      printf("structlen = 0x%x\n", i);
+      cpu_qos_data[n] = new_qos;
+    }
+    free(dummy);
+    new_qos = NULL;
+}
+
+
+#define xstr(x) str(x)
+#define str(x) #x
+
+const struct argp_option cmd_opts[] =
+{
+    { .name = "log-thresh", .key='t', .arg="l",
+        .doc =
+            "Set number, l, of new records required to trigger a write to 
output "
+            "(default " xstr(NEW_DATA_THRESH) ")." },
+
+    { .name = "poll-sleep", .key='s', .arg="p",
+        .doc = 
+            "Set sleep time, p, in milliseconds between polling the trace 
buffer "
+            "for new data (default " xstr(POLL_SLEEP_MILLIS) ")." },
+
+    { .name = "ms_per_sample", .key='m', .arg="MS",
+        .doc = 
+            "Specify the number of milliseconds per sample "
+            " (default " xstr(MS_PER_SAMPLE) ")." },
+
+    {0}
+};
+
+const struct argp parser_def =
+{
+    .options = cmd_opts,
+    .parser = cmd_parser,
+    //    .args_doc = "[output file]",
+    .doc =
+        "Tool to capture and partially process Xen trace buffer data"
+        "\v"
+        "This tool is used to capture trace buffer data from Xen.  The data is 
"
+        "saved in a shared memory structure to be further processed by xenmon."
+};
+
+
+const char *argp_program_version     = "xenbaked v1.3";
+const char *argp_program_bug_address = "<rob.gardner@xxxxxx>";
+
+
+int main(int argc, char **argv)
+{
+    int ret;
+    struct sigaction act;
+
+    time(&start_time);
+    opts.outfile = 0;
+    opts.poll_sleep = millis_to_timespec(POLL_SLEEP_MILLIS);
+    opts.new_data_thresh = NEW_DATA_THRESH;
+    opts.ms_per_sample = MS_PER_SAMPLE;
+    opts.cpu_freq = CPU_FREQ;
+
+    argp_parse(&parser_def, argc, argv, 0, 0, &opts);
+    fprintf(stderr, "ms_per_sample = %ld\n", opts.ms_per_sample);
+
+
+    /* ensure that if we get a signal, we'll do cleanup, then exit */
+    act.sa_handler = close_handler;
+    act.sa_flags = 0;
+    sigemptyset(&act.sa_mask);
+    sigaction(SIGHUP,  &act, NULL);
+    sigaction(SIGTERM, &act, NULL);
+    sigaction(SIGINT,  &act, NULL);
+
+    ret = monitor_tbufs();
+
+    dump_stats();
+    msync(new_qos, sizeof(_new_qos_data), MS_SYNC);
+
+    return ret;
+}
+
+int domain_runnable(int domid)
+{
+    return new_qos->domain_info[ID(domid)].runnable;
+}
+
+
+void update_blocked_time(int domid, uint64_t now)
+{
+    uint64_t t_blocked;
+    int id = ID(domid);
+
+    if (new_qos->domain_info[id].blocked_start_time != 0) {
+        if (now >= new_qos->domain_info[id].blocked_start_time)
+            t_blocked = now - new_qos->domain_info[id].blocked_start_time;
+        else
+            t_blocked = now + (~0ULL - 
new_qos->domain_info[id].blocked_start_time);
+        new_qos->qdata[new_qos->next_datapoint].ns_blocked[id] += t_blocked;
+    }
+
+    if (domain_runnable(id))
+        new_qos->domain_info[id].blocked_start_time = 0;
+    else
+        new_qos->domain_info[id].blocked_start_time = now;
+}
+
+
+// advance to next datapoint for all domains
+void advance_next_datapoint(uint64_t now)
+{
+    int new, old, didx;
+
+    old = new_qos->next_datapoint;
+    new = QOS_INCR(old);
+    new_qos->next_datapoint = new;
+    // memset(&new_qos->qdata[new], 0, sizeof(uint64_t)*(2+5*NDOMAINS));
+    for (didx = 0; didx < NDOMAINS; didx++) {
+        new_qos->qdata[new].ns_gotten[didx] = 0;
+        new_qos->qdata[new].ns_allocated[didx] = 0;
+        new_qos->qdata[new].ns_waiting[didx] = 0;
+        new_qos->qdata[new].ns_blocked[didx] = 0;
+        new_qos->qdata[new].switchin_count[didx] = 0;
+        new_qos->qdata[new].io_count[didx] = 0;
+    }
+    new_qos->qdata[new].ns_passed = 0;
+    new_qos->qdata[new].lost_records = 0;
+    new_qos->qdata[new].flip_free_periods = 0;
+
+    new_qos->qdata[new].timestamp = now;
+}
+
+
+
+void qos_update_thread(int cpu, int domid, uint64_t now)
+{
+    int n, id;
+    uint64_t last_update_time, start;
+    int64_t time_since_update, run_time = 0;
+
+    id = ID(domid);
+
+    n = new_qos->next_datapoint;
+    last_update_time = new_qos->domain_info[id].last_update_time;
+
+    time_since_update = now - last_update_time;
+
+    if (time_since_update < 0) {
+      // what happened here? either a timestamp wraparound, or more likely,
+      // a slight inconsistency among timestamps from various cpu's
+      if (-time_since_update < billion) {
+       // fairly small difference, let's just adjust 'now' to be a little
+       // beyond last_update_time
+       time_since_update = -time_since_update;
+      }
+      else if ( ((~0ULL - last_update_time) < billion) && (now < billion) ) {
+       // difference is huge, must be a wraparound
+       // last_update time should be "near" ~0ULL,
+       // and now should be "near" 0
+       time_since_update = now + (~0ULL - last_update_time);
+       printf("time wraparound\n");
+      }
+      else {
+       // none of the above, may be an out of order record
+       // no good solution, just ignore and update again later
+       return;
+      }
+    }
+       
+    new_qos->domain_info[id].last_update_time = now;
+
+    if (new_qos->domain_info[id].runnable_at_last_update && is_current(domid, 
cpu)) {
+        start = new_qos->domain_info[id].start_time;
+        if (start > now) {             // wrapped around
+            run_time = now + (~0ULL - start);
+           printf("warning: start > now\n");
+        }
+        else
+            run_time = now - start;
+       //      if (run_time < 0)       // should not happen
+       //        printf("warning: run_time < 0; start = %lld now= %lld\n", 
start, now);
+        new_qos->domain_info[id].ns_oncpu_since_boot += run_time;
+        new_qos->domain_info[id].start_time = now;
+        new_qos->domain_info[id].ns_since_boot += time_since_update;
+#if 1
+       new_qos->qdata[n].ns_gotten[id] += run_time;
+       if (domid == 0 && cpu == 1)
+         printf("adding run time for dom0 on cpu1\r\n");
+#endif
+    }
+
+    new_qos->domain_info[id].runnable_at_last_update = domain_runnable(domid);
+
+    update_blocked_time(domid, now);
+
+    // how much time passed since this datapoint was updated?
+    if (now >= new_qos->qdata[n].timestamp) {
+        // all is right with the world, time is increasing
+        new_qos->qdata[n].ns_passed += (now - new_qos->qdata[n].timestamp);
+    }
+    else {
+        // time wrapped around
+        //new_qos->qdata[n].ns_passed += (now + (~0LL - 
new_qos->qdata[n].timestamp));
+        //    printf("why timewrap?\r\n");
+    }
+    new_qos->qdata[n].timestamp = now;
+}
+
+
+// called by dump routines to update all structures
+void qos_update_all(uint64_t now, int cpu)
+{
+    int i;
+
+    for (i=0; i<NDOMAINS; i++)
+        if (new_qos->domain_info[i].in_use)
+            qos_update_thread(cpu, i, now);
+}
+
+
+void qos_update_thread_stats(int cpu, int domid, uint64_t now)
+{
+    if (new_qos->qdata[new_qos->next_datapoint].ns_passed > 
(million*opts.ms_per_sample)) {
+        qos_update_all(now, cpu);
+        advance_next_datapoint(now);
+        return;
+    }
+    qos_update_thread(cpu, domid, now);
+}
+
+
+void qos_init_domain(int cpu, int domid, uint64_t now)
+{
+    int i, id;
+
+    id = ID(domid);
+
+    if (new_qos->domain_info[id].in_use)
+        return;
+
+
+    memset(&new_qos->domain_info[id], 0, sizeof(_domain_info));
+    new_qos->domain_info[id].last_update_time = now;
+    //  runnable_start_time[id] = 0;
+    new_qos->domain_info[id].runnable_start_time = 0; // invalidate
+    new_qos->domain_info[id].in_use = 1;
+    new_qos->domain_info[id].blocked_start_time = 0;
+    new_qos->domain_info[id].id = id;
+    if (domid == IDLE_DOMAIN_ID)
+        sprintf(new_qos->domain_info[id].name, "Idle Task%d", cpu);
+    else
+        sprintf(new_qos->domain_info[id].name, "Domain#%d", domid);
+
+    for (i=0; i<NSAMPLES; i++) {
+        new_qos->qdata[i].ns_gotten[id] = 0;
+        new_qos->qdata[i].ns_allocated[id] = 0;
+        new_qos->qdata[i].ns_waiting[id] = 0;
+        new_qos->qdata[i].ns_blocked[id] = 0;
+        new_qos->qdata[i].switchin_count[id] = 0;
+        new_qos->qdata[i].io_count[id] = 0;
+    }
+}
+
+
+// called when a new thread gets the cpu
+void qos_switch_in(int cpu, int domid, uint64_t now, unsigned long ns_alloc, 
unsigned long ns_waited)
+{
+    int id = ID(domid);
+
+    new_qos->domain_info[id].runnable = 1;
+    update_blocked_time(domid, now);
+    new_qos->domain_info[id].blocked_start_time = 0; // invalidate
+    new_qos->domain_info[id].runnable_start_time = 0; // invalidate
+    //runnable_start_time[id] = 0;
+
+    new_qos->domain_info[id].start_time = now;
+    new_qos->qdata[new_qos->next_datapoint].switchin_count[id]++;
+    new_qos->qdata[new_qos->next_datapoint].ns_allocated[id] += ns_alloc;
+    new_qos->qdata[new_qos->next_datapoint].ns_waiting[id] += ns_waited;
+    qos_update_thread_stats(cpu, domid, now);
+    set_current(cpu, id);
+
+    // count up page flips for dom0 execution
+    if (id == 0)
+      dom0_flips = 0;
+}
+
+// called when the current thread is taken off the cpu
+void qos_switch_out(int cpu, int domid, uint64_t now, unsigned long gotten)
+{
+    int id = ID(domid);
+    int n;
+
+    if (!is_current(id, cpu)) {
+        //    printf("switching out domain %d but it is not current. 
gotten=%ld\r\n", id, gotten);
+    }
+
+    if (gotten == 0) {
+        printf("gotten==0 in qos_switchout(domid=%d)\n", domid);
+    }
+
+    if (gotten < 100) {
+        printf("gotten<100ns in qos_switchout(domid=%d)\n", domid);
+    }
+
+
+    n = new_qos->next_datapoint;
+#if 0
+    new_qos->qdata[n].ns_gotten[id] += gotten;
+    if (gotten > new_qos->qdata[n].ns_passed)
+      printf("inconsistency #257, diff = %lld\n",
+           gotten - new_qos->qdata[n].ns_passed );
+#endif
+    new_qos->domain_info[id].ns_oncpu_since_boot += gotten;
+    new_qos->domain_info[id].runnable_start_time = now;
+    //  runnable_start_time[id] = now;
+    qos_update_thread_stats(cpu, id, now);
+
+    // process dom0 page flips
+    if (id == 0)
+      if (dom0_flips == 0)
+       new_qos->qdata[n].flip_free_periods++;
+}
+
+// called when domain is put to sleep, may also be called
+// when thread is already asleep
+void qos_state_sleeping(int cpu, int domid, uint64_t now) 
+{
+    int id = ID(domid);
+
+    if (!domain_runnable(id))  // double call?
+        return;
+
+    new_qos->domain_info[id].runnable = 0;
+    new_qos->domain_info[id].blocked_start_time = now;
+    new_qos->domain_info[id].runnable_start_time = 0; // invalidate
+    //  runnable_start_time[id] = 0; // invalidate
+    qos_update_thread_stats(cpu, domid, now);
+}
+
+
+
+void qos_kill_thread(int domid)
+{
+    new_qos->domain_info[ID(domid)].in_use = 0;
+}
+
+
+// called when thread becomes runnable, may also be called
+// when thread is already runnable
+void qos_state_runnable(int cpu, int domid, uint64_t now)
+{
+    int id = ID(domid);
+
+    if (domain_runnable(id))   // double call?
+        return;
+    new_qos->domain_info[id].runnable = 1;
+    update_blocked_time(domid, now);
+
+    qos_update_thread_stats(cpu, domid, now);
+
+    new_qos->domain_info[id].blocked_start_time = 0; /* invalidate */
+    new_qos->domain_info[id].runnable_start_time = now;
+    //  runnable_start_time[id] = now;
+}
+
+
+void qos_count_packets(domid_t domid, uint64_t now)
+{
+  int i, id = ID(domid);
+  _new_qos_data *cpu_data;
+
+  for (i=0; i<NCPU; i++) {
+    cpu_data = cpu_qos_data[i];
+    if (cpu_data->domain_info[id].in_use) {
+      cpu_data->qdata[cpu_data->next_datapoint].io_count[id]++;
+    }
+  }
+
+  new_qos->qdata[new_qos->next_datapoint].io_count[0]++;
+  dom0_flips++;
+}
+
+
+int domain_ok(int cpu, int domid, uint64_t now)
+{
+    if (domid == IDLE_DOMAIN_ID)
+        domid = NDOMAINS-1;
+    if (domid < 0 || domid >= NDOMAINS) {
+        printf("bad domain id: %d\n", domid);
+        return 0;
+    }
+    if (new_qos->domain_info[domid].in_use == 0)
+        qos_init_domain(cpu, domid, now);
+    return 1;
+}
+
+
+void process_record(int cpu, struct t_rec *r)
+{
+  uint64_t now;
+
+
+  new_qos = cpu_qos_data[cpu];
+
+  rec_count++;
+
+  now = ((double)r->cycles) / (opts.cpu_freq / 1000.0);
+
+  log_event(r->event);
+
+  switch (r->event) {
+
+  case TRC_SCHED_SWITCH_INFPREV:
+    // domain data[0] just switched out and received data[1] ns of cpu time
+    if (domain_ok(cpu, r->data[0], now))
+      qos_switch_out(cpu, r->data[0], now, r->data[1]);
+    //    printf("ns_gotten %ld\n", r->data[1]);
+    break;
+    
+  case TRC_SCHED_SWITCH_INFNEXT:
+    // domain data[0] just switched in and
+    // waited data[1] ns, and was allocated data[2] ns of cpu time
+    if (domain_ok(cpu, r->data[0], now))
+      qos_switch_in(cpu, r->data[0], now, r->data[2], r->data[1]);
+    break;
+    
+  case TRC_SCHED_DOM_ADD:
+    if (domain_ok(cpu, r->data[0], now))
+      qos_init_domain(cpu, r->data[0],  now);
+    break;
+    
+  case TRC_SCHED_DOM_REM:
+    if (domain_ok(cpu, r->data[0], now))
+      qos_kill_thread(r->data[0]);
+    break;
+    
+  case TRC_SCHED_SLEEP:
+    if (domain_ok(cpu, r->data[0], now))
+      qos_state_sleeping(cpu, r->data[0], now);
+    break;
+    
+  case TRC_SCHED_WAKE:
+    if (domain_ok(cpu, r->data[0], now))
+      qos_state_runnable(cpu, r->data[0], now);
+    break;
+    
+  case TRC_SCHED_BLOCK:
+    if (domain_ok(cpu, r->data[0], now))
+      qos_state_sleeping(cpu, r->data[0], now);
+    break;
+    
+  case TRC_MEM_PAGE_GRANT_TRANSFER:
+    if (domain_ok(cpu, r->data[0], now))
+      qos_count_packets(r->data[0], now);
+    break;
+    
+  default:
+    break;
+  }
+  new_qos = NULL;
+}
+
+
+
diff -r e62c54ab862f -r 878a9891b056 tools/xenmon/xenbaked.h
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xenmon/xenbaked.h   Sat Nov 19 05:16:29 2005
@@ -0,0 +1,101 @@
+/******************************************************************************
+ * tools/xenbaked.h
+ *
+ * Header file for xenbaked
+ *
+ * Copyright (C) 2005 by Hewlett Packard, Palo Alto and Fort Collins
+ *
+ * Authors: Diwaker Gupta, diwaker.gupta@xxxxxx
+ *          Rob Gardner, rob.gardner@xxxxxx
+ *          Lucy Cherkasova, lucy.cherkasova.hp.com
+ * 
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; under version 2 of the License.
+ *
+ *  This program 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 General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#ifndef __QOS_H__
+#define __QOS_H__
+
+///// qos stuff
+#define million 1000000LL
+#define billion 1000000000LL
+
+#define QOS_ADD(N,A) ((N+A)<(NSAMPLES-1) ? (N+A) : A)
+#define QOS_INCR(N) ((N<(NSAMPLES-2)) ? (N+1) : 0)
+#define QOS_DECR(N) ((N==0) ? (NSAMPLES-1) : (N-1))
+
+#define MAX_NAME_SIZE 32
+#define IDLE_DOMAIN_ID 32767
+
+/* Number of domains we can keep track of in memory */
+#define NDOMAINS 32
+
+/* Number of data points to keep */
+#define NSAMPLES 100
+
+
+// per domain stuff
+typedef struct 
+{
+  uint64_t last_update_time;
+  uint64_t start_time;         // when the thread started running
+  uint64_t runnable_start_time;        // when the thread became runnable
+  uint64_t blocked_start_time; // when the thread became blocked
+  uint64_t ns_since_boot;              // time gone by since boot
+  uint64_t ns_oncpu_since_boot;        // total cpu time used by thread since 
boot
+  //  uint64_t ns_runnable_since_boot;
+  int runnable_at_last_update; // true if the thread was runnable last time we 
checked.
+  int runnable;                        // true if thread is runnable right now
+  // tells us something about what happened during the 
+  // sample period that we are analysing right now
+  int in_use;                  // 
+  domid_t  id;
+  char     name[MAX_NAME_SIZE];
+} _domain_info;
+
+
+
+typedef struct 
+{
+  struct 
+  {
+// data point:
+//   stuff that is recorded once for each measurement interval
+    uint64_t ns_gotten[NDOMAINS];              // ns used in the last sample 
period
+    uint64_t ns_allocated[NDOMAINS];           // ns allocated by scheduler
+    uint64_t ns_waiting[NDOMAINS];             // ns spent waiting to execute, 
ie, time from
+                                        // becoming runnable until actually 
running
+    uint64_t ns_blocked[NDOMAINS];             // ns spent blocked
+    uint64_t switchin_count[NDOMAINS]; // number of executions of the domain   
+    uint64_t io_count[NDOMAINS];
+    uint64_t ns_passed;              // ns gone by on the wall clock, ie, the 
sample period
+    uint64_t timestamp;
+    uint64_t lost_records;             // # of lost trace records this time 
period
+    uint64_t flip_free_periods;        // # of executions of dom0 in which no 
page flips happened
+  } qdata[NSAMPLES];
+  
+  _domain_info domain_info[NDOMAINS];
+  
+  // control information
+  int next_datapoint;
+  int ncpu;
+  int structlen;
+
+  // parameters
+  int measurement_frequency;   // for example
+  
+} _new_qos_data;
+
+
+
+#endif
diff -r e62c54ab862f -r 878a9891b056 tools/xenmon/xenmon.py
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xenmon/xenmon.py    Sat Nov 19 05:16:29 2005
@@ -0,0 +1,578 @@
+#!/usr/bin/env python
+
+#####################################################################
+# xenmon is a front-end for xenbaked.
+# There is a curses interface for live monitoring. XenMon also allows
+# logging to a file. For options, run python xenmon.py -h
+#
+# Copyright (C) 2005 by Hewlett Packard, Palo Alto and Fort Collins
+# Authors: Lucy Cherkasova, lucy.cherkasova@xxxxxx
+#          Rob Gardner, rob.gardner@xxxxxx
+#          Diwaker Gupta, diwaker.gupta@xxxxxx
+#####################################################################
+#   This program is free software; you can redistribute it and/or modify
+#   it under the terms of the GNU General Public License as published by
+#   the Free Software Foundation; under version 2 of the License.
+# 
+#   This program 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 General Public License for more details.
+# 
+#   You should have received a copy of the GNU General Public License
+#   along with this program; if not, write to the Free Software
+#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#####################################################################
+
+import mmap
+import struct
+import os
+import time
+import optparse as _o
+import curses as _c
+import math
+import sys
+
+# constants
+NSAMPLES = 100
+NDOMAINS = 32
+
+# the struct strings for qos_info
+ST_DOM_INFO = "6Q4i32s"
+ST_QDATA = "%dQ" % (6*NDOMAINS + 4)
+
+# size of mmaped file
+QOS_DATA_SIZE = struct.calcsize(ST_QDATA)*NSAMPLES + 
struct.calcsize(ST_DOM_INFO)*NDOMAINS + struct.calcsize("4i")
+
+# location of mmaped file, hard coded right now
+SHM_FILE = "/tmp/xenq-shm"
+
+# format strings
+TOTALS = 15*' ' + "%6.2f%%" + 35*' ' + "%6.2f%%"
+
+ALLOCATED = "Allocated"
+GOTTEN = "Gotten"
+BLOCKED = "Blocked"
+WAITED = "Waited"
+IOCOUNT = "I/O Count"
+EXCOUNT = "Exec Count"
+
+# globals
+# our curses screen
+stdscr = None
+
+# parsed options
+options, args = None, None
+
+# the optparse module is quite smart
+# to see help, just run xenmon -h
+def setup_cmdline_parser():
+    parser = _o.OptionParser()
+    parser.add_option("-l", "--live", dest="live", action="store_true",
+                      default=True, help = "show the ncurses live monitoring 
frontend (default)")
+    parser.add_option("-n", "--notlive", dest="live", action="store_false",
+                      default="True", help = "write to file instead of live 
monitoring")
+    parser.add_option("-p", "--prefix", dest="prefix",
+                      default = "log", help="prefix to use for output files")
+    parser.add_option("-t", "--time", dest="duration",
+            action="store", type="int", default=10, 
+            help="stop logging to file after this much time has elapsed (in 
seconds). set to 0 to keep logging indefinitely")
+    parser.add_option("-i", "--interval", dest="interval",
+            action="store", type="int", default=1000,
+            help="interval for logging (in ms)")
+    parser.add_option("--ms_per_sample", dest="mspersample",
+            action="store", type="int", default=100,
+            help = "determines how many ms worth of data goes in a sample")
+    return parser
+
+# encapsulate information about a domain
+class DomainInfo:
+    def __init__(self):
+        self.allocated_samples = []
+        self.gotten_samples = []
+        self.blocked_samples = []
+        self.waited_samples = []
+        self.execcount_samples = []
+        self.iocount_samples = []
+        self.ffp_samples = []
+
+    def gotten_stats(self, passed):
+        total = float(sum(self.gotten_samples))
+        per = 100*total/passed
+        exs = sum(self.execcount_samples)
+        if exs > 0:
+            avg = total/exs
+        else:
+            avg = 0
+        return [total/(float(passed)/10**9), per, avg]
+
+    def waited_stats(self, passed):
+        total = float(sum(self.waited_samples))
+        per = 100*total/passed
+        exs = sum(self.execcount_samples)
+        if exs > 0:
+            avg = total/exs
+        else:
+            avg = 0
+        return [total/(float(passed)/10**9), per, avg]
+
+    def blocked_stats(self, passed):
+        total = float(sum(self.blocked_samples))
+        per = 100*total/passed
+        ios = sum(self.iocount_samples)
+        if ios > 0:
+            avg = total/float(ios)
+        else:
+            avg = 0
+        return [total/(float(passed)/10**9), per, avg]
+
+    def allocated_stats(self, passed):
+        total = sum(self.allocated_samples)
+        exs = sum(self.execcount_samples)
+        if exs > 0:
+            return float(total)/exs
+        else:
+            return 0
+
+    def ec_stats(self, passed):
+        total = float(sum(self.execcount_samples))/(float(passed)/10**9)
+        return total
+
+    def io_stats(self, passed):
+        total = float(sum(self.iocount_samples))
+        exs = sum(self.execcount_samples)
+        if exs > 0:
+            avg = total/exs
+        else:
+            avg = 0
+        return [total/(float(passed)/10**9), avg]
+
+    def stats(self, passed):
+        return [self.gotten_stats(passed), self.allocated_stats(passed), 
self.blocked_stats(passed), 
+                self.waited_stats(passed), self.ec_stats(passed), 
self.io_stats(passed)]
+
+# report values over desired interval
+def summarize(startat, endat, duration, samples):
+    dominfos = {}
+    for i in range(0, NDOMAINS):
+        dominfos[i] = DomainInfo()
+        
+    passed = 1              # to prevent zero division
+    curid = startat
+    numbuckets = 0
+    lost_samples = []
+    ffp_samples = []
+    
+    while passed < duration:
+        for i in range(0, NDOMAINS):
+            dominfos[i].gotten_samples.append(samples[curid][0*NDOMAINS + i])
+            dominfos[i].allocated_samples.append(samples[curid][1*NDOMAINS + 
i])
+            dominfos[i].waited_samples.append(samples[curid][2*NDOMAINS + i])
+            dominfos[i].blocked_samples.append(samples[curid][3*NDOMAINS + i])
+            dominfos[i].execcount_samples.append(samples[curid][4*NDOMAINS + 
i])
+            dominfos[i].iocount_samples.append(samples[curid][5*NDOMAINS + i])
+    
+        passed += samples[curid][6*NDOMAINS]
+        lost_samples.append(samples[curid][6*NDOMAINS + 2])
+        ffp_samples.append(samples[curid][6*NDOMAINS + 3])
+
+        numbuckets += 1
+
+        if curid > 0:
+            curid -= 1
+        else:
+            curid = NSAMPLES - 1
+        if curid == endat:
+            break
+
+    lostinfo = [min(lost_samples), sum(lost_samples), max(lost_samples)]
+    ffpinfo = [min(ffp_samples), sum(ffp_samples), max(ffp_samples)]
+    ldoms = map(lambda x: dominfos[x].stats(passed), range(0, NDOMAINS))
+
+    return [ldoms, lostinfo, ffpinfo]
+
+# scale microseconds to milliseconds or seconds as necessary
+def time_scale(ns):
+    if ns < 1000:
+        return "%4.2f ns" % float(ns)
+    elif ns < 1000*1000:
+        return "%4.2f us" % (float(ns)/10**3)
+    elif ns < 10**9:
+           return "%4.2f ms" % (float(ns)/10**6)
+    else:
+        return "%4.2f s" % (float(ns)/10**9)
+
+# paint message on curses screen, but detect screen size errors
+def display(scr, row, col, str, attr=0):
+    try:
+        scr.addstr(row, col, str, attr)
+    except:
+        scr.erase()
+        _c.nocbreak()
+        scr.keypad(0)
+        _c.echo()
+        _c.endwin()
+        print "Your terminal screen is not big enough; Please resize it."
+        print "row=%d, col=%d, str='%s'" % (row, col, str)
+        sys.exit(1)
+
+
+# the live monitoring code
+def show_livestats():
+    cpu = 0          # cpu of interest to display data for
+    ncpu = 1         # number of cpu's on this platform
+    slen = 0         # size of shared data structure, incuding padding
+    
+    # mmap the (the first chunk of the) file
+    shmf = open(SHM_FILE, "r+")
+    shm = mmap.mmap(shmf.fileno(), QOS_DATA_SIZE)
+
+    samples = []
+    doms = []
+
+    # initialize curses
+    stdscr = _c.initscr()
+    _c.noecho()
+    _c.cbreak()
+
+    stdscr.keypad(1)
+    stdscr.timeout(1000)
+    [maxy, maxx] = stdscr.getmaxyx()
+
+    
+
+    # display in a loop
+    while True:
+
+        for cpuidx in range(0, ncpu):
+
+            # calculate offset in mmap file to start from
+            idx = cpuidx * slen
+
+
+            samples = []
+            doms = []
+
+            # read in data
+            for i in range(0, NSAMPLES):
+                len = struct.calcsize(ST_QDATA)
+                sample = struct.unpack(ST_QDATA, shm[idx:idx+len])
+                samples.append(sample)
+                idx += len
+
+            for i in range(0, NDOMAINS):
+                len = struct.calcsize(ST_DOM_INFO)
+                dom = struct.unpack(ST_DOM_INFO, shm[idx:idx+len])
+                doms.append(dom)
+                idx += len
+
+            len = struct.calcsize("4i")
+            oldncpu = ncpu
+            (next, ncpu, slen, freq) = struct.unpack("4i", shm[idx:idx+len])
+            idx += len
+
+            # xenbaked tells us how many cpu's it's got, so re-do
+            # the mmap if necessary to get multiple cpu data
+            if oldncpu != ncpu:
+                shm = mmap.mmap(shmf.fileno(), ncpu*slen)
+
+            # if we've just calculated data for the cpu of interest, then
+            # stop examining mmap data and start displaying stuff
+            if cpuidx == cpu:
+                break
+
+        # calculate starting and ending datapoints; never look at "next" since
+        # it represents live data that may be in transition. 
+        startat = next - 1
+        if next + 10 < NSAMPLES:
+            endat = next + 10
+        else:
+            endat = 10
+
+        # get summary over desired interval
+        [h1, l1, f1] = summarize(startat, endat, 10**9, samples)
+        [h2, l2, f2] = summarize(startat, endat, 10 * 10**9, samples)
+
+        # the actual display code
+        row = 0
+        display(stdscr, row, 1, "CPU = %d" % cpu, _c.A_STANDOUT)
+
+        display(stdscr, row, 10, "%sLast 10 seconds%sLast 1 second" % (6*' ', 
30*' '), _c.A_BOLD)
+        row +=1
+        display(stdscr, row, 1, "%s" % ((maxx-2)*'='))
+
+        total_h1_cpu = 0
+        total_h2_cpu = 0
+
+        for dom in range(0, NDOMAINS):
+            if h1[dom][0][1] > 0 or dom == NDOMAINS - 1:
+                # display gotten
+                row += 1 
+                col = 2
+                display(stdscr, row, col, "%d" % dom)
+                col += 4
+                display(stdscr, row, col, "%s" % time_scale(h2[dom][0][0]))
+                col += 12
+                display(stdscr, row, col, "%3.2f%%" % h2[dom][0][1])
+                col += 12
+                display(stdscr, row, col, "%s/ex" % time_scale(h2[dom][0][2]))
+                col += 18
+                display(stdscr, row, col, "%s" % time_scale(h1[dom][0][0]))
+                col += 12
+                display(stdscr, row, col, "%3.2f%%" % h1[dom][0][1])
+                col += 12
+                display(stdscr, row, col, "%s/ex" % time_scale(h1[dom][0][2]))
+                col += 18
+                display(stdscr, row, col, "Gotten")
+    
+                # display allocated
+                row += 1
+                col = 2
+                display(stdscr, row, col, "%d" % dom)
+                col += 28
+                display(stdscr, row, col, "%s/ex" % time_scale(h2[dom][1]))
+                col += 42
+                display(stdscr, row, col, "%s/ex" % time_scale(h1[dom][1]))
+                col += 18
+                display(stdscr, row, col, "Allocated")
+
+                # display blocked
+                row += 1
+                col = 2
+                display(stdscr, row, col, "%d" % dom)
+                col += 4
+                display(stdscr, row, col, "%s" % time_scale(h2[dom][2][0]))
+                col += 12
+                display(stdscr, row, col, "%3.2f%%" % h2[dom][2][1])
+                col += 12
+                display(stdscr, row, col, "%s/io" % time_scale(h2[dom][2][2]))
+                col += 18
+                display(stdscr, row, col, "%s" % time_scale(h1[dom][2][0]))
+                col += 12
+                display(stdscr, row, col, "%3.2f%%" % h1[dom][2][1])
+                col += 12
+                display(stdscr, row, col, "%s/io" % time_scale(h1[dom][2][2]))
+                col += 18
+                display(stdscr, row, col, "Blocked")
+
+                # display waited
+                row += 1
+                col = 2
+                display(stdscr, row, col, "%d" % dom)
+                col += 4
+                display(stdscr, row, col, "%s" % time_scale(h2[dom][3][0]))
+                col += 12
+                display(stdscr, row, col, "%3.2f%%" % h2[dom][3][1])
+                col += 12
+                display(stdscr, row, col, "%s/ex" % time_scale(h2[dom][3][2]))
+                col += 18
+                display(stdscr, row, col, "%s" % time_scale(h1[dom][3][0]))
+                col += 12
+                display(stdscr, row, col, "%3.2f%%" % h1[dom][3][1])
+                col += 12
+                display(stdscr, row, col, "%s/ex" % time_scale(h1[dom][3][2]))
+                col += 18
+                display(stdscr, row, col, "Waited")
+
+                # display ex count
+                row += 1
+                col = 2
+                display(stdscr, row, col, "%d" % dom)
+
+                col += 28
+                display(stdscr, row, col, "%d/s" % h2[dom][4])
+                col += 42
+                display(stdscr, row, col, "%d" % h1[dom][4])
+                col += 18
+                display(stdscr, row, col, "Execution count")
+
+                # display io count
+                row += 1
+                col = 2
+                display(stdscr, row, col, "%d" % dom)
+                col += 4
+                display(stdscr, row, col, "%d/s" % h2[dom][5][0])
+                col += 24
+                display(stdscr, row, col, "%d/ex" % h2[dom][5][1])
+                col += 18
+                display(stdscr, row, col, "%d" % h1[dom][5][0])
+                col += 24
+                display(stdscr, row, col, "%3.2f/ex" % h1[dom][5][1])
+                col += 18
+                display(stdscr, row, col, "I/O Count")
+
+            #row += 1
+            #stdscr.hline(row, 1, '-', maxx - 2)
+            total_h1_cpu += h1[dom][0][1]
+            total_h2_cpu += h2[dom][0][1]
+
+
+        row += 1
+        display(stdscr, row, 2, TOTALS % (total_h2_cpu, total_h1_cpu))
+        row += 1
+#        display(stdscr, row, 2, 
+#                "\tFFP: %d (Min: %d, Max: %d)\t\t\tFFP: %d (Min: %d, Max %d)" 
% 
+#                (math.ceil(f2[1]), f2[0], f2[2], math.ceil(f1[1]), f1[0], 
f1[2]), _c.A_BOLD)
+
+        if l1[1] > 1 :
+            row += 1
+            display(stdscr, row, 2, 
+                    "\tRecords lost: %d (Min: %d, Max: %d)\t\t\tRecords lost: 
%d (Min: %d, Max %d)" % 
+                    (math.ceil(l2[1]), l2[0], l2[2], math.ceil(l1[1]), l1[0], 
l1[2]), _c.A_BOLD)
+
+        # grab a char from tty input; exit if interrupt hit
+        try:
+            c = stdscr.getch()
+        except:
+            break
+        
+        # q = quit
+        if c == ord('q'):
+            break
+    
+        # c = cycle to a new cpu of interest
+        if c == ord('c'):
+            cpu = (cpu + 1) % ncpu
+
+        stdscr.erase()
+
+    _c.nocbreak()
+    stdscr.keypad(0)
+    _c.echo()
+    _c.endwin()
+    shm.close()
+    shmf.close()
+
+
+# simple functions to allow initialization of log files without actually
+# physically creating files that are never used; only on the first real
+# write does the file get created
+class Delayed(file):
+    def __init__(self, filename, mode):
+       self.filename = filename
+       self.saved_mode = mode
+       self.delay_data = ""
+       self.opened = 0
+
+    def delayed_write(self, str):
+       self.delay_data = str
+
+    def write(self, str):
+       if not self.opened:
+           self.file = open(self.filename, self.saved_mode)
+           self.opened = 1
+            self.file.write(self.delay_data)
+       self.file.write(str)
+
+    def flush(self):
+        if  self.opened:
+            self.file.flush()
+
+    def close(self):
+        if  self.opened:
+            self.file.close()
+            
+
+def writelog():
+    global options
+
+    ncpu = 1        # number of cpu's
+    slen = 0        # size of shared structure inc. padding
+
+    shmf = open(SHM_FILE, "r+")
+    shm = mmap.mmap(shmf.fileno(), QOS_DATA_SIZE)
+
+    interval = 0
+    outfiles = {}
+    for dom in range(0, NDOMAINS):
+        outfiles[dom] = Delayed("%s-dom%d.log" % (options.prefix, dom), 'w')
+        outfiles[dom].delayed_write("# passed cpu dom cpu(tot) cpu(%) cpu/ex 
allocated/ex blocked(tot) blocked(%) blocked/io waited(tot) waited(%) waited/ex 
ex/s io(tot) io/ex\n")
+
+    while options.duration == 0 or interval < (options.duration * 1000):
+        for cpuidx in range(0, ncpu):
+            idx = cpuidx * slen      # offset needed in mmap file
+
+
+            samples = []
+            doms = []
+
+            for i in range(0, NSAMPLES):
+                len = struct.calcsize(ST_QDATA)
+                sample = struct.unpack(ST_QDATA, shm[idx:idx+len])
+                samples.append(sample)
+                idx += len
+
+            for i in range(0, NDOMAINS):
+                len = struct.calcsize(ST_DOM_INFO)
+                dom = struct.unpack(ST_DOM_INFO, shm[idx:idx+len])
+                doms.append(dom)
+                idx += len
+
+            len = struct.calcsize("4i")
+            oldncpu = ncpu
+            (next, ncpu, slen, freq) = struct.unpack("4i", shm[idx:idx+len])
+            idx += len
+
+            if oldncpu != ncpu:
+                shm = mmap.mmap(shmf.fileno(), ncpu*slen)
+
+            startat = next - 1
+            if next + 10 < NSAMPLES:
+                endat = next + 10
+            else:
+                endat = 10
+
+            [h1,l1, f1] = summarize(startat, endat, options.interval * 10**6, 
samples)
+            for dom in range(0, NDOMAINS):
+                if h1[dom][0][1] > 0 or dom == NDOMAINS - 1:
+                    outfiles[dom].write("%.3f %d %d %.3f %.3f %.3f %.3f %.3f 
%.3f %.3f %.3f %.3f %.3f %.3f %.3f %.3f\n" %
+                                     (interval, cpuidx, dom,
+                                     h1[dom][0][0], h1[dom][0][1], 
h1[dom][0][2],
+                                     h1[dom][1],
+                                     h1[dom][2][0], h1[dom][2][1], 
h1[dom][2][2],
+                                     h1[dom][3][0], h1[dom][3][1], 
h1[dom][3][2],
+                                     h1[dom][4], 
+                                     h1[dom][5][0], h1[dom][5][1]))
+                    outfiles[dom].flush()
+
+        interval += options.interval
+        time.sleep(1)
+
+    for dom in range(0, NDOMAINS):
+        outfiles[dom].close()
+
+# start xenbaked
+def start_xenbaked():
+    global options
+    global args
+    
+    os.system("killall -9 xenbaked")
+    # assumes that xenbaked is in your path
+    os.system("xenbaked --ms_per_sample=%d &" %
+              options.mspersample)
+    time.sleep(1)
+
+# stop xenbaked
+def stop_xenbaked():
+    os.system("killall -s INT xenbaked")
+
+def main():
+    global options
+    global args
+    global domains
+
+    parser = setup_cmdline_parser()
+    (options, args) = parser.parse_args()
+    
+    start_xenbaked()
+    if options.live:
+        show_livestats()
+    else:
+        try:
+            writelog()
+        except:
+            print 'Quitting.'
+    stop_xenbaked()
+
+if __name__ == "__main__":
+    main()
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/mergereport
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/mergereport Sat Nov 19 05:16:29 2005
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+# Dan Smith <danms@xxxxxxxxxx> - 16-Sep-2005
+#
+# This script takes all the .report files in the current
+# directory and generates a summary table, showing the 
+# number of PASS, FAIL, XPASS, and XFAIL tests in each 
+# report
+
+
+echo "            Platform | PASS | FAIL | XPASS | XFAIL |"
+echo "---------------------+------+------+-------+-------+"
+
+for r in *.report; do
+    
+    mach=$(basename $r .report)
+    pass=$(cat $r | grep '  PASS' | cut -d : -f 2 | sed 's/  *//')
+    fail=$(cat $r | grep '  FAIL' | cut -d : -f 2 | sed 's/  *//')
+    xpas=$(cat $r | grep ' XPASS' | cut -d : -f 2 | sed 's/  *//')
+    xfal=$(cat $r | grep ' XFAIL' | cut -d : -f 2 | sed 's/  *//')
+
+    printf "%20s | %4s | %4s | %5s | %5s |\n" "$mach" "$pass" \
+           "$fail" "$xpas" "$xfal"
+
+done
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/ramdisk/patches/buildroot/hping.patch
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/ramdisk/patches/buildroot/hping.patch       Sat Nov 19 
05:16:29 2005
@@ -0,0 +1,67 @@
+diff -Naur buildroot.orig/package/Config.in buildroot/package/Config.in
+--- buildroot.orig/package/Config.in   2005-11-15 07:30:21.000000000 -0800
++++ buildroot/package/Config.in        2005-11-15 07:30:54.000000000 -0800
+@@ -118,6 +118,6 @@
+ source "package/wireless-tools/Config.in"
+ source "package/xorg/Config.in"
+ source "package/zlib/Config.in"
+-
++source "package/hping/Config.in"
+ 
+ endmenu
+diff -Naur buildroot.orig/package/hping/Config.in 
buildroot/package/hping/Config.in
+--- buildroot.orig/package/hping/Config.in     1969-12-31 16:00:00.000000000 
-0800
++++ buildroot/package/hping/Config.in  2005-11-14 14:13:20.000000000 -0800
+@@ -0,0 +1,5 @@
++config BR2_PACKAGE_HPING
++      bool "hping"
++      default y
++      help
++              This is the hping package
+diff -Naur buildroot.orig/package/hping/hping.mk 
buildroot/package/hping/hping.mk
+--- buildroot.orig/package/hping/hping.mk      1969-12-31 16:00:00.000000000 
-0800
++++ buildroot/package/hping/hping.mk   2005-11-14 15:11:06.000000000 -0800
+@@ -0,0 +1,43 @@
++# Taken from the buildroot examples
++
++HPING_VERSION = 2.0.0-rc3
++HPING_TBALL = hping$(HPING_VERSION).tar.gz
++HPING_URL = http://www.hping.org/$(HPING_TBALL)
++HPING_DIR = $(BUILD_DIR)/hping2-rc3
++HPING_TARGET_BINARY = usr/bin/hping
++HPING_BINARY = hping
++
++$(DL_DIR)/$(HPING_TBALL):
++      $(WGET) -P $(DL_DIR) $(HPING_URL)
++
++$(HPING_DIR)/.source: $(DL_DIR)/$(HPING_TBALL)
++      tar xzf $(DL_DIR)/$(HPING_TBALL) -C $(BUILD_DIR)
++      touch $(HPING_DIR)/.source
++
++$(HPING_DIR)/.configured: $(HPING_DIR)/.source
++      (cd $(HPING_DIR); \
++      ./configure; )
++      cat $(HPING_DIR)/Makefile | grep -v './hping2 -v' > $(HPING_DIR)/foo
++      mv $(HPING_DIR)/foo $(HPING_DIR)/Makefile
++      touch $(HPING_DIR)/.configured 
++
++$(HPING_DIR)/$(HPING_BINARY): $(HPING_DIR)/.configured
++      $(MAKE) CC=$(TARGET_CC) -C $(HPING_DIR)
++
++$(TARGET_DIR)/$(HPING_TARGET_BINARY): $(HPING_DIR)/$(HPING_BINARY)
++      cp $(HPING_DIR)/hping2 $(TARGET_DIR)/bin
++
++hping: $(TARGET_DIR)/$(HPING_TARGET_BINARY)
++
++hping-clean:
++      $(MAKE) prefix=$(TARGET_DIR)/usr -C $(HPING_DIR) uninstall
++      -$(MAKE) -C $(HPING_DIR) clean
++
++hping-dirclean:
++      rm -Rf $(HPING_DIR)
++
++ifeq ($(strip $(BR2_PACKAGE_HPING)),y)
++TARGETS += hping
++endif
++
++
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/block-list/06_block-list_checkremove_pos.py
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/block-list/06_block-list_checkremove_pos.py   Sat Nov 
19 05:16:29 2005
@@ -0,0 +1,66 @@
+#!/usr/bin/python
+
+# Copyright (C) International Business Machines Corp., 2005
+# Author: Dan Smith <danms@xxxxxxxxxx>
+
+from XmTestLib import *
+
+domain = XmTestDomain()
+
+try:
+    domain.start()
+except DomainError, e:
+    FAIL(str(e))
+
+try:
+    console = XmConsole(domain.getName())
+except ConsoleError, e:
+    FAIL(str(e))
+
+s, o = traceCommand("xm block-list %s" % domain.getName())
+if s != 0:
+    FAIL("block-list returned !0 when no devices attached")
+if o:
+    FAIL("block-list without devices reported something!")
+
+s, o = traceCommand("xm block-attach %s phy:/dev/ram0 hda1 w" % 
domain.getName())
+if s != 0:
+    FAIL("Unable to attach /dev/ram0->hda1")
+
+s, o = traceCommand("xm block-list %s" % domain.getName())
+if s != 0:
+    FAIL("block-list failed")
+if not o.find("769"):
+    FAIL("block-list didn't show the block device I just attached!")
+
+s, o = traceCommand("xm block-attach %s phy:/dev/ram1 hda2 w" % 
domain.getName())
+if s != 0:
+    FAIL("Unable to attach /dev/ram1->hda2")
+
+s, o = traceCommand("xm block-list %s" % domain.getName())
+if s != 0:
+    FAIL("block-list failed")
+if not o.find("770"):
+    FAIL("block-list didn't show the other block device I just attached!")
+
+s, o = traceCommand("xm block-detach %s 769" % domain.getName())
+if s != 0:
+    FAIL("block-destroy of hda1 failed")
+
+s, o = traceCommand("xm block-list %s" % domain.getName())
+if s != 0:
+    FAIL("block-list failed after detaching a device")
+if o.find("769"):
+    FAIL("hda1 still shown in block-list after detach!")
+if not o.find("770"):
+    FAIL("hda2 not shown after detach of hda1!")
+
+s, o = traceCommand("xm block-detach %s 770" % domain.getName())
+if s != 0:
+    FAIL("block-list failed after detaching another device")
+if o.find("770"):
+    FAIL("hda2 still shown in block-list after detach!")
+if o:
+    FAIL("block-list still shows something after all devices detached!")
+    
+
diff -r e62c54ab862f -r 878a9891b056 
tools/xm-test/tests/create/15_create_smallmem_pos.py
--- /dev/null   Sat Nov 19 05:06:09 2005
+++ b/tools/xm-test/tests/create/15_create_smallmem_pos.py      Sat Nov 19 
05:16:29 2005
@@ -0,0 +1,28 @@
+#!/usr/bin/python
+
+# Copyright (C) International Business Machines Corp., 2005
+# Author: Dan Smith <danms@xxxxxxxxxx>
+
+from XmTestLib import *
+
+MEM = 16
+
+domain = XmTestDomain(extraOpts={"memory":"%i" % MEM,
+                                 "extra" :"mem=%iM" % MEM})
+
+try:
+    domain.start()
+except DomainError, e:
+    FAIL("Unable to start a domain with %i MB" % MEM)
+
+try:
+    console = XmConsole(domain.getName())
+    console.sendInput("input")
+    console.runCmd("ls")
+except ConsoleError, e:
+    if e.reason == RUNAWAY:
+        FAIL("Bug #380: Starting a console with %i MB crashed the console 
daemon" % MEM)
+    else:
+        FAIL("Starting a console with %i MB failed: domain dies immediately!" 
% MEM)
+
+domain.destroy()
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/lib/XmTestReport/xmtest.py
--- a/tools/xm-test/lib/XmTestReport/xmtest.py  Sat Nov 19 05:06:09 2005
+++ /dev/null   Sat Nov 19 05:16:29 2005
@@ -1,3 +0,0 @@
-#!/usr/bin/python
-
-XM_TEST_VERSION = "0.4.0"
diff -r e62c54ab862f -r 878a9891b056 tools/xm-test/tests/create/log
--- a/tools/xm-test/tests/create/log    Sat Nov 19 05:06:09 2005
+++ /dev/null   Sat Nov 19 05:16:29 2005
@@ -1,14 +0,0 @@
--- BEGIN XmTest Log @Fri Oct 28 13:00:55 PDT 2005
-*input
-
-
-BusyBox v1.01 (2005.10.27-17:34+0000) Built-in shell (ash)
-Enter 'help' for a list of built-in commands.
-
--sh: can't access tty; job control turned off
-*ls
-CVS         etc         linuxrc     opt         sbin        var
-bin         home        lost+found  proc        tmp
-dev         lib         mnt         root        usr
-
--- END XmTest Log

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


 


Rackspace

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