x86/physmap: Prevent incorrect updates of m2p mappings

In certain conditions, such as low memory, set_p2m_entry() can fail.
Currently, the p2m and m2p tables will get out of sync because we still
update the m2p table after the p2m update has failed.

If that happens, subsequent guest-invoked memory operations can cause
BUG()s and ASSERT()s to kill Xen.

This is fixed by only updating the m2p table iff the p2m was
successfully updated.

This is a security problem, XSA-22 / CVE-2012-4537.

Signed-off-by: Andrew Cooper <andrew.cooper3@citrix.com>
Acked-by: Ian Campbell <ian.campbell@citrix.com>
Acked-by: Ian Jackson <ian.jackson@eu.citrix.com>
[ Add backport of 20516:c4e620a2e65c to correct error return from set_p2m_entry ]

diff -r 14709d196e43 xen/arch/x86/mm/p2m.c
--- a/xen/arch/x86/mm/p2m.c	Wed Jun 30 18:26:13 2010 +0100
+++ b/xen/arch/x86/mm/p2m.c	Fri Oct 26 11:27:44 2012 +0100
@@ -1500,14 +1500,15 @@ int set_p2m_entry(struct domain *d, unsi
 {
     unsigned long todo = 1ul << page_order;
     unsigned int order;
-    int rc = 0;
+    int rc = 1;
 
     while ( todo )
     {
         order = ((((gfn | mfn_x(mfn) | todo) & (SUPERPAGE_PAGES - 1)) == 0) &&
                  hvm_hap_has_2mb(d)) ? 9 : 0;
 
-        rc = d->arch.p2m->set_entry(d, gfn, mfn, order, p2mt);
+        if ( !d->arch.p2m->set_entry(d, gfn, mfn, order, p2mt) )
+            rc = 0;
         gfn += 1ul << order;
         if ( mfn_x(mfn) != INVALID_MFN )
             mfn = _mfn(mfn_x(mfn) + (1ul << order));
@@ -2054,7 +2055,10 @@ guest_physmap_add_entry(struct domain *d
     if ( mfn_valid(_mfn(mfn)) ) 
     {
         if ( !set_p2m_entry(d, gfn, _mfn(mfn), page_order, t) )
+        {
             rc = -EINVAL;
+            goto out; /* Failed to update p2m, bail without updating m2p. */
+        }
         for ( i = 0; i < (1UL << page_order); i++ )
             set_gpfn_from_mfn(mfn+i, gfn+i);
     }
@@ -2072,6 +2076,7 @@ guest_physmap_add_entry(struct domain *d
         }
     }
 
+out:
     audit_p2m(d);
     p2m_unlock(d->arch.p2m);
 
