Skip to contentSkip to conversation

x86/ucode: Fix module-handling use-aftere-free's

PATCH Superseded Andrew Cooper 3 participants 41 messages Oct 28, 2024 – Nov 5, 2024

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover x86/ucode: Fix module-handling use-aftere-free's

Some of these were known, some not, but they were creating unecessary complexity in the Hyperlaunch series.

https://gitlab.com/xen-project/people/andyhhp/xen/-/pipelines/1513996396

Andrew Cooper (10):
x86/ucode: Turn microcode_init_cache() into a presmp_initcall x86/ucode: Delete the microcode_init() initcall
x86/ucode: Break early_microcode_load() out of early_microcode_init() x86/ucode: Fold early_microcode_update_cpu() into it's single caller x86/ucode: Fold microcode_grab_module() into its single caller x86/ucode: Enforce invariant about module selection x86/ucode: Move the CPIO path string into microcode_ops x86/ucode: Use bootstrap_unmap() in early_microcode_load() x86/ucode: Drop ucode_mod and ucode_blob
x86/ucode: Fold early_update_cache() into its single caller

 xen/arch/x86/cpu/microcode/amd.c     |   4 +
 xen/arch/x86/cpu/microcode/core.c    | 329 ++++++++++++++-------------
 xen/arch/x86/cpu/microcode/intel.c   |   4 +
 xen/arch/x86/cpu/microcode/private.h |   7 +
 xen/arch/x86/include/asm/microcode.h |   1 -
 xen/arch/x86/setup.c                 |   2 -
 6 files changed, 189 insertions(+), 158 deletions(-)
Signature · 1 line
2.39.5
#1 lore raw

PATCH 1/10 x86/ucode: Turn microcode_init_cache() into a presmp_initcall

There's no need for microcode_init_cache() to be called exactly where it is in __start_xen(). All that matters is it must be after xmalloc() is available and before APs start up.

As a consequence, microcode_init_cache() runs a little later on boot now.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c    | 4 +++-
 xen/arch/x86/include/asm/microcode.h | 1 -
 xen/arch/x86/setup.c                 | 2 --
 3 files changed, 3 insertions(+), 4 deletions(-)
xen/arch/x86/cpu/microcode/core.c +3 -1
index 8d916d891e6e..9a2cc631d2aa 100644
@@ -819,8 +819,9 @@ static int __init early_update_cache(const void *data, size_t len)
     return rc;
 }
 
-int __init microcode_init_cache(struct boot_info *bi)
+static int __init cf_check microcode_init_cache(void)
 {
+    struct boot_info *bi = &xen_boot_info;
     int rc = 0;
 
     if ( !ucode_ops.apply_microcode )
@@ -838,6 +839,7 @@ int __init microcode_init_cache(struct boot_info *bi)
 
     return rc;
 }
+presmp_initcall(microcode_init_cache);
 
 /* BSP calls this function to parse ucode blob and then apply an update. */
 static int __init early_microcode_update_cpu(void)
xen/arch/x86/include/asm/microcode.h +0 -1
index a278773f8b5d..c62c131fd047 100644
@@ -28,6 +28,5 @@ int microcode_update_one(void);
 
 struct boot_info;
 int early_microcode_init(struct boot_info *bi);
-int microcode_init_cache(struct boot_info *bi);
 
 #endif /* ASM_X86__MICROCODE_H */
xen/arch/x86/setup.c +0 -2
index 177f4024abca..5db57e1b1af2 100644
@@ -1952,8 +1952,6 @@ void asmlinkage __init noreturn __start_xen(void)
 
     timer_init();
 
-    microcode_init_cache(bi); /* Needs xmalloc() */
-
     tsx_init(); /* Needs microcode.  May change HLE/RTM feature bits. */
 
     calculate_raw_cpu_policy(); /* Needs microcode.  No other dependenices. */
Signature · 1 line
2.39.5
Acked-by on v1 1/10
#2 lore raw

Re: [PATCH 01/10] x86/ucode: Turn microcode_init_cache() into a presmp_initcall

Quoted 9 lines · Andrew Cooper

There's no need for microcode_init_cache() to be called exactly where it is in __start_xen(). All that matters is it must be after xmalloc() is available and before APs start up.

As a consequence, microcode_init_cache() runs a little later on boot now.

No functional change.

xen/arch/x86/cpu/microcode/core.c static int __init early_update_cache(const void *data, size_t len) · line 824

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +2 -1
@@ -819,8 +819,9 @@ static int __init early_update_cache(const void *data, size_t len)
     return rc;
 }
 
-int __init microcode_init_cache(struct boot_info *bi)
+static int __init cf_check microcode_init_cache(void)
 {
+    struct boot_info *bi = &xen_boot_info;

I take it that this not becoming pointer-to-const is related to your reply to Roger elsewhere, where he asked for adding const, while you expect the const to need dropping again in the course of Daniel's work?

Jan

#3 lore raw

Re: [PATCH 01/10] x86/ucode: Turn microcode_init_cache() into a presmp_initcall

Quoted 11 lines · Jan Beulich
Quoted 9 lines · Andrew Cooper

There's no need for microcode_init_cache() to be called exactly where it is in __start_xen(). All that matters is it must be after xmalloc() is available and before APs start up.

As a consequence, microcode_init_cache() runs a little later on boot now.

No functional change.

Thanks.

Quoted 7 lines
Quoted 7 lines
xen/arch/x86/cpu/microcode/core.c +0 -0
@@ -819,8 +819,9 @@ static int __init early_update_cache(const void *data, size_t len)
     return rc;
 }
 
Quoted 7 lines

xen/arch/x86/cpu/microcode/core.c static int __init early_update_cache(const void *data, size_t len) · line 824

Quoted 4 lines
xen/arch/x86/cpu/microcode/core.c +2 -1
-int __init microcode_init_cache(struct boot_info *bi)
+static int __init cf_check microcode_init_cache(void)
 {
+    struct boot_info *bi = &xen_boot_info;

I take it that this not becoming pointer-to-const is related to your reply to Roger elsewhere, where he asked for adding const, while you expect the const to need dropping again in the course of Daniel's work?

It's not const because that wouldn't even compile here.

But yes, it does get mutated by the end of the boot module work.

~Andrew

Reviewed-by on v1 1/10
#4 lore raw

Re: [PATCH 01/10] x86/ucode: Turn microcode_init_cache() into a presmp_initcall

In reply to Andrew Cooper
Quoted 24 lines · Andrew Cooper

There's no need for microcode_init_cache() to be called exactly where it is in __start_xen(). All that matters is it must be after xmalloc() is available and before APs start up.

As a consequence, microcode_init_cache() runs a little later on boot now.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
  xen/arch/x86/cpu/microcode/core.c    | 4 +++-
  xen/arch/x86/include/asm/microcode.h | 1 -
  xen/arch/x86/setup.c                 | 2 --
  3 files changed, 3 insertions(+), 4 deletions(-)
xen/arch/x86/cpu/microcode/core.c +0 -0
index 8d916d891e6e..9a2cc631d2aa 100644

xen/arch/x86/cpu/microcode/core.c static int __init early_update_cache(const void *data, size_t len) · line 824

Quoted 7 lines
xen/arch/x86/cpu/microcode/core.c +2 -1
@@ -819,8 +819,9 @@ static int __init early_update_cache(const void *data, size_t len)
      return rc;
  }
 
-int __init microcode_init_cache(struct boot_info *bi)
+static int __init cf_check microcode_init_cache(void)
  {
+    struct boot_info *bi = &xen_boot_info;

For context, the current function definition didn't have *bi const because it will become necessary later update state in bi. So it is natural for it to remain as such by getting the reference from global.

#5 lore raw

PATCH 2/10 x86/ucode: Delete the microcode_init() initcall

In reply to Andrew Cooper

The comment highlights just how bogus this really is. Being an initcall, the boot allocator is long gone, and bootstrap_unmap() is a no-op.

The fact there is nothing to do should be a giant red flag about the validity of the mappings "being freed". Indeed, they both constitute use-after-frees.

We could move the size/data/end clobbering into microcode_init_cache() which is the final consumer of the information, but we're intending to delete these static variables entirely, and it's less churn to just leave them dangling for a few patches.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

After the $N'th rearranging, this could actually be merged into "x86/ucode:
Drop ucode_mod and ucode_blob" with no effect on the intermediate patches.

---
 xen/arch/x86/cpu/microcode/core.c | 22 ----------------------
 1 file changed, 22 deletions(-)
xen/arch/x86/cpu/microcode/core.c +0 -22
index 9a2cc631d2aa..3e815f1880af 100644
@@ -758,28 +758,6 @@ int microcode_update(XEN_GUEST_HANDLE(const_void) buf,
     return continue_hypercall_on_cpu(0, microcode_update_helper, buffer);
 }
 
-static int __init cf_check microcode_init(void)
-{
-    /*
-     * At this point, all CPUs should have updated their microcode
-     * via the early_microcode_* paths so free the microcode blob.
-     */
-    if ( ucode_blob.size )
-    {
-        bootstrap_unmap();
-        ucode_blob.size = 0;
-        ucode_blob.data = NULL;
-    }
-    else if ( ucode_mod.mod_end )
-    {
-        bootstrap_unmap();
-        ucode_mod.mod_end = 0;
-    }
-
-    return 0;
-}
-__initcall(microcode_init);
-
 /* Load a cached update to current cpu */
 int microcode_update_one(void)
 {
Signature · 1 line
2.39.5
Acked-by on v1 2/10
#6 lore raw

Re: [PATCH 02/10] x86/ucode: Delete the microcode_init() initcall

Quoted 2 lines · Andrew Cooper

The comment highlights just how bogus this really is. Being an initcall, the boot allocator is long gone, and bootstrap_unmap() is a no-op.

How's the boot allocator coming into the picture here? This is all about (un)mapping, not allocating.

Quoted 2 lines

The fact there is nothing to do should be a giant red flag about the validity of the mappings "being freed". Indeed, they both constitute use-after-frees.

I can't spot any use-after-free; the pointers in question ...

Quoted 17 lines
xen/arch/x86/cpu/microcode/core.c +0 -11
@@ -758,28 +758,6 @@ int microcode_update(XEN_GUEST_HANDLE(const_void) buf,
     return continue_hypercall_on_cpu(0, microcode_update_helper, buffer);
 }
 
-static int __init cf_check microcode_init(void)
-{
-    /*
-     * At this point, all CPUs should have updated their microcode
-     * via the early_microcode_* paths so free the microcode blob.
-     */
-    if ( ucode_blob.size )
-    {
-        bootstrap_unmap();
-        ucode_blob.size = 0;
-        ucode_blob.data = NULL;

xen/arch/x86/cpu/microcode/core.c int microcode_update(XEN_GUEST_HANDLE(const_void) buf, · line 781

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +0 -10
-    }
-    else if ( ucode_mod.mod_end )
-    {
-        bootstrap_unmap();
-        ucode_mod.mod_end = 0;
-    }
-
-    return 0;
-}
-__initcall(microcode_init);

... aren't used anywhere. bootstrap_unmap() is "just in case" (perhaps indeed a no-op at least nowadays), and the rest is field clobbering. I'm okay with the code change, so

yet I'd like to ask for the description to be "softened" some.

Jan

#7 lore raw

Re: [PATCH 02/10] x86/ucode: Delete the microcode_init() initcall

Quoted 40 lines · Jan Beulich
Quoted 2 lines · Andrew Cooper

The comment highlights just how bogus this really is. Being an initcall, the boot allocator is long gone, and bootstrap_unmap() is a no-op.

How's the boot allocator coming into the picture here? This is all about (un)mapping, not allocating.

Quoted 2 lines

The fact there is nothing to do should be a giant red flag about the validity of the mappings "being freed". Indeed, they both constitute use-after-frees.

I can't spot any use-after-free; the pointers in question ...

Quoted 17 lines
xen/arch/x86/cpu/microcode/core.c +0 -11
@@ -758,28 +758,6 @@ int microcode_update(XEN_GUEST_HANDLE(const_void) buf,
     return continue_hypercall_on_cpu(0, microcode_update_helper, buffer);
 }
 
-static int __init cf_check microcode_init(void)
-{
-    /*
-     * At this point, all CPUs should have updated their microcode
-     * via the early_microcode_* paths so free the microcode blob.
-     */
-    if ( ucode_blob.size )
-    {
-        bootstrap_unmap();
-        ucode_blob.size = 0;
-        ucode_blob.data = NULL;

xen/arch/x86/cpu/microcode/core.c int microcode_update(XEN_GUEST_HANDLE(const_void) buf, · line 781

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +0 -10
-    }
-    else if ( ucode_mod.mod_end )
-    {
-        bootstrap_unmap();
-        ucode_mod.mod_end = 0;
-    }
-
-    return 0;
-}
-__initcall(microcode_init);

... aren't used anywhere. bootstrap_unmap() is "just in case" (perhaps indeed a no-op at least nowadays), and the rest is field clobbering. I'm okay with the code change, so

Quoted 2 lines

yet I'd like to ask for the description to be "softened" some.

As I said, this could be folded into patch 9, given this particular arrangement of the series.

The UAFs are apparent *because* the comment demonstrates a false line of reasoning.

ucode_mod literally is used after free.  ucode=$n is genuinely buggy today, because its a stash of a physical pointer across move_xen().

ucode_blob stashes a virtual pointer.  This was even noticed in dc380df12acf ("x86/ucode: load microcode earlier on boot CPU")

---
It needs to rescan the modules in order to find the new virtual address of the ucode blob because it changes during the boot process, e.g. from 0x00000000010802fc to 0xffff83204dac52fc.
---

which highlighted the problem but duct-taped over it.

~Andrew

#8 lore raw

Re: [PATCH 02/10] x86/ucode: Delete the microcode_init() initcall

Quoted 44 lines · Andrew Cooper
Quoted 40 lines · Jan Beulich
Quoted 2 lines · Andrew Cooper

The comment highlights just how bogus this really is. Being an initcall, the boot allocator is long gone, and bootstrap_unmap() is a no-op.

How's the boot allocator coming into the picture here? This is all about (un)mapping, not allocating.

Quoted 2 lines

The fact there is nothing to do should be a giant red flag about the validity of the mappings "being freed". Indeed, they both constitute use-after-frees.

I can't spot any use-after-free; the pointers in question ...

Quoted 17 lines
xen/arch/x86/cpu/microcode/core.c +0 -11
@@ -758,28 +758,6 @@ int microcode_update(XEN_GUEST_HANDLE(const_void) buf,
     return continue_hypercall_on_cpu(0, microcode_update_helper, buffer);
 }
 
-static int __init cf_check microcode_init(void)
-{
-    /*
-     * At this point, all CPUs should have updated their microcode
-     * via the early_microcode_* paths so free the microcode blob.
-     */
-    if ( ucode_blob.size )
-    {
-        bootstrap_unmap();
-        ucode_blob.size = 0;
-        ucode_blob.data = NULL;

xen/arch/x86/cpu/microcode/core.c int microcode_update(XEN_GUEST_HANDLE(const_void) buf, · line 781

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +0 -10
-    }
-    else if ( ucode_mod.mod_end )
-    {
-        bootstrap_unmap();
-        ucode_mod.mod_end = 0;
-    }
-
-    return 0;
-}
-__initcall(microcode_init);

... aren't used anywhere. bootstrap_unmap() is "just in case" (perhaps indeed a no-op at least nowadays), and the rest is field clobbering. I'm okay with the code change, so

Quoted 2 lines

yet I'd like to ask for the description to be "softened" some.

Quoted 2 lines

As I said, this could be folded into patch 9, given this particular arrangement of the series.

I certainly don't mind the folding, but then I'd still like to see the description of the resulting patch before giving a (hopefully) unconditional ack.

Quoted 5 lines

The UAFs are apparent *because* the comment demonstrates a false line of reasoning.

ucode_mod literally is used after free.  ucode=$n is genuinely buggy today, because its a stash of a physical pointer across move_xen().

Maybe my problem is that the UAF is elsewhere, not in the code you delete? If so, it might help to simply point out where the actual bad use is. As it stands, microcode_init() doesn't have any uses (reads), only writes. What I agree with is that the comment there is at best misleading.

Jan

Quoted 12 lines

ucode_blob stashes a virtual pointer.  This was even noticed in dc380df12acf ("x86/ucode: load microcode earlier on boot CPU")

---
It needs to rescan the modules in order to find the new virtual address of the ucode blob because it changes during the boot process, e.g. from 0x00000000010802fc to 0xffff83204dac52fc.
---

which highlighted the problem but duct-taped over it.

~Andrew

Reviewed-by on v1 2/10
#9 lore raw

Re: [PATCH 02/10] x86/ucode: Delete the microcode_init() initcall

In reply to Andrew Cooper
Quoted 14 lines · Andrew Cooper

The comment highlights just how bogus this really is. Being an initcall, the boot allocator is long gone, and bootstrap_unmap() is a no-op.

The fact there is nothing to do should be a giant red flag about the validity of the mappings "being freed". Indeed, they both constitute use-after-frees.

We could move the size/data/end clobbering into microcode_init_cache() which is the final consumer of the information, but we're intending to delete these static variables entirely, and it's less churn to just leave them dangling for a few patches.

No functional change.

Quoted 8 lines

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

After the $N'th rearranging, this could actually be merged into "x86/ucode:
Drop ucode_mod and ucode_blob" with no effect on the intermediate patches.
---

Not sure if this helps, but for clarification sake, the module itself is freed by discard_initial_images() and ucode_mod is __initdata and will be cleaned up with the rest of _initdata. This function is called after the last user of ucode_mod and the call to bootstrap_unmap() perpetuates the assumption that some how the underlying module has remained mapped. There is not any condition where this function does anything that would affect the execution of the hypervisor. It frees nothing and sets the value of a unit local variable that is no longer used shortly before the backing memory is freed.

As to patch ordering, I have no opinion.

#10 lore raw

PATCH 3/10 x86/ucode: Break early_microcode_load() out of early_microcode_init()

In reply to Andrew Cooper

microcode_grab_module() and early_microcode_update_cpu() are logically one task that passes state via static variables.

We intend to delete said static variables, so start by moving these functions out of early_microcode_init().

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)
xen/arch/x86/cpu/microcode/core.c +17 -4
index 3e815f1880af..d13f8338e4e6 100644
@@ -854,6 +854,22 @@ static int __init early_microcode_update_cpu(void)
     return microcode_update_cpu(patch, 0);
 }
 
+/*
+ * There are several tasks:
+ * - Locate the ucode blob in the boot modules.
+ * - Parse and attempt in-place load.
+ * - Inform microcode_init_cache() of how to find the blob again.
+ */
+static int __init early_microcode_load(struct boot_info *bi)
+{
+    microcode_grab_module(bi);
+
+    if ( !ucode_mod.mod_end && !ucode_blob.size )
+        return 0;
+
+    return early_microcode_update_cpu();
+}
+
 int __init early_microcode_init(struct boot_info *bi)
 {
     const struct cpuinfo_x86 *c = &boot_cpu_data;
@@ -897,10 +913,7 @@ int __init early_microcode_init(struct boot_info *bi)
         return -ENODEV;
     }
 
-    microcode_grab_module(bi);
-
-    if ( ucode_mod.mod_end || ucode_blob.size )
-        rc = early_microcode_update_cpu();
+    rc = early_microcode_load(bi);
 
     /*
      * Some CPUID leaves and MSRs are only present after microcode updates
Signature · 1 line
2.39.5
Acked-by on v1 3/10
#11 lore raw

Re: [PATCH 03/10] x86/ucode: Break early_microcode_load() out of early_microcode_init()

Quoted 9 lines · Andrew Cooper

microcode_grab_module() and early_microcode_update_cpu() are logically one task that passes state via static variables.

We intend to delete said static variables, so start by moving these functions out of early_microcode_init().

No functional change.

I expect I'll see later how this actually helps.

Jan

Reviewed-by on v1 3/10
#12 lore raw

Re: [PATCH 03/10] x86/ucode: Break early_microcode_load() out of early_microcode_init()

In reply to Andrew Cooper
Quoted 6 lines · Andrew Cooper

microcode_grab_module() and early_microcode_update_cpu() are logically one task that passes state via static variables.

We intend to delete said static variables, so start by moving these functions out of early_microcode_init().

Quoted 8 lines

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>
---

#13 lore raw

PATCH 4/10 x86/ucode: Fold early_microcode_update_cpu() into it's single caller

In reply to Andrew Cooper

Diff-wise, as early_microcode_update_cpu() is the larger function, this more closely resembles "merge early_microcode_load() into it's single callee", but the end result is the same.

At the same time, rename the len variable to size. This is for better consistency with existing logic, and to reduce churn later.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c | 38 +++++++++++++------------------
 1 file changed, 16 insertions(+), 22 deletions(-)
xen/arch/x86/cpu/microcode/core.c +16 -22
index d13f8338e4e6..0b00e70f3b07 100644
@@ -819,28 +819,38 @@ static int __init cf_check microcode_init_cache(void)
 }
 presmp_initcall(microcode_init_cache);
 
-/* BSP calls this function to parse ucode blob and then apply an update. */
-static int __init early_microcode_update_cpu(void)
+/*
+ * There are several tasks:
+ * - Locate the ucode blob in the boot modules.
+ * - Parse and attempt in-place load.
+ * - Inform microcode_init_cache() of how to find the blob again.
+ */
+static int __init early_microcode_load(struct boot_info *bi)
 {
     const void *data = NULL;
-    size_t len;
+    size_t size;
     struct microcode_patch *patch;
 
+    microcode_grab_module(bi);
+
+    if ( !ucode_mod.mod_end && !ucode_blob.size )
+        return 0;
+
     if ( ucode_blob.size )
     {
-        len = ucode_blob.size;
+        size = ucode_blob.size;
         data = ucode_blob.data;
     }
     else if ( ucode_mod.mod_end )
     {
-        len = ucode_mod.mod_end;
+        size = ucode_mod.mod_end;
         data = bootstrap_map(&ucode_mod);
     }
 
     if ( !data )
         return -ENOMEM;
 
-    patch = ucode_ops.cpu_request_microcode(data, len, false);
+    patch = ucode_ops.cpu_request_microcode(data, size, false);
     if ( IS_ERR(patch) )
     {
         printk(XENLOG_WARNING "Parsing microcode blob error %ld\n",
@@ -854,22 +864,6 @@ static int __init early_microcode_update_cpu(void)
     return microcode_update_cpu(patch, 0);
 }
 
-/*
- * There are several tasks:
- * - Locate the ucode blob in the boot modules.
- * - Parse and attempt in-place load.
- * - Inform microcode_init_cache() of how to find the blob again.
- */
-static int __init early_microcode_load(struct boot_info *bi)
-{
-    microcode_grab_module(bi);
-
-    if ( !ucode_mod.mod_end && !ucode_blob.size )
-        return 0;
-
-    return early_microcode_update_cpu();
-}
-
 int __init early_microcode_init(struct boot_info *bi)
 {
     const struct cpuinfo_x86 *c = &boot_cpu_data;
Signature · 1 line
2.39.5
Acked-by on v1 4/10
#14 lore raw

Re: [PATCH 04/10] x86/ucode: Fold early_microcode_update_cpu() into it's single caller

Quoted 10 lines · Andrew Cooper

Diff-wise, as early_microcode_update_cpu() is the larger function, this more closely resembles "merge early_microcode_load() into it's single callee", but the end result is the same.

At the same time, rename the len variable to size. This is for better consistency with existing logic, and to reduce churn later.

No functional change.

As a nit - in the title isn't it "its", i.e. without the apostrophe?

Jan

#15 lore raw

Re: [PATCH 04/10] x86/ucode: Fold early_microcode_update_cpu() into it's single caller

Quoted 5 lines · Jan Beulich
Quoted 4 lines · Andrew Cooper

Diff-wise, as early_microcode_update_cpu() is the larger function, this more closely resembles "merge early_microcode_load() into it's single callee", but the end result is the same.

Quoted 7 lines
Quoted 6 lines

At the same time, rename the len variable to size. This is for better consistency with existing logic, and to reduce churn later.

No functional change.

Thanks.

Quoted 1 line

As a nit - in the title isn't it "its", i.e. without the apostrophe?

Yes.  Will fix.

~Andrew

Reviewed-by on v1 4/10
#16 lore raw

Re: [PATCH 04/10] x86/ucode: Fold early_microcode_update_cpu() into it's single caller

In reply to Andrew Cooper
Quoted 7 lines · Andrew Cooper

Diff-wise, as early_microcode_update_cpu() is the larger function, this more closely resembles "merge early_microcode_load() into it's single callee", but the end result is the same.

At the same time, rename the len variable to size. This is for better consistency with existing logic, and to reduce churn later.

Quoted 8 lines

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>
---

#17 lore raw

PATCH 5/10 x86/ucode: Fold microcode_grab_module() into its single caller

In reply to Andrew Cooper

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c | 23 +++++++++--------------
 1 file changed, 9 insertions(+), 14 deletions(-)
xen/arch/x86/cpu/microcode/core.c +9 -14
index 0b00e70f3b07..4c4003bf9687 100644
@@ -205,19 +205,6 @@ static void __init microcode_scan_module(struct boot_info *bi)
     }
 }
 
-static void __init microcode_grab_module(struct boot_info *bi)
-{
-    if ( ucode_mod_idx < 0 )
-        ucode_mod_idx += bi->nr_modules;
-    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
-         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
-        goto scan;
-    ucode_mod = *bi->mods[ucode_mod_idx].mod;
-scan:
-    if ( ucode_scan )
-        microcode_scan_module(bi);
-}
-
 static struct microcode_ops __ro_after_init ucode_ops;
 
 static DEFINE_SPINLOCK(microcode_mutex);
@@ -831,7 +818,15 @@ static int __init early_microcode_load(struct boot_info *bi)
     size_t size;
     struct microcode_patch *patch;
 
-    microcode_grab_module(bi);
+    if ( ucode_mod_idx < 0 )
+        ucode_mod_idx += bi->nr_modules;
+    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
+         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
+        goto scan;
+    ucode_mod = *bi->mods[ucode_mod_idx].mod;
+ scan:
+    if ( ucode_scan )
+        microcode_scan_module(bi);
 
     if ( !ucode_mod.mod_end && !ucode_blob.size )
         return 0;
Signature · 1 line
2.39.5
Acked-by on v1 5/10
#18 lore raw

Re: [PATCH 05/10] x86/ucode: Fold microcode_grab_module() into its single caller

Quoted 29 lines · Andrew Cooper
xen/arch/x86/cpu/microcode/core.c +2 -14
@@ -205,19 +205,6 @@ static void __init microcode_scan_module(struct boot_info *bi)
     }
 }
 
-static void __init microcode_grab_module(struct boot_info *bi)
-{
-    if ( ucode_mod_idx < 0 )
-        ucode_mod_idx += bi->nr_modules;
-    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
-         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
-        goto scan;
-    ucode_mod = *bi->mods[ucode_mod_idx].mod;
-scan:
-    if ( ucode_scan )
-        microcode_scan_module(bi);
-}
-
 static struct microcode_ops __ro_after_init ucode_ops;
 
 static DEFINE_SPINLOCK(microcode_mutex);
@@ -831,7 +818,15 @@ static int __init early_microcode_load(struct boot_info *bi)
     size_t size;
     struct microcode_patch *patch;
 
-    microcode_grab_module(bi);
+    if ( ucode_mod_idx < 0 )
+        ucode_mod_idx += bi->nr_modules;

xen/arch/x86/cpu/microcode/core.c static int __init early_microcode_load(struct boot_info *bi) · line 832

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +7 -0
+    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
+         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
+        goto scan;
+    ucode_mod = *bi->mods[ucode_mod_idx].mod;
+ scan:
+    if ( ucode_scan )
+        microcode_scan_module(bi);
 
     if ( !ucode_mod.mod_end && !ucode_blob.size )
         return 0;

Could I talk you into doing away with the goto at the same time, by inverting the if()'s condition? Preferably with that:

Jan

Reviewed-by on v1 5/10
#19 lore raw

Re: [PATCH 05/10] x86/ucode: Fold microcode_grab_module() into its single caller

In reply to Andrew Cooper
Quoted 42 lines · Andrew Cooper

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
  xen/arch/x86/cpu/microcode/core.c | 23 +++++++++--------------
  1 file changed, 9 insertions(+), 14 deletions(-)
xen/arch/x86/cpu/microcode/core.c +2 -14
index 0b00e70f3b07..4c4003bf9687 100644
@@ -205,19 +205,6 @@ static void __init microcode_scan_module(struct boot_info *bi)
      }
  }
 
-static void __init microcode_grab_module(struct boot_info *bi)
-{
-    if ( ucode_mod_idx < 0 )
-        ucode_mod_idx += bi->nr_modules;
-    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
-         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
-        goto scan;
-    ucode_mod = *bi->mods[ucode_mod_idx].mod;
-scan:
-    if ( ucode_scan )
-        microcode_scan_module(bi);
-}
-
  static struct microcode_ops __ro_after_init ucode_ops;
 
  static DEFINE_SPINLOCK(microcode_mutex);
@@ -831,7 +818,15 @@ static int __init early_microcode_load(struct boot_info *bi)
      size_t size;
      struct microcode_patch *patch;
 
-    microcode_grab_module(bi);
+    if ( ucode_mod_idx < 0 )
+        ucode_mod_idx += bi->nr_modules;

xen/arch/x86/cpu/microcode/core.c static int __init early_microcode_load(struct boot_info *bi) · line 832

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +7 -0
+    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
+         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
+        goto scan;
+    ucode_mod = *bi->mods[ucode_mod_idx].mod;
+ scan:
+    if ( ucode_scan )
+        microcode_scan_module(bi);
 
      if ( !ucode_mod.mod_end && !ucode_blob.size )
          return 0;

Just a suggestion, but would it be useful to add a comment to explain the three conditions of ucode_mod_idx that are being handled before scanning is attempted? These being negative value, a valid module index, and module index wasn't already claimed in the module map.

Otherwise,

#20 lore raw

Re: [PATCH 05/10] x86/ucode: Fold microcode_grab_module() into its single caller

Quoted 13 lines · Daniel P. Smith
Quoted 12 lines · Andrew Cooper
xen/arch/x86/cpu/microcode/core.c +7 -0
@@ -831,7 +818,15 @@ static int __init early_microcode_load(struct
 boot_info *bi)
       size_t size;
       struct microcode_patch *patch;
   -    microcode_grab_module(bi);
+    if ( ucode_mod_idx < 0 )
+        ucode_mod_idx += bi->nr_modules;
+    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
+         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
+        goto scan;
+    ucode_mod = *bi->mods[ucode_mod_idx].mod;
+ scan:
Quoted 8 lines

xen/arch/x86/cpu/microcode/core.c static int __init early_microcode_load(struct boot_info *bi) · line 832

Quoted 4 lines
xen/arch/x86/cpu/microcode/core.c +2 -0
+    if ( ucode_scan )
+        microcode_scan_module(bi);
         if ( !ucode_mod.mod_end && !ucode_blob.size )
           return 0;

Just a suggestion, but would it be useful to add a comment to explain the three conditions of ucode_mod_idx that are being handled before scanning is attempted?

The already did that, but it's in the next patch, which also rearranges this block massively.

~Andrew

Reviewed-by
#21 lore raw

Re: [PATCH 05/10] x86/ucode: Fold microcode_grab_module() into its single caller

Quoted 23 lines · Andrew Cooper
Quoted 13 lines · Daniel P. Smith
Quoted 12 lines · Andrew Cooper
xen/arch/x86/cpu/microcode/core.c +7 -0
@@ -831,7 +818,15 @@ static int __init early_microcode_load(struct
 boot_info *bi)
       size_t size;
       struct microcode_patch *patch;
   -    microcode_grab_module(bi);
+    if ( ucode_mod_idx < 0 )
+        ucode_mod_idx += bi->nr_modules;
+    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
+         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
+        goto scan;
+    ucode_mod = *bi->mods[ucode_mod_idx].mod;
+ scan:
Quoted 8 lines

xen/arch/x86/cpu/microcode/core.c static int __init early_microcode_load(struct boot_info *bi) · line 832

Quoted 4 lines
xen/arch/x86/cpu/microcode/core.c +2 -0
+    if ( ucode_scan )
+        microcode_scan_module(bi);
         if ( !ucode_mod.mod_end && !ucode_blob.size )
           return 0;

Just a suggestion, but would it be useful to add a comment to explain the three conditions of ucode_mod_idx that are being handled before scanning is attempted?

Quoted 2 lines

The already did that, but it's in the next patch, which also rearranges this block massively.

I realized that and meant to come back to adjust my response. As such,

#22 lore raw

PATCH 6/10 x86/ucode: Enforce invariant about module selection

In reply to Andrew Cooper

The work to add the ucode=nmi cmdline option left a subtle corner case. Both scan and an explicit index could be selected, and we could really find a CPIO archive and explicit microcode file.

Worse, because the if/else chains for processing ucode_{blob,mod} are opposite ways around in early_microcode_load() and microcode_init_cache(), we can genuinely perform early microcode loading from the CPIO archive, then cache from the explicit file.

Therefore, enforce that only one selection method can be active.

Rename ucode_{scan,mod_idx} to have an opt_ prefix. This is both for consistency with the rest of Xen, and to guarantee that we've got all instances of the variables covered in this change. Explain how they're use. During cmdline/config parsing, always update both variables in pairs.

In early_microcode_load(), ASSERT() the invariant just in case. Use a local variable for idx rather than operating on the static; we're the only consume of the value.

Expand the index selection logic with comments and warnings to the user when something went wrong.

Fixes 5ed12565aa32 ("microcode: rendezvous CPUs in NMI handler and load ucode")

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

Despite the fixes tag, this can't be backported (at least not in this form).

---
 xen/arch/x86/cpu/microcode/core.c | 76 +++++++++++++++++++++++--------
 1 file changed, 57 insertions(+), 19 deletions(-)
xen/arch/x86/cpu/microcode/core.c +57 -19
index 4c4003bf9687..fc31ab35c3c8 100644
@@ -60,7 +60,6 @@
 #define MICROCODE_UPDATE_TIMEOUT_US 1000000
 
 static module_t __initdata ucode_mod;
-static signed int __initdata ucode_mod_idx;
 static bool __initdata ucode_mod_forced;
 static unsigned int nr_cores;
 
@@ -97,11 +96,6 @@ struct patch_with_flags {
 };
 
 static struct ucode_mod_blob __initdata ucode_blob;
-/*
- * By default we will NOT parse the multiboot modules to see if there is
- * cpio image with the microcode images.
- */
-static bool __initdata ucode_scan;
 
 /* By default, ucode loading is done in NMI handler */
 static bool ucode_in_nmi = true;
@@ -109,13 +103,28 @@ static bool ucode_in_nmi = true;
 /* Protected by microcode_mutex */
 static const struct microcode_patch *microcode_cache;
 
+/*
+ * opt_mod_idx and opt_scan have subtle semantics.
+ *
+ * The cmdline can either identify a module by number (inc -ve back-reference)
+ * containing a raw microcode container, or select scan which instructs Xen to
+ * search all modules for an uncompressed CPIO archive containing a file with
+ * a vendor-dependent name.
+ *
+ * These options do not make sense when combined, so for the benefit of module
+ * location we require that they are not both active together.
+ */
+static int __initdata opt_mod_idx;
+static bool __initdata opt_scan;
+
 /*
  * Used by the EFI path only, when xen.cfg identifies an explicit microcode
  * file.  Overrides ucode=<int>|scan on the regular command line.
  */
 void __init microcode_set_module(unsigned int idx)
 {
-    ucode_mod_idx = idx;
+    opt_mod_idx = idx;
+    opt_scan = false;
     ucode_mod_forced = 1;
 }
 
@@ -139,12 +148,16 @@ static int __init cf_check parse_ucode(const char *s)
         else if ( !ucode_mod_forced ) /* Not forced by EFI */
         {
             if ( (val = parse_boolean("scan", s, ss)) >= 0 )
-                ucode_scan = val;
+            {
+                opt_scan = val;
+                opt_mod_idx = 0;
+            }
             else
             {
                 const char *q;
 
-                ucode_mod_idx = simple_strtol(s, &q, 0);
+                opt_scan = false;
+                opt_mod_idx = simple_strtol(s, &q, 0);
                 if ( q != ss )
                     rc = -EINVAL;
             }
@@ -166,7 +179,7 @@ static void __init microcode_scan_module(struct boot_info *bi)
     int i;
 
     ucode_blob.size = 0;
-    if ( !ucode_scan )
+    if ( !opt_scan )
         return;
 
     if ( boot_cpu_data.x86_vendor == X86_VENDOR_AMD )
@@ -792,7 +805,7 @@ static int __init cf_check microcode_init_cache(void)
     if ( !ucode_ops.apply_microcode )
         return -ENODEV;
 
-    if ( ucode_scan )
+    if ( opt_scan )
         /* Need to rescan the modules because they might have been relocated */
         microcode_scan_module(bi);
 
@@ -817,17 +830,42 @@ static int __init early_microcode_load(struct boot_info *bi)
     const void *data = NULL;
     size_t size;
     struct microcode_patch *patch;
+    int idx = opt_mod_idx;
+
+    /*
+     * Cmdline parsing ensures this invariant holds, so that we don't end up
+     * trying to mix multiple ways of finding the microcode.
+     */
+    ASSERT(idx == 0 || !opt_scan);
 
-    if ( ucode_mod_idx < 0 )
-        ucode_mod_idx += bi->nr_modules;
-    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
-         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
-        goto scan;
-    ucode_mod = *bi->mods[ucode_mod_idx].mod;
- scan:
-    if ( ucode_scan )
+    if ( opt_scan ) /* Scan for a CPIO archive */
         microcode_scan_module(bi);
 
+    if ( idx ) /* Specific module nominated */
+    {
+        /*
+         * Negative indicies can be used to reference from the end of the
+         * modules.  e.g. ucode=-1 refers to the last module.
+         */
+        if ( idx < 0 )
+            idx += bi->nr_modules;
+
+        if ( idx <= 0 || idx >= bi->nr_modules )
+        {
+            printk(XENLOG_WARNING "Microcode: Chosen module %d out of range [1, %u)\n",
+                   idx, bi->nr_modules);
+            return -ENODEV;
+        }
+
+        if ( !__test_and_clear_bit(idx, bi->module_map) )
+        {
+            printk(XENLOG_WARNING "Microcode: Chosen module %d already used\n", idx);
+            return -ENODEV;
+        }
+
+        ucode_mod = *bi->mods[idx].mod;
+    }
+
     if ( !ucode_mod.mod_end && !ucode_blob.size )
         return 0;
 
Signature · 1 line
2.39.5
#23 lore raw

Re: [PATCH 06/10] x86/ucode: Enforce invariant about module selection

Quoted 10 lines · Andrew Cooper

The work to add the ucode=nmi cmdline option left a subtle corner case. Both scan and an explicit index could be selected, and we could really find a CPIO archive and explicit microcode file.

Worse, because the if/else chains for processing ucode_{blob,mod} are opposite ways around in early_microcode_load() and microcode_init_cache(), we can genuinely perform early microcode loading from the CPIO archive, then cache from the explicit file.

Therefore, enforce that only one selection method can be active.

Question is - is this really the best of all possible behaviors? One may want to use one approach as the fallback for the other, e.g. preferably use what the CPIO has, but fall back to something pre-installed on the boot or EFI partition.

Quoted 9 lines
xen/arch/x86/cpu/microcode/core.c +4 -1
@@ -139,12 +148,16 @@ static int __init cf_check parse_ucode(const char *s)
         else if ( !ucode_mod_forced ) /* Not forced by EFI */
         {
             if ( (val = parse_boolean("scan", s, ss)) >= 0 )
-                ucode_scan = val;
+            {
+                opt_scan = val;
+                opt_mod_idx = 0;
+            }

xen/arch/x86/cpu/microcode/core.c static int __init cf_check parse_ucode(const char *s) · line 163

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +2 -1
             else
             {
                 const char *q;
 
-                ucode_mod_idx = simple_strtol(s, &q, 0);
+                opt_scan = false;
+                opt_mod_idx = simple_strtol(s, &q, 0);
                 if ( q != ss )
                     rc = -EINVAL;
             }

I think this latter part rather wants to be

                opt_mod_idx = simple_strtol(s, &q, 0);
                if ( q != ss )
                {
                    opt_mod_idx = 0;
                    rc = -EINVAL;
                }
                else
                    opt_scan = false;

to prevent a malformed ucode= to clobber an earlier wellformed ucode=scan. (There are limits to this of course, as an out-of-range value would still invalidate the "scan" request.)

Quoted 9 lines
xen/arch/x86/cpu/microcode/core.c +5 -0
@@ -817,17 +830,42 @@ static int __init early_microcode_load(struct boot_info *bi)
     const void *data = NULL;
     size_t size;
     struct microcode_patch *patch;
+    int idx = opt_mod_idx;
+
+    /*
+     * Cmdline parsing ensures this invariant holds, so that we don't end up
+     * trying to mix multiple ways of finding the microcode.

xen/arch/x86/cpu/microcode/core.c static int __init early_microcode_load(struct boot_info *bi) · line 827

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +2 -7
+     */
+    ASSERT(idx == 0 || !opt_scan);
 
-    if ( ucode_mod_idx < 0 )
-        ucode_mod_idx += bi->nr_modules;
-    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
-         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
-        goto scan;
-    ucode_mod = *bi->mods[ucode_mod_idx].mod;
- scan:

Oh, the goto and label are going away here anyway. Never mind the comment on the earlier patch then.

Jan

#24 lore raw

Re: [PATCH 06/10] x86/ucode: Enforce invariant about module selection

Quoted 10 lines · Jan Beulich
Quoted 9 lines · Andrew Cooper

The work to add the ucode=nmi cmdline option left a subtle corner case. Both scan and an explicit index could be selected, and we could really find a CPIO archive and explicit microcode file.

Worse, because the if/else chains for processing ucode_{blob,mod} are opposite ways around in early_microcode_load() and microcode_init_cache(), we can genuinely perform early microcode loading from the CPIO archive, then cache from the explicit file.

Quoted 5 lines
Quoted 1 line

Therefore, enforce that only one selection method can be active.

Question is - is this really the best of all possible behaviors? One may want to use one approach as the fallback for the other, e.g. preferably use what the CPIO has, but fall back to something pre-installed on the boot or EFI partition.

It is unfortunate behaviour.

I've seen explicit complains about it on the archlinux forums; putting a CPIO fragment in EFI's ucode= argument and getting confused as to why it doesn't work.

However, it is (reasonably) necessary to dis-enagle this path, and we currently document it as "undefined behaviour".

I think that we should re-evaluate the behaviour, after the rest of the boot cleanup is done and we have an easier time reasoning about what is what.

Quoted 30 lines
Quoted 9 lines
xen/arch/x86/cpu/microcode/core.c +4 -1
@@ -139,12 +148,16 @@ static int __init cf_check parse_ucode(const char *s)
         else if ( !ucode_mod_forced ) /* Not forced by EFI */
         {
             if ( (val = parse_boolean("scan", s, ss)) >= 0 )
-                ucode_scan = val;
+            {
+                opt_scan = val;
+                opt_mod_idx = 0;
+            }

xen/arch/x86/cpu/microcode/core.c static int __init cf_check parse_ucode(const char *s) · line 163

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +2 -1
             else
             {
                 const char *q;
 
-                ucode_mod_idx = simple_strtol(s, &q, 0);
+                opt_scan = false;
+                opt_mod_idx = simple_strtol(s, &q, 0);
                 if ( q != ss )
                     rc = -EINVAL;
             }

I think this latter part rather wants to be

                opt_mod_idx = simple_strtol(s, &q, 0);
                if ( q != ss )
                {
                    opt_mod_idx = 0;
                    rc = -EINVAL;
                }
                else
                    opt_scan = false;
Quoted 3 lines

to prevent a malformed ucode= to clobber an earlier wellformed ucode=scan. (There are limits to this of course, as an out-of-range value would still invalidate the "scan" request.)

Fine.  I'm not overly fussed.  We don't make any pretence that erroneous cmdline settings are handled nicely.

Quoted 13 lines
Quoted 13 lines
xen/arch/x86/cpu/microcode/core.c +7 -0
@@ -817,17 +830,42 @@ static int __init early_microcode_load(struct boot_info *bi)
     const void *data = NULL;
     size_t size;
     struct microcode_patch *patch;
+    int idx = opt_mod_idx;
+
+    /*
+     * Cmdline parsing ensures this invariant holds, so that we don't end up
+     * trying to mix multiple ways of finding the microcode.
+     */
+    ASSERT(idx == 0 || !opt_scan);
 
Quoted 9 lines

xen/arch/x86/cpu/microcode/core.c static int __init early_microcode_load(struct boot_info *bi) · line 827

Quoted 7 lines
xen/arch/x86/cpu/microcode/core.c +0 -7
-    if ( ucode_mod_idx < 0 )
-        ucode_mod_idx += bi->nr_modules;
-    if ( ucode_mod_idx <= 0 || ucode_mod_idx >= bi->nr_modules ||
-         !__test_and_clear_bit(ucode_mod_idx, bi->module_map) )
-        goto scan;
-    ucode_mod = *bi->mods[ucode_mod_idx].mod;
- scan:

Oh, the goto and label are going away here anyway. Never mind the comment on the earlier patch then.

Thanks, and yes.

I did play with the order quite a lot.  The first iteration did clean this up as part of merging into early_microcode_load(), but it turned into a mess.

This way around (straight fold in the previous patch, rework here given the invariant) was the cleanest I came up with.

~Andrew

Reviewed-by on v1 6/10
#25 lore raw

Re: [PATCH 06/10] x86/ucode: Enforce invariant about module selection

In reply to Andrew Cooper
Quoted 23 lines · Andrew Cooper

The work to add the ucode=nmi cmdline option left a subtle corner case. Both scan and an explicit index could be selected, and we could really find a CPIO archive and explicit microcode file.

Worse, because the if/else chains for processing ucode_{blob,mod} are opposite ways around in early_microcode_load() and microcode_init_cache(), we can genuinely perform early microcode loading from the CPIO archive, then cache from the explicit file.

Therefore, enforce that only one selection method can be active.

Rename ucode_{scan,mod_idx} to have an opt_ prefix. This is both for consistency with the rest of Xen, and to guarantee that we've got all instances of the variables covered in this change. Explain how they're use. During cmdline/config parsing, always update both variables in pairs.

In early_microcode_load(), ASSERT() the invariant just in case. Use a local variable for idx rather than operating on the static; we're the only consume of the value.

Expand the index selection logic with comments and warnings to the user when something went wrong.

Quoted 8 lines
Fixes 5ed12565aa32 ("microcode: rendezvous CPUs in NMI handler and load ucode")

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

Despite the fixes tag, this can't be backported (at least not in this form).

This provides a much more consistent/predictable behavior.

#26 lore raw

PATCH 7/10 x86/ucode: Move the CPIO path string into microcode_ops

In reply to Andrew Cooper

We've got a perfectly good vendor abstraction already for microcode. No need for a second ad-hoc one in microcode_scan_module().

This is in preparation to use ucode_ops.cpio_path in multiple places.

These paths are only used during __init, so take the opportunity to move them into __initconst.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
 xen/arch/x86/cpu/microcode/amd.c     |  4 ++++
 xen/arch/x86/cpu/microcode/core.c    | 14 +++-----------
 xen/arch/x86/cpu/microcode/intel.c   |  4 ++++
 xen/arch/x86/cpu/microcode/private.h |  7 +++++++
 4 files changed, 18 insertions(+), 11 deletions(-)
xen/arch/x86/cpu/microcode/amd.c +4 -0
index 0fe869eff119..c7a779c1d885 100644
@@ -443,11 +443,15 @@ static struct microcode_patch *cf_check cpu_request_microcode(
     return patch;
 }
 
+static const char __initconst amd_cpio_path[] =
+    "kernel/x86/microcode/AuthenticAMD.bin";
+
 static const struct microcode_ops __initconst_cf_clobber amd_ucode_ops = {
     .cpu_request_microcode            = cpu_request_microcode,
     .collect_cpu_info                 = collect_cpu_info,
     .apply_microcode                  = apply_microcode,
     .compare_patch                    = compare_patch,
+    .cpio_path                        = amd_cpio_path,
 };
 
 void __init ucode_probe_amd(struct microcode_ops *ops)
xen/arch/x86/cpu/microcode/core.c +3 -11
index fc31ab35c3c8..6a87390ab770 100644
@@ -170,25 +170,19 @@ static int __init cf_check parse_ucode(const char *s)
 }
 custom_param("ucode", parse_ucode);
 
+static struct microcode_ops __ro_after_init ucode_ops;
+
 static void __init microcode_scan_module(struct boot_info *bi)
 {
     uint64_t *_blob_start;
     unsigned long _blob_size;
     struct cpio_data cd;
-    const char *p = NULL;
     int i;
 
     ucode_blob.size = 0;
     if ( !opt_scan )
         return;
 
-    if ( boot_cpu_data.x86_vendor == X86_VENDOR_AMD )
-        p = "kernel/x86/microcode/AuthenticAMD.bin";
-    else if ( boot_cpu_data.x86_vendor == X86_VENDOR_INTEL )
-        p = "kernel/x86/microcode/GenuineIntel.bin";
-    else
-        return;
-
     /*
      * Try all modules and see whichever could be the microcode blob.
      */
@@ -207,7 +201,7 @@ static void __init microcode_scan_module(struct boot_info *bi)
         }
         cd.data = NULL;
         cd.size = 0;
-        cd = find_cpio_data(p, _blob_start, _blob_size);
+        cd = find_cpio_data(ucode_ops.cpio_path, _blob_start, _blob_size);
         if ( cd.data )
         {
             ucode_blob.size = cd.size;
@@ -218,8 +212,6 @@ static void __init microcode_scan_module(struct boot_info *bi)
     }
 }
 
-static struct microcode_ops __ro_after_init ucode_ops;
-
 static DEFINE_SPINLOCK(microcode_mutex);
 
 DEFINE_PER_CPU(struct cpu_signature, cpu_sig);
xen/arch/x86/cpu/microcode/intel.c +4 -0
index bad51f64724a..aad6a693e800 100644
@@ -405,11 +405,15 @@ static bool __init can_load_microcode(void)
     return !(mcu_ctrl & MCU_CONTROL_DIS_MCU_LOAD);
 }
 
+static const char __initconst intel_cpio_path[] =
+    "kernel/x86/microcode/GenuineIntel.bin";
+
 static const struct microcode_ops __initconst_cf_clobber intel_ucode_ops = {
     .cpu_request_microcode            = cpu_request_microcode,
     .collect_cpu_info                 = collect_cpu_info,
     .apply_microcode                  = apply_microcode,
     .compare_patch                    = compare_patch,
+    .cpio_path                        = intel_cpio_path,
 };
 
 void __init ucode_probe_intel(struct microcode_ops *ops)
xen/arch/x86/cpu/microcode/private.h +7 -0
index c72f060ac394..c9dd8ba066f9 100644
@@ -59,6 +59,13 @@ struct microcode_ops {
      */
     enum microcode_match_result (*compare_patch)(
         const struct microcode_patch *new, const struct microcode_patch *old);
+
+    /*
+     * For Linux inird microcode compatibliity.
+     *
+     * The path where this vendor's microcode can be found in CPIO.
+     */
+    const char *cpio_path;
 };
 
 /*
Signature · 1 line
2.39.5
Acked-by on v1 7/10
#27 lore raw

Re: [PATCH 07/10] x86/ucode: Move the CPIO path string into microcode_ops

Quoted 7 lines · Andrew Cooper

We've got a perfectly good vendor abstraction already for microcode. No need for a second ad-hoc one in microcode_scan_module().

This is in preparation to use ucode_ops.cpio_path in multiple places.

These paths are only used during __init, so take the opportunity to move them into __initconst.

As an alternative to this, how about ...

xen/arch/x86/cpu/microcode/private.h struct microcode_ops { · line 68

Quoted 13 lines
xen/arch/x86/cpu/microcode/private.h +7 -0
@@ -59,6 +59,13 @@ struct microcode_ops {
      */
     enum microcode_match_result (*compare_patch)(
         const struct microcode_patch *new, const struct microcode_patch *old);
+
+    /*
+     * For Linux inird microcode compatibliity.
+     *
+     * The path where this vendor's microcode can be found in CPIO.
+     */
+    const char *cpio_path;
    const char cpio_path[];

inheriting the __initconst from the struct instances?

with a slight preference to the form without the extra pointer. Except that:
gcc14 looks to be buggy when it comes to the copying of such a struct. The example below yields an internal compiler error. And the direct structure assignment also doesn't quite do what I would expect it to do (visible when commenting out the "else" branch. Bottom line - leave the code as is.

Jan

struct s {
	unsigned long ul;
	int i;
	char ac[];
};

const struct s gs = { 3, -4, "abcdef" };

void copy_s(struct s*d, const struct s*s) {
	*d = *s;
}
unsigned test(struct s*ps, _Bool direct) {
	if(direct)
		*ps = gs;
	else
		copy_s(ps, &gs);
	return sizeof(*ps);
}
unsigned size(void) {
	return sizeof(gs);
}
#28 lore raw

Re: [PATCH 07/10] x86/ucode: Move the CPIO path string into microcode_ops

Quoted 25 lines · Jan Beulich
Quoted 7 lines · Andrew Cooper

We've got a perfectly good vendor abstraction already for microcode. No need for a second ad-hoc one in microcode_scan_module().

This is in preparation to use ucode_ops.cpio_path in multiple places.

These paths are only used during __init, so take the opportunity to move them into __initconst.

As an alternative to this, how about ...

xen/arch/x86/cpu/microcode/private.h struct microcode_ops { · line 68

Quoted 13 lines
xen/arch/x86/cpu/microcode/private.h +7 -0
@@ -59,6 +59,13 @@ struct microcode_ops {
      */
     enum microcode_match_result (*compare_patch)(
         const struct microcode_patch *new, const struct microcode_patch *old);
+
+    /*
+     * For Linux inird microcode compatibliity.
+     *
+     * The path where this vendor's microcode can be found in CPIO.
+     */
+    const char *cpio_path;
    const char cpio_path[];
Quoted 3 lines

inheriting the __initconst from the struct instances?

with a slight preference to the form without the extra pointer.

I'm slightly surprised at this request, given that the form with the pointer results in less data held at runtime.

Quoted 5 lines

Except that:
gcc14 looks to be buggy when it comes to the copying of such a struct. The example below yields an internal compiler error. And the direct structure assignment also doesn't quite do what I would expect it to do (visible when commenting out the "else" branch. Bottom line - leave the code as is.

It's unfortunate to hit an ICE, but the copy cannot possibly work in the first place.

ucode_ops is in a separate translation unit and has no space allocated after the flexible member.   Any copy into it is memory corruption of whatever object happens to be sequentially after ucode_ops.

The only way it would work is having const char cpio_path[40]; which is long enough for anything we'd expect to find.

But again, that involves holding init-only data post init.

~Andrew

#29 lore raw

Re: [PATCH 07/10] x86/ucode: Move the CPIO path string into microcode_ops

Quoted 26 lines · Andrew Cooper
Quoted 25 lines · Jan Beulich
Quoted 7 lines · Andrew Cooper

We've got a perfectly good vendor abstraction already for microcode. No need for a second ad-hoc one in microcode_scan_module().

This is in preparation to use ucode_ops.cpio_path in multiple places.

These paths are only used during __init, so take the opportunity to move them into __initconst.

As an alternative to this, how about ...

xen/arch/x86/cpu/microcode/private.h struct microcode_ops { · line 68

Quoted 13 lines
xen/arch/x86/cpu/microcode/private.h +7 -0
@@ -59,6 +59,13 @@ struct microcode_ops {
      */
     enum microcode_match_result (*compare_patch)(
         const struct microcode_patch *new, const struct microcode_patch *old);
+
+    /*
+     * For Linux inird microcode compatibliity.
+     *
+     * The path where this vendor's microcode can be found in CPIO.
+     */
+    const char *cpio_path;
    const char cpio_path[];
Quoted 6 lines
Quoted 3 lines

inheriting the __initconst from the struct instances?

with a slight preference to the form without the extra pointer.

I'm slightly surprised at this request, given that the form with the pointer results in less data held at runtime.

No, it doesn't. Yet I only now realize that ...

Quoted 6 lines
Quoted 5 lines

Except that:
gcc14 looks to be buggy when it comes to the copying of such a struct. The example below yields an internal compiler error. And the direct structure assignment also doesn't quite do what I would expect it to do (visible when commenting out the "else" branch. Bottom line - leave the code as is.

Quoted 6 lines

It's unfortunate to hit an ICE, but the copy cannot possibly work in the first place.

ucode_ops is in a separate translation unit and has no space allocated after the flexible member.   Any copy into it is memory corruption of whatever object happens to be sequentially after ucode_ops.

... my expectation of how the copy ought to work (and how the C standard, at least in close enough an example, specifies it) would specifically _not_ suit our needs. The copy ought to only cover sizeof(struct ...), i.e. not the string. Yet we'd need that string to be copied to be usable for our purposes.

Quoted 4 lines

The only way it would work is having const char cpio_path[40]; which is long enough for anything we'd expect to find.

But again, that involves holding init-only data post init.

This, indeed, would increase post-init size. Yet with the compiler issue no question arises anyway as to how this needs doing.

Jan

Reviewed-by on v1 7/10
#30 lore raw

Re: [PATCH 07/10] x86/ucode: Move the CPIO path string into microcode_ops

In reply to Andrew Cooper
Quoted 8 lines · Andrew Cooper

We've got a perfectly good vendor abstraction already for microcode. No need for a second ad-hoc one in microcode_scan_module().

This is in preparation to use ucode_ops.cpio_path in multiple places.

These paths are only used during __init, so take the opportunity to move them into __initconst.

Quoted 6 lines

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>
---

#31 lore raw

PATCH 8/10 x86/ucode: Use bootstrap_unmap() in early_microcode_load()

In reply to Andrew Cooper

If bootstrap_map() has provided a mapping, we must free it when done. Failing to do so may cause a spurious failure for unrelated logic later.

Inserting a bootstrap_unmap() here does not break the use of ucode_{blob,mod} any more than they already are.

Add a printk noting when we didn't find a microcode patch. It's at debug level, because this is the expected case on AMD Client systems, and SDPs, but for people trying to figure out why microcode loading isn't work, it might be helpful.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)
xen/arch/x86/cpu/microcode/core.c +15 -5
index 6a87390ab770..28cfeab75a81 100644
@@ -823,6 +823,7 @@ static int __init early_microcode_load(struct boot_info *bi)
     size_t size;
     struct microcode_patch *patch;
     int idx = opt_mod_idx;
+    int rc = 0;
 
     /*
      * Cmdline parsing ensures this invariant holds, so that we don't end up
@@ -878,15 +879,24 @@ static int __init early_microcode_load(struct boot_info *bi)
     patch = ucode_ops.cpu_request_microcode(data, size, false);
     if ( IS_ERR(patch) )
     {
-        printk(XENLOG_WARNING "Parsing microcode blob error %ld\n",
-               PTR_ERR(patch));
-        return PTR_ERR(patch);
+        rc = PTR_ERR(patch);
+        printk(XENLOG_WARNING "Microcode: Parse error %d\n", rc);
+        goto unmap;
     }
 
     if ( !patch )
-        return -ENOENT;
+    {
+        printk(XENLOG_DEBUG "Microcode: No suitable patch found\n");
+        rc = -ENOENT;
+        goto unmap;
+    }
+
+    rc = microcode_update_cpu(patch, 0);
 
-    return microcode_update_cpu(patch, 0);
+ unmap:
+    bootstrap_unmap();
+
+    return rc;
 }
 
 int __init early_microcode_init(struct boot_info *bi)
Signature · 1 line
2.39.5
Acked-by on v1 8/10
#32 lore raw

Re: [PATCH 08/10] x86/ucode: Use bootstrap_unmap() in early_microcode_load()

Quoted 6 lines · Andrew Cooper

If bootstrap_map() has provided a mapping, we must free it when done. Failing to do so may cause a spurious failure for unrelated logic later.

Inserting a bootstrap_unmap() here does not break the use of ucode_{blob,mod} any more than they already are.

Quoted 6 lines

Add a printk noting when we didn't find a microcode patch. It's at debug level, because this is the expected case on AMD Client systems, and SDPs, but for people trying to figure out why microcode loading isn't work, it might be helpful.

Hmm, yes, I think this is correct now (but the mapping had to persist earlier on, likely years ago). So

However, as a nit, ...

xen/arch/x86/cpu/microcode/core.c static int __init early_microcode_load(struct boot_info *bi) · line 826

Quoted 7 lines
xen/arch/x86/cpu/microcode/core.c +1 -0
@@ -823,6 +823,7 @@ static int __init early_microcode_load(struct boot_info *bi)
     size_t size;
     struct microcode_patch *patch;
     int idx = opt_mod_idx;
+    int rc = 0;

... the initializer doesn't appear to be needed here; all paths ...

Quoted 18 lines
xen/arch/x86/cpu/microcode/core.c +7 -4
@@ -878,15 +879,24 @@ static int __init early_microcode_load(struct boot_info *bi)
     patch = ucode_ops.cpu_request_microcode(data, size, false);
     if ( IS_ERR(patch) )
     {
-        printk(XENLOG_WARNING "Parsing microcode blob error %ld\n",
-               PTR_ERR(patch));
-        return PTR_ERR(patch);
+        rc = PTR_ERR(patch);
+        printk(XENLOG_WARNING "Microcode: Parse error %d\n", rc);
+        goto unmap;
     }
 
     if ( !patch )
-        return -ENOENT;
+    {
+        printk(XENLOG_DEBUG "Microcode: No suitable patch found\n");
+        rc = -ENOENT;
+        goto unmap;

xen/arch/x86/cpu/microcode/core.c static int __init early_microcode_load(struct boot_info *bi) · line 900

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +7 -1
+    }
+
+    rc = microcode_update_cpu(patch, 0);
 
-    return microcode_update_cpu(patch, 0);
+ unmap:
+    bootstrap_unmap();
+
+    return rc;
 }

... reliably set the variable. (I don't recall what our conclusion was as to Misra possibly considering such unnecessary initializers dead code.)

Jan

Reviewed-by on v1 8/10
#33 lore raw

Re: [PATCH 08/10] x86/ucode: Use bootstrap_unmap() in early_microcode_load()

In reply to Andrew Cooper
Quoted 11 lines · Andrew Cooper

If bootstrap_map() has provided a mapping, we must free it when done. Failing to do so may cause a spurious failure for unrelated logic later.

Inserting a bootstrap_unmap() here does not break the use of ucode_{blob,mod} any more than they already are.

Add a printk noting when we didn't find a microcode patch. It's at debug level, because this is the expected case on AMD Client systems, and SDPs, but for people trying to figure out why microcode loading isn't work, it might be helpful.

Quoted 6 lines

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>
---

#34 lore raw

PATCH 9/10 x86/ucode: Drop ucode_mod and ucode_blob

In reply to Andrew Cooper

Both are used to pass information from early_microcode_load() to microcode_init_cache(), and both constitute use-after-free's in certain cases.

* ucode_mod is a copy of the module_t identified by ucode=$n. Except it's a copy from prior to Xen relocating the modules. microcode_init_cache() might happen to find the data still intact in it's old location, but it might be an arbitrary part of some other module.

* ucode_blob is a stashed pointer to a bootstrap_map() which becomes invalid the moment control returns to __start_xen(), where other logic is free to to make temporary mappings. This was even noticed and microcode_init_cache() adjusted to "fix" the stashed pointers.

The information which should be passed between these two functions is which module to look in. Introduce early_mod_idx for this purpose. opt_scan can be reused to distinguish between CPIO archives and raw containers.

Notably this means microcode_init_cache() doesn't need to scan all modules any more; we know exactly which one to look in. However, we do re-parse the CPIO header for simplicity.

Furthermore, microcode_init_cache(), being a presmp_initcall does not need to use bootstrap_map() to access modules; it can use mfn_to_virt() directly, which avoids needing to funnel exit paths through bootstrap_unmap().

Fold microcode_scan_module() into what is now it's single caller. It operates on the function-wide idx/data/size state which allows for a unified "found" path irrespective of module selection method.

This resolves all issues to do with holding pointers (physical or virtual) across returning to __start_xen().

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c | 172 ++++++++++++++++--------------
 1 file changed, 89 insertions(+), 83 deletions(-)
xen/arch/x86/cpu/microcode/core.c +89 -83
index 28cfeab75a81..591c13ad91fb 100644
@@ -28,7 +28,6 @@
 #include <xen/err.h>
 #include <xen/guest_access.h>
 #include <xen/init.h>
-#include <xen/multiboot.h>
 #include <xen/param.h>
 #include <xen/spinlock.h>
 #include <xen/stop_machine.h>
@@ -59,7 +58,6 @@
  */
 #define MICROCODE_UPDATE_TIMEOUT_US 1000000
 
-static module_t __initdata ucode_mod;
 static bool __initdata ucode_mod_forced;
 static unsigned int nr_cores;
 
@@ -79,24 +77,11 @@ static enum {
     LOADING_EXIT,
 } loading_state;
 
-/*
- * If we scan the initramfs.cpio for the early microcode code
- * and find it, then 'ucode_blob' will contain the pointer
- * and the size of said blob. It is allocated from Xen's heap
- * memory.
- */
-struct ucode_mod_blob {
-    const void *data;
-    size_t size;
-};
-
 struct patch_with_flags {
     unsigned int flags;
     const struct microcode_patch *patch;
 };
 
-static struct ucode_mod_blob __initdata ucode_blob;
-
 /* By default, ucode loading is done in NMI handler */
 static bool ucode_in_nmi = true;
 
@@ -172,46 +157,6 @@ custom_param("ucode", parse_ucode);
 
 static struct microcode_ops __ro_after_init ucode_ops;
 
-static void __init microcode_scan_module(struct boot_info *bi)
-{
-    uint64_t *_blob_start;
-    unsigned long _blob_size;
-    struct cpio_data cd;
-    int i;
-
-    ucode_blob.size = 0;
-    if ( !opt_scan )
-        return;
-
-    /*
-     * Try all modules and see whichever could be the microcode blob.
-     */
-    for ( i = 1 /* Ignore dom0 kernel */; i < bi->nr_modules; i++ )
-    {
-        if ( !test_bit(i, bi->module_map) )
-            continue;
-
-        _blob_start = bootstrap_map(bi->mods[i].mod);
-        _blob_size = bi->mods[i].mod->mod_end;
-        if ( !_blob_start )
-        {
-            printk("Could not map multiboot module #%d (size: %ld)\n",
-                   i, _blob_size);
-            continue;
-        }
-        cd.data = NULL;
-        cd.size = 0;
-        cd = find_cpio_data(ucode_ops.cpio_path, _blob_start, _blob_size);
-        if ( cd.data )
-        {
-            ucode_blob.size = cd.size;
-            ucode_blob.data = cd.data;
-            break;
-        }
-        bootstrap_unmap();
-    }
-}
-
 static DEFINE_SPINLOCK(microcode_mutex);
 
 DEFINE_PER_CPU(struct cpu_signature, cpu_sig);
@@ -789,23 +734,47 @@ static int __init early_update_cache(const void *data, size_t len)
     return rc;
 }
 
+/*
+ * Set by early_microcode_load() to indicate where it found microcode, so
+ * microcode_init_cache() can find it again and initalise the cache.  opt_scan
+ * tells us whether we're looking for a raw container or CPIO archive.
+ */
+static int __initdata early_mod_idx = -1;
+
 static int __init cf_check microcode_init_cache(void)
 {
     struct boot_info *bi = &xen_boot_info;
+    void *data;
+    size_t size;
     int rc = 0;
 
-    if ( !ucode_ops.apply_microcode )
-        return -ENODEV;
+    if ( early_mod_idx < 0 )
+        /* early_microcode_load() didn't leave us any work to do. */
+        return 0;
+
+    size = bi->mods[early_mod_idx].mod->mod_end;
+    data = __mfn_to_virt(bi->mods[early_mod_idx].mod->mod_start);
 
+    /*
+     * If opt_scan is set, we're looking for a CPIO archive rather than a raw
+     * microcode container.  Look within it.
+     */
     if ( opt_scan )
-        /* Need to rescan the modules because they might have been relocated */
-        microcode_scan_module(bi);
+    {
+        struct cpio_data cd = find_cpio_data(ucode_ops.cpio_path, data, size);
 
-    if ( ucode_mod.mod_end )
-        rc = early_update_cache(bootstrap_map(&ucode_mod),
-                                ucode_mod.mod_end);
-    else if ( ucode_blob.size )
-        rc = early_update_cache(ucode_blob.data, ucode_blob.size);
+        if ( !cd.data )
+        {
+            printk(XENLOG_WARNING "Microcode: %s not found in CPIO archive\n",
+                   strrchr(ucode_ops.cpio_path, '/') + 1);
+            return -ENOENT;
+        }
+
+        data = cd.data;
+        size = cd.size;
+    }
+
+    rc = early_update_cache(data, size);
 
     return rc;
 }
@@ -819,7 +788,7 @@ presmp_initcall(microcode_init_cache);
  */
 static int __init early_microcode_load(struct boot_info *bi)
 {
-    const void *data = NULL;
+    void *data = NULL;
     size_t size;
     struct microcode_patch *patch;
     int idx = opt_mod_idx;
@@ -832,7 +801,40 @@ static int __init early_microcode_load(struct boot_info *bi)
     ASSERT(idx == 0 || !opt_scan);
 
     if ( opt_scan ) /* Scan for a CPIO archive */
-        microcode_scan_module(bi);
+    {
+        for ( idx = 1; idx < bi->nr_modules; ++idx )
+        {
+            struct cpio_data cd;
+
+            if ( !test_bit(idx, bi->module_map) )
+                continue;
+
+            size = bi->mods[idx].mod->mod_end;
+            data = bootstrap_map_bm(&bi->mods[idx]);
+            if ( !data )
+            {
+                printk(XENLOG_WARNING "Microcode: Could not map module %d, size %zu\n",
+                       idx, size);
+                continue;
+            }
+
+            cd = find_cpio_data(ucode_ops.cpio_path, data, size);
+            if ( !cd.data )
+            {
+                /* CPIO archive, but no cpio_path.  Try the next module */
+                bootstrap_unmap();
+                continue;
+            }
+
+            data = cd.data;
+            size = cd.size;
+            goto found;
+        }
+
+        printk(XENLOG_WARNING "Microcode: %s not found during CPIO scan\n",
+               strrchr(ucode_ops.cpio_path, '/') + 1);
+        return -ENODEV;
+    }
 
     if ( idx ) /* Specific module nominated */
     {
@@ -856,26 +858,21 @@ static int __init early_microcode_load(struct boot_info *bi)
             return -ENODEV;
         }
 
-        ucode_mod = *bi->mods[idx].mod;
-    }
-
-    if ( !ucode_mod.mod_end && !ucode_blob.size )
-        return 0;
-
-    if ( ucode_blob.size )
-    {
-        size = ucode_blob.size;
-        data = ucode_blob.data;
-    }
-    else if ( ucode_mod.mod_end )
-    {
-        size = ucode_mod.mod_end;
-        data = bootstrap_map(&ucode_mod);
+        size = bi->mods[idx].mod->mod_end;
+        data = bootstrap_map_bm(&bi->mods[idx]);
+        if ( !data )
+        {
+            printk(XENLOG_WARNING "Microcode: Could not map module %d, size %zu\n",
+                   idx, size);
+            return -ENODEV;
+        }
+        goto found;
     }
 
-    if ( !data )
-        return -ENOMEM;
+    /* No method of finding microcode specified.  Nothing to do. */
+    return 0;
 
+ found:
     patch = ucode_ops.cpu_request_microcode(data, size, false);
     if ( IS_ERR(patch) )
     {
@@ -891,6 +888,15 @@ static int __init early_microcode_load(struct boot_info *bi)
         goto unmap;
     }
 
+    /*
+     * We've found a microcode patch suitable for this CPU.
+     *
+     * Tell microcode_init_cache() which module we found it in.  We cache it
+     * irrespective of whether the BSP successfully loads it; Some platforms
+     * are known to update the BSP but leave the APs on older ucode.
+     */
+    early_mod_idx = idx;
+
     rc = microcode_update_cpu(patch, 0);
 
  unmap:
Signature · 1 line
2.39.5
Acked-by on v1 9/10
#35 lore raw

Re: [PATCH 09/10] x86/ucode: Drop ucode_mod and ucode_blob

Quoted 5 lines · Andrew Cooper
xen/arch/x86/cpu/microcode/core.c +1 -0
@@ -789,23 +734,47 @@ static int __init early_update_cache(const void *data, size_t len)
     return rc;
 }
 
+/*

xen/arch/x86/cpu/microcode/core.c static int __init early_update_cache(const void *data, size_t len) · line 747

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +7 -0
+ * Set by early_microcode_load() to indicate where it found microcode, so
+ * microcode_init_cache() can find it again and initalise the cache.  opt_scan
+ * tells us whether we're looking for a raw container or CPIO archive.
+ */
+static int __initdata early_mod_idx = -1;
+
 static int __init cf_check microcode_init_cache(void)
 {
     struct boot_info *bi = &xen_boot_info;
+    void *data;

Afaics the sole reason this isn't const void * and ...

xen/arch/x86/cpu/microcode/core.c presmp_initcall(microcode_init_cache); · line 791

Quoted 6 lines
xen/arch/x86/cpu/microcode/core.c +1 -1
@@ -819,7 +788,7 @@ presmp_initcall(microcode_init_cache);
  */
 static int __init early_microcode_load(struct boot_info *bi)
 {
-    const void *data = NULL;
+    void *data = NULL;

... you're actively dropping const here (which I consider bad) is find_cpio_data() wrongly taking void * as 2nd parameter. Internally it copies the parameter to a const char * variable, so the non-const param is bogus. With the const here retained and const added further up (on top of a trivial prereq patch adjusting find_cpio_data(), which I've just sent out):

Jan

#36 lore raw

Re: [PATCH 09/10] x86/ucode: Drop ucode_mod and ucode_blob

Quoted 18 lines · Jan Beulich
Quoted 5 lines · Andrew Cooper
xen/arch/x86/cpu/microcode/core.c +1 -0
@@ -789,23 +734,47 @@ static int __init early_update_cache(const void *data, size_t len)
     return rc;
 }
 
+/*

xen/arch/x86/cpu/microcode/core.c static int __init early_update_cache(const void *data, size_t len) · line 747

Quoted 10 lines
xen/arch/x86/cpu/microcode/core.c +7 -0
+ * Set by early_microcode_load() to indicate where it found microcode, so
+ * microcode_init_cache() can find it again and initalise the cache.  opt_scan
+ * tells us whether we're looking for a raw container or CPIO archive.
+ */
+static int __initdata early_mod_idx = -1;
+
 static int __init cf_check microcode_init_cache(void)
 {
     struct boot_info *bi = &xen_boot_info;
+    void *data;

Afaics the sole reason this isn't const void * and ...

Quoted 8 lines

xen/arch/x86/cpu/microcode/core.c presmp_initcall(microcode_init_cache); · line 791

Quoted 6 lines
xen/arch/x86/cpu/microcode/core.c +1 -1
@@ -819,7 +788,7 @@ presmp_initcall(microcode_init_cache);
  */
 static int __init early_microcode_load(struct boot_info *bi)
 {
-    const void *data = NULL;
+    void *data = NULL;

... you're actively dropping const here (which I consider bad) is find_cpio_data() wrongly taking void * as 2nd parameter.

No; it's only one of 2 reasons.

Quoted 3 lines

Internally it
copies the parameter to a const char * variable, so the non-const param is bogus.

... and then back into a non-const variable, hence why such a change doesn't work.

Quoted 4 lines

With the const here retained and const added further up (on
top of a trivial prereq patch adjusting find_cpio_data(), which I've just sent out):

Only after this series has make const-ness consistent through this logic, can you go about changing CPIO.

~Andrew

Reviewed-by on v1 9/10
#37 lore raw

Re: [PATCH 09/10] x86/ucode: Drop ucode_mod and ucode_blob

In reply to Andrew Cooper
Quoted 32 lines · Andrew Cooper

Both are used to pass information from early_microcode_load() to microcode_init_cache(), and both constitute use-after-free's in certain cases.

* ucode_mod is a copy of the module_t identified by ucode=$n. Except it's a copy from prior to Xen relocating the modules. microcode_init_cache() might happen to find the data still intact in it's old location, but it might be an arbitrary part of some other module.

* ucode_blob is a stashed pointer to a bootstrap_map() which becomes invalid the moment control returns to __start_xen(), where other logic is free to to make temporary mappings. This was even noticed and microcode_init_cache() adjusted to "fix" the stashed pointers.

The information which should be passed between these two functions is which module to look in. Introduce early_mod_idx for this purpose. opt_scan can be reused to distinguish between CPIO archives and raw containers.

Notably this means microcode_init_cache() doesn't need to scan all modules any more; we know exactly which one to look in. However, we do re-parse the CPIO header for simplicity.

Furthermore, microcode_init_cache(), being a presmp_initcall does not need to use bootstrap_map() to access modules; it can use mfn_to_virt() directly, which avoids needing to funnel exit paths through bootstrap_unmap().

Fold microcode_scan_module() into what is now it's single caller. It operates on the function-wide idx/data/size state which allows for a unified "found" path irrespective of module selection method.

This resolves all issues to do with holding pointers (physical or virtual) across returning to __start_xen().

Quoted 6 lines

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>
---

#38 lore raw

PATCH 10/10 x86/ucode: Fold early_update_cache() into its single caller

In reply to Andrew Cooper

The data pointer is known good, so the -ENOMEM path is unnecessary. However, if we find no patch, something's wrong seeing as early_microcode_init() indicated it was happy.

We are the entity initialising the cache, so we don't need the complexity of using microcode_update_cache(). Just assert the cache is empty, and populate it.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c | 47 +++++++++++++------------------
 1 file changed, 19 insertions(+), 28 deletions(-)
xen/arch/x86/cpu/microcode/core.c +19 -28
index 591c13ad91fb..90a6f2bd87ae 100644
@@ -707,33 +707,6 @@ int microcode_update_one(void)
     return microcode_update_cpu(NULL, 0);
 }
 
-static int __init early_update_cache(const void *data, size_t len)
-{
-    int rc = 0;
-    struct microcode_patch *patch;
-
-    if ( !data )
-        return -ENOMEM;
-
-    patch = parse_blob(data, len);
-    if ( IS_ERR(patch) )
-    {
-        printk(XENLOG_WARNING "Parsing microcode blob error %ld\n",
-               PTR_ERR(patch));
-        return PTR_ERR(patch);
-    }
-
-    if ( !patch )
-        return -ENOENT;
-
-    spin_lock(&microcode_mutex);
-    rc = microcode_update_cache(patch);
-    spin_unlock(&microcode_mutex);
-    ASSERT(rc);
-
-    return rc;
-}
-
 /*
  * Set by early_microcode_load() to indicate where it found microcode, so
  * microcode_init_cache() can find it again and initalise the cache.  opt_scan
@@ -744,6 +717,7 @@ static int __initdata early_mod_idx = -1;
 static int __init cf_check microcode_init_cache(void)
 {
     struct boot_info *bi = &xen_boot_info;
+    struct microcode_patch *patch;
     void *data;
     size_t size;
     int rc = 0;
@@ -774,7 +748,24 @@ static int __init cf_check microcode_init_cache(void)
         size = cd.size;
     }
 
-    rc = early_update_cache(data, size);
+    patch = parse_blob(data, size);
+    if ( IS_ERR(patch) )
+    {
+        rc = PTR_ERR(patch);
+        printk(XENLOG_WARNING "Microcode: Parse error %d\n", rc);
+        return rc;
+    }
+
+    if ( !patch )
+    {
+        printk(XENLOG_WARNING "Microcode: No suitable patch found\n");
+        return -ENOENT;
+    }
+
+    spin_lock(&microcode_mutex);
+    ASSERT(microcode_cache == NULL);
+    microcode_cache = patch;
+    spin_unlock(&microcode_mutex);
 
     return rc;
 }
Signature · 1 line
2.39.5
Acked-by on v1 10/10
#39 lore raw

Re: [PATCH 10/10] x86/ucode: Fold early_update_cache() into its single caller

Quoted 9 lines · Andrew Cooper

The data pointer is known good, so the -ENOMEM path is unnecessary. However, if we find no patch, something's wrong seeing as early_microcode_init() indicated it was happy.

We are the entity initialising the cache, so we don't need the complexity of using microcode_update_cache(). Just assert the cache is empty, and populate it.

Reviewed-by on v1 10/10
#40 lore raw

Re: [PATCH 10/10] x86/ucode: Fold early_update_cache() into its single caller

In reply to Andrew Cooper
Quoted 8 lines · Andrew Cooper

The data pointer is known good, so the -ENOMEM path is unnecessary. However, if we find no patch, something's wrong seeing as early_microcode_init() indicated it was happy.

We are the entity initialising the cache, so we don't need the complexity of using microcode_update_cache(). Just assert the cache is empty, and populate it.

Quoted 6 lines

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Daniel P. Smith <[email protected]>
---