Skip to contentSkip to conversation

x86/ucode: Simplify/fix loading paths further

PATCH Superseded Andrew Cooper 2 participants 20 messages Nov 7, 2024 – Nov 12, 2024

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover x86/ucode: Simplify/fix loading paths further

collect_cpu_info() is fairly expensive and called excessively. Rationalise this substantially.

Except I found yet another bug when testing this. Notes in patch 3.

Andrew Cooper (3):
x86/ucode: Don't use microcode_update_cpu() in early_microcode_load() x86/ucode: Fold microcode_update_cpu() and fix error handling x86/ucode: Remove the collect_cpu_info() call from parse_blob()

 xen/arch/x86/cpu/microcode/core.c | 53 +++++++++----------------------
 1 file changed, 15 insertions(+), 38 deletions(-)
Signature · 1 line
2.39.5
#1 lore raw

PATCH 1/3 x86/ucode: Don't use microcode_update_cpu() in early_microcode_load()

There are two callers of microcode_update_cpu(), and because one passes NULL and one doesn't, there are effectively two disjoint pieces of logic wrapped in a single function.

early_microcode_load()'s use skips all the microcode_cache handling, and is just a simple patch application.

This skips a redundant collect_cpu_info() call (performed in early_microcode_init(), marginally earlier), and avoids holding microcode_mutex when we're not interacting with microcode_cache at all.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
xen/arch/x86/cpu/microcode/core.c +1 -1
index 11cd878d1f2e..d9406ec3fd34 100644
@@ -900,7 +900,7 @@ static int __init early_microcode_load(struct boot_info *bi)
      */
     early_mod_idx = idx;
 
-    rc = microcode_update_cpu(patch, 0);
+    rc = ucode_ops.apply_microcode(patch, 0);
 
  unmap:
     bootstrap_unmap();
Signature · 1 line
2.39.5
Reviewed-by on v1 1/3
#2 lore raw

Re: [PATCH 1/3] x86/ucode: Don't use microcode_update_cpu() in early_microcode_load()

Quoted 7 lines · Andrew Cooper

There are two callers of microcode_update_cpu(), and because one passes NULL and one doesn't, there are effectively two disjoint pieces of logic wrapped in a single function.

early_microcode_load()'s use skips all the microcode_cache handling, and is just a simple patch application.

Quoted 7 lines

This skips a redundant collect_cpu_info() call (performed in early_microcode_init(), marginally earlier), and avoids holding microcode_mutex when we're not interacting with microcode_cache at all.

No functional change.

Personally I would have deemed it more logical (and Misra-compliant) to remove the "if ( patch )" case from microcode_update_cpu() right here. Surely (by its title) the next patch is going to have the same effect.

Jan

#3 lore raw

PATCH 2/3 x86/ucode: Fold microcode_update_cpu() and fix error handling

In reply to Andrew Cooper

Fold microcode_update_cpu() into its single remaining caller and simplify the logic by removing the patch != NULL path with microcode_mutex held.

Explain why we bother grabbing the microcode revision even if we can't load microcode.

Furthermore, delete the -EIO path. An error updating microcode on AP boot or S3 resume is certainly bad, but freeing the cache is about the worst possible action we can take in response; it prevents subsequent APs from taking an update they might have accepted.

This avoids a double collect_cpu_info() call on each AP.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/cpu/microcode/core.c | 49 +++++++++----------------------
 1 file changed, 14 insertions(+), 35 deletions(-)
xen/arch/x86/cpu/microcode/core.c +14 -35
index d9406ec3fd34..fd4b08b45388 100644
@@ -263,40 +263,6 @@ static bool cf_check wait_cpu_callout(unsigned int nr)
     return atomic_read(&cpu_out) >= nr;
 }
 
-/*
- * Load a microcode update to current CPU.
- *
- * If no patch is provided, the cached patch will be loaded. Microcode update
- * during APs bringup and CPU resuming falls into this case.
- */
-static int microcode_update_cpu(const struct microcode_patch *patch,
-                                unsigned int flags)
-{
-    int err;
-
-    alternative_vcall(ucode_ops.collect_cpu_info);
-
-    spin_lock(&microcode_mutex);
-    if ( patch )
-        err = alternative_call(ucode_ops.apply_microcode, patch, flags);
-    else if ( microcode_cache )
-    {
-        err = alternative_call(ucode_ops.apply_microcode, microcode_cache,
-                               flags);
-        if ( err == -EIO )
-        {
-            microcode_free_patch(microcode_cache);
-            microcode_cache = NULL;
-        }
-    }
-    else
-        /* No patch to update */
-        err = -ENOENT;
-    spin_unlock(&microcode_mutex);
-
-    return err;
-}
-
 static bool wait_for_state(typeof(loading_state) state)
 {
     typeof(loading_state) cur_state;
@@ -702,13 +668,26 @@ int microcode_update(XEN_GUEST_HANDLE(const_void) buf,
 /* Load a cached update to current cpu */
 int microcode_update_one(void)
 {
+    int rc;
+
+    /*
+     * This path is used for APs and S3 resume.  Read the microcode revision
+     * if possible, even if we can't load microcode.
+     */
     if ( ucode_ops.collect_cpu_info )
         alternative_vcall(ucode_ops.collect_cpu_info);
 
     if ( !ucode_ops.apply_microcode )
         return -EOPNOTSUPP;
 
-    return microcode_update_cpu(NULL, 0);
+    spin_lock(&microcode_mutex);
+    if ( microcode_cache )
+        rc = alternative_call(ucode_ops.apply_microcode, microcode_cache, 0);
+    else
+        rc = -ENOENT;
+    spin_unlock(&microcode_mutex);
+
+    return rc;
 }
 
 /*
Signature · 1 line
2.39.5
#4 lore raw

Re: [PATCH 2/3] x86/ucode: Fold microcode_update_cpu() and fix error handling

Quoted 10 lines · Andrew Cooper

Fold microcode_update_cpu() into its single remaining caller and simplify the logic by removing the patch != NULL path with microcode_mutex held.

Explain why we bother grabbing the microcode revision even if we can't load microcode.

Furthermore, delete the -EIO path. An error updating microcode on AP boot or S3 resume is certainly bad, but freeing the cache is about the worst possible action we can take in response; it prevents subsequent APs from taking an update they might have accepted.

I'm afraid I disagree here, but I also disagree with the present error handling. -EIO indicates the patch didn't apply. Why would there be any hope that any other CPU would accept it? We're assuming fully symmetric hardware, after all. However, imo it's not -EIO that ought to be special cased, but success and -EEXIST. In all other cases the same error will re-surface for other CPUs. Plus by not cleaning the cache we prevent an older revision to be installed (without forcing its installation).

Keeping what's cached might be an option, but then followed by cleaning the cache unless at least one CPU actually accepted the ucode.

Jan

#5 lore raw

Re: [PATCH 2/3] x86/ucode: Fold microcode_update_cpu() and fix error handling

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

Fold microcode_update_cpu() into its single remaining caller and simplify the logic by removing the patch != NULL path with microcode_mutex held.

Explain why we bother grabbing the microcode revision even if we can't load microcode.

Quoted 7 lines
Quoted 4 lines

Furthermore, delete the -EIO path. An error updating microcode on AP boot or S3 resume is certainly bad, but freeing the cache is about the worst possible action we can take in response; it prevents subsequent APs from taking an update they might have accepted.

I'm afraid I disagree here, but I also disagree with the present error handling. -EIO indicates the patch didn't apply. Why would there be any hope that any other CPU would accept it?

-EIO is "something went wrong".

On modern systems this can include "checksum didn't match because there's a bad SRAM cell".  This is literally one of the failures leading to the introduction of In-Field-Scan.

Individual cores really can fail in a way which won't be the same elsewhere in the system.

Quoted 2 lines

Keeping what's cached might be an option, but then followed by cleaning the cache unless at least one CPU actually accepted the ucode.

We already have that behaviour.

We cache speculatively on boot, even if the BSP doesn't need to load, because APs might need to.  This really is the best we can do.

The only other time the cache gets modified is after a late-load attempt which reported success.  There are still a lot of partial-failure error cases to handle less badly, but that needs yet more untangling before it can be addressed adequately.

~Andrew

Acked-by
#6 lore raw

Re: [PATCH 2/3] x86/ucode: Fold microcode_update_cpu() and fix error handling

Quoted 16 lines · Andrew Cooper
Quoted 7 lines · Jan Beulich
Quoted 6 lines · Andrew Cooper

Fold microcode_update_cpu() into its single remaining caller and simplify the logic by removing the patch != NULL path with microcode_mutex held.

Explain why we bother grabbing the microcode revision even if we can't load microcode.

Quoted 7 lines
Quoted 4 lines

Furthermore, delete the -EIO path. An error updating microcode on AP boot or S3 resume is certainly bad, but freeing the cache is about the worst possible action we can take in response; it prevents subsequent APs from taking an update they might have accepted.

I'm afraid I disagree here, but I also disagree with the present error handling. -EIO indicates the patch didn't apply. Why would there be any hope that any other CPU would accept it?

Quoted 8 lines

-EIO is "something went wrong".

On modern systems this can include "checksum didn't match because there's a bad SRAM cell".  This is literally one of the failures leading to the introduction of In-Field-Scan.

Individual cores really can fail in a way which won't be the same elsewhere in the system.

Hmm, well, slightly hesitantly

Ideally with a remark added to the description that there is known room for further improvement.

Quoted 8 lines
Quoted 2 lines

Keeping what's cached might be an option, but then followed by cleaning the cache unless at least one CPU actually accepted the ucode.

We already have that behaviour.

We cache speculatively on boot, even if the BSP doesn't need to load, because APs might need to.  This really is the best we can do.

That's a different scenario. If we ended up with ucode which no single CPU accepts, there's hardly much point in caching that ucode. This specifically is meant not to include the case where simply all CPUs are already up-to-date. The one largely theoretical case where caching may still make sense is for CPU hotplug, where the hot-plugged CPU(s) may accept what all boot-time CPUs refused.

Jan

#7 lore raw

PATCH 3/3 x86/ucode: Remove the collect_cpu_info() call from parse_blob()

In reply to Andrew Cooper

With the tangle of logic starting to come under control, it is now plain to see that parse_blob()'s side effect of re-gathering the signature/revision is pointless.

The cpu_request_microcode() hooks need the signature only. The BSP gathers this in early_microcode_init(), the APs and S3 in microcode_update_cpu(). For good measure, the apply_microcode() hooks also keep the revision correct as load attempts are made.

This finally gets us down to a single call per CPU on boot / S3 resume, and no calls during late-load hypercalls.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

Slightly RFC.

Just before posting, I've realised that cpu_request_microcode() does actually use the current CPU revision, and it's buggy, and it's the cause of xen-ucode --force not working as expected.

I'm tempted to do another series cleaning that up in isolation, such that this patch becomes true in this form.

---
 xen/arch/x86/cpu/microcode/core.c | 2 --
 1 file changed, 2 deletions(-)
xen/arch/x86/cpu/microcode/core.c +0 -2
index fd4b08b45388..5897ec54032a 100644
@@ -189,8 +189,6 @@ static struct patch_with_flags nmi_patch =
  */
 static struct microcode_patch *parse_blob(const char *buf, size_t len)
 {
-    alternative_vcall(ucode_ops.collect_cpu_info);
-
     return alternative_call(ucode_ops.cpu_request_microcode, buf, len, true);
 }
 
Signature · 1 line
2.39.5
#8 lore raw

Re: [PATCH 3/3] x86/ucode: Remove the collect_cpu_info() call from parse_blob()

Quoted 19 lines · Andrew Cooper

With the tangle of logic starting to come under control, it is now plain to see that parse_blob()'s side effect of re-gathering the signature/revision is pointless.

The cpu_request_microcode() hooks need the signature only. The BSP gathers this in early_microcode_init(), the APs and S3 in microcode_update_cpu(). For good measure, the apply_microcode() hooks also keep the revision correct as load attempts are made.

This finally gets us down to a single call per CPU on boot / S3 resume, and no calls during late-load hypercalls.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

Quoted 8 lines

Slightly RFC.

Just before posting, I've realised that cpu_request_microcode() does actually use the current CPU revision, and it's buggy, and it's the cause of xen-ucode --force not working as expected.

I'm tempted to do another series cleaning that up in isolation, such that this patch becomes true in this form.

Actually no.  Having tried a bit, I think it's easier to do with patch 2 already in place.

So instead I'm tempted to edit the middle paragraph to note that it currently uses the revision but that's going to be fixed shortly.  The rest of the paragraph explains why it's still safe anyway.

~Andrew

#9 lore raw

Re: [PATCH 3/3] x86/ucode: Remove the collect_cpu_info() call from parse_blob()

Quoted 26 lines · Andrew Cooper
Quoted 25 lines · Andrew Cooper

With the tangle of logic starting to come under control, it is now plain to see that parse_blob()'s side effect of re-gathering the signature/revision is pointless.

The cpu_request_microcode() hooks need the signature only. The BSP gathers this in early_microcode_init(), the APs and S3 in microcode_update_cpu(). For good measure, the apply_microcode() hooks also keep the revision correct as load attempts are made.

This finally gets us down to a single call per CPU on boot / S3 resume, and no calls during late-load hypercalls.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

Slightly RFC.

Just before posting, I've realised that cpu_request_microcode() does actually use the current CPU revision, and it's buggy, and it's the cause of xen-ucode --force not working as expected.

Quoted 8 lines
Quoted 2 lines

I'm tempted to do another series cleaning that up in isolation, such that this patch becomes true in this form.

Actually no.  Having tried a bit, I think it's easier to do with patch 2 already in place.

So instead I'm tempted to edit the middle paragraph to note that it currently uses the revision but that's going to be fixed shortly.  The rest of the paragraph explains why it's still safe anyway.

So, after the latter series, this patch happens to be accurate.

cpu_request_microcode() does read the revision, but discards the result of the calculation which used it.

~Andrew

#10 lore raw

Re: [PATCH 3/3] x86/ucode: Remove the collect_cpu_info() call from parse_blob()

Quoted 32 lines · Andrew Cooper
Quoted 31 lines · Andrew Cooper
Quoted 19 lines · Andrew Cooper

With the tangle of logic starting to come under control, it is now plain to see that parse_blob()'s side effect of re-gathering the signature/revision is pointless.

The cpu_request_microcode() hooks need the signature only. The BSP gathers this in early_microcode_init(), the APs and S3 in microcode_update_cpu(). For good measure, the apply_microcode() hooks also keep the revision correct as load attempts are made.

This finally gets us down to a single call per CPU on boot / S3 resume, and no calls during late-load hypercalls.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

Quoted 8 lines

Slightly RFC.

Just before posting, I've realised that cpu_request_microcode() does actually use the current CPU revision, and it's buggy, and it's the cause of xen-ucode --force not working as expected.

I'm tempted to do another series cleaning that up in isolation, such that this patch becomes true in this form.

Actually no.  Having tried a bit, I think it's easier to do with patch 2 already in place.

Quoted 8 lines
Quoted 3 lines

So instead I'm tempted to edit the middle paragraph to note that it currently uses the revision but that's going to be fixed shortly.  The rest of the paragraph explains why it's still safe anyway.

So, after the latter series, this patch happens to be accurate.

cpu_request_microcode() does read the revision, but discards the result of the calculation which used it.

What's the intended overall sequence of patches then? With two series that (aiui) now have grown some sort of dependency, and with this series have gained a 4/3 patch, having a clear picture would certainly help. Might it be best if you merge both series and re-submit as a single one?

Jan

#11 lore raw

Re: [PATCH 3/3] x86/ucode: Remove the collect_cpu_info() call from parse_blob()

Quoted 36 lines · Jan Beulich
Quoted 35 lines · Andrew Cooper
Quoted 34 lines · Andrew Cooper
Quoted 19 lines · Andrew Cooper

With the tangle of logic starting to come under control, it is now plain to see that parse_blob()'s side effect of re-gathering the signature/revision is pointless.

The cpu_request_microcode() hooks need the signature only. The BSP gathers this in early_microcode_init(), the APs and S3 in microcode_update_cpu(). For good measure, the apply_microcode() hooks also keep the revision correct as load attempts are made.

This finally gets us down to a single call per CPU on boot / S3 resume, and no calls during late-load hypercalls.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

Quoted 8 lines

Slightly RFC.

Just before posting, I've realised that cpu_request_microcode() does actually use the current CPU revision, and it's buggy, and it's the cause of xen-ucode --force not working as expected.

I'm tempted to do another series cleaning that up in isolation, such that this patch becomes true in this form.

Actually no.  Having tried a bit, I think it's easier to do with patch 2 already in place.

So instead I'm tempted to edit the middle paragraph to note that it currently uses the revision but that's going to be fixed shortly.  The rest of the paragraph explains why it's still safe anyway.

Quoted 8 lines
Quoted 4 lines

So, after the latter series, this patch happens to be accurate.

cpu_request_microcode() does read the revision, but discards the result of the calculation which used it.

What's the intended overall sequence of patches then? With two series that (aiui) now have grown some sort of dependency, and with this series have gained a 4/3 patch, having a clear picture would certainly help. Might it be best if you merge both series and re-submit as a single one?

The order turns out to be as emailed out and threaded.

~Andrew

#12 lore raw

Re: [PATCH 3/3] x86/ucode: Remove the collect_cpu_info() call from parse_blob()

Quoted 39 lines · Andrew Cooper
Quoted 38 lines · Jan Beulich
Quoted 37 lines · Andrew Cooper
Quoted 26 lines · Andrew Cooper
Quoted 25 lines · Andrew Cooper

With the tangle of logic starting to come under control, it is now plain to see that parse_blob()'s side effect of re-gathering the signature/revision is pointless.

The cpu_request_microcode() hooks need the signature only. The BSP gathers this in early_microcode_init(), the APs and S3 in microcode_update_cpu(). For good measure, the apply_microcode() hooks also keep the revision correct as load attempts are made.

This finally gets us down to a single call per CPU on boot / S3 resume, and no calls during late-load hypercalls.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

Slightly RFC.

Just before posting, I've realised that cpu_request_microcode() does actually use the current CPU revision, and it's buggy, and it's the cause of xen-ucode --force not working as expected.

Quoted 8 lines
Quoted 2 lines

I'm tempted to do another series cleaning that up in isolation, such that this patch becomes true in this form.

Actually no.  Having tried a bit, I think it's easier to do with patch 2 already in place.

So instead I'm tempted to edit the middle paragraph to note that it currently uses the revision but that's going to be fixed shortly.  The rest of the paragraph explains why it's still safe anyway.

So, after the latter series, this patch happens to be accurate.

Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

cpu_request_microcode() does read the revision, but discards the result of the calculation which used it.

What's the intended overall sequence of patches then? With two series that (aiui) now have grown some sort of dependency, and with this series have gained a 4/3 patch, having a clear picture would certainly help. Might it be best if you merge both series and re-submit as a single one?

The order turns out to be as emailed out and threaded.

Yet above you said "after the latter series, this patch happens to be accurate." Which suggest to me that at least part of the latter series needs to be in place for the change here to be correct. IOW - I'm confused now.

Jan

#13 lore raw

[PATCH 4/3] x86/ucode: Fix cache handling in microcode_update_helper()

In reply to Andrew Cooper

microcode_update_cache() now has a single caller, but inlining it shows how unnecessarily complicated the logic really is.

Outside of error paths, there is always one microcode patch to free. Its either result of parse_blob(), or it's the old cached value.

In order to fix this, have a local patch pointer (mostly to avoid the unnecessary verbosity of patch_with_flags.patch), and always free it at the end. The only error path needing care is the IS_ERR(patch) path, which is easy enough to handle.

Also, widen the scope of result. We only need to call compare_patch() once, and the answer is still good later when updating the cache. In order to update the cache, simply SWAP() the patch and the cache pointers, allowing the singular xfree() at the end to cover both cases.

This also removes all callers microcode_free_patch() which fixes the need to cast away const to allow it to compile.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

This is in prepartion to totally overhaul compare_patch(). There's now only a single caller.

---
 xen/arch/x86/cpu/microcode/core.c | 66 +++++++++++--------------------
 1 file changed, 24 insertions(+), 42 deletions(-)
xen/arch/x86/cpu/microcode/core.c +24 -42
index 5897ec54032a..0cc5daa251e2 100644
@@ -86,7 +86,7 @@ struct patch_with_flags {
 static bool ucode_in_nmi = true;
 
 /* Protected by microcode_mutex */
-static const struct microcode_patch *microcode_cache;
+static struct microcode_patch *microcode_cache;
 
 /*
  * opt_mod_idx and opt_scan have subtle semantics.
@@ -192,33 +192,6 @@ static struct microcode_patch *parse_blob(const char *buf, size_t len)
     return alternative_call(ucode_ops.cpu_request_microcode, buf, len, true);
 }
 
-static void microcode_free_patch(const struct microcode_patch *patch)
-{
-    xfree((struct microcode_patch *)patch);
-}
-
-/* Return true if cache gets updated. Otherwise, return false */
-static bool microcode_update_cache(const struct microcode_patch *patch)
-{
-    ASSERT(spin_is_locked(&microcode_mutex));
-
-    if ( !microcode_cache )
-        microcode_cache = patch;
-    else if ( alternative_call(ucode_ops.compare_patch,
-                               patch, microcode_cache) == NEW_UCODE )
-    {
-        microcode_free_patch(microcode_cache);
-        microcode_cache = patch;
-    }
-    else
-    {
-        microcode_free_patch(patch);
-        return false;
-    }
-
-    return true;
-}
-
 /* Returns true if ucode should be loaded on a given cpu */
 static bool is_cpu_primary(unsigned int cpu)
 {
@@ -496,6 +469,8 @@ struct ucode_buf {
 
 static long cf_check microcode_update_helper(void *data)
 {
+    struct microcode_patch *patch = NULL;
+    enum microcode_match_result result;
     int ret;
     struct ucode_buf *buffer = data;
     unsigned int cpu, updated;
@@ -524,17 +499,20 @@ static long cf_check microcode_update_helper(void *data)
         goto put;
     }
 
-    patch_with_flags.patch = parse_blob(buffer->buffer, buffer->len);
+    patch = parse_blob(buffer->buffer, buffer->len);
     patch_with_flags.flags = buffer->flags;
+
     xfree(buffer);
-    if ( IS_ERR(patch_with_flags.patch) )
+
+    if ( IS_ERR(patch) )
     {
-        ret = PTR_ERR(patch_with_flags.patch);
+        ret = PTR_ERR(patch);
+        patch = NULL;
         printk(XENLOG_WARNING "Parsing microcode blob error %d\n", ret);
         goto put;
     }
 
-    if ( !patch_with_flags.patch )
+    if ( !patch )
     {
         printk(XENLOG_WARNING "microcode: couldn't find any matching ucode in "
                               "the provided blob!\n");
@@ -549,10 +527,7 @@ static long cf_check microcode_update_helper(void *data)
     spin_lock(&microcode_mutex);
     if ( microcode_cache )
     {
-        enum microcode_match_result result;
-
-        result = alternative_call(ucode_ops.compare_patch,
-                                  patch_with_flags.patch, microcode_cache);
+        result = alternative_call(ucode_ops.compare_patch, patch, microcode_cache);
 
         if ( result != NEW_UCODE &&
              !(ucode_force && (result == OLD_UCODE || result == SAME_UCODE)) )
@@ -561,12 +536,13 @@ static long cf_check microcode_update_helper(void *data)
             printk(XENLOG_WARNING
                    "microcode: couldn't find any newer%s revision in the provided blob!\n",
                    ucode_force ? " (or a valid)" : "");
-            microcode_free_patch(patch_with_flags.patch);
             ret = -EEXIST;
 
             goto put;
         }
     }
+    else
+        result = NEW_UCODE;
     spin_unlock(&microcode_mutex);
 
     cpumask_clear(&cpu_callin_map);
@@ -593,14 +569,18 @@ static long cf_check microcode_update_helper(void *data)
      *   this requirement can be relaxed in the future. Right now, this is
      *   conservative and good.
      */
+    patch_with_flags.patch = patch;
     ret = stop_machine_run(do_microcode_update, &patch_with_flags, NR_CPUS);
 
     updated = atomic_read(&cpu_updated);
     if ( updated > 0 )
     {
-        spin_lock(&microcode_mutex);
-        microcode_update_cache(patch_with_flags.patch);
-        spin_unlock(&microcode_mutex);
+        if ( result == NEW_UCODE )
+        {
+            spin_lock(&microcode_mutex);
+            SWAP(patch, microcode_cache);
+            spin_unlock(&microcode_mutex);
+        }
 
         /*
          * Refresh the raw CPU policy, in case the features have changed.
@@ -615,8 +595,6 @@ static long cf_check microcode_update_helper(void *data)
         if ( ctxt_switch_masking )
             alternative_vcall(ctxt_switch_masking, current);
     }
-    else
-        microcode_free_patch(patch_with_flags.patch);
 
     if ( updated && updated != nr_cores )
         printk(XENLOG_ERR "ERROR: Updating microcode succeeded on %u cores and failed\n"
@@ -627,6 +605,10 @@ static long cf_check microcode_update_helper(void *data)
 
  put:
     put_cpu_maps();
+
+    /* The parsed blob or old cached value, whichever we're not keeping. */
+    xfree(patch);
+
     return ret;
 }
 
Signature · 1 line
2.39.5
#14 lore raw

cover x86/ucode: Untangle revision-relational logic

In reply to Andrew Cooper

Right now, cpu_request_microcode() ends up consuming the currently-loaded microcode revision (and discarding the answer), simply because the helpers are too overloaded.

Andrew Cooper (3):
x86/ucode: Rework Intel's microcode_update_match() x86/ucode: Rework AMD's microcode_fits() x86/ucode: Drop MIS_UCODE and microcode_match_result

 xen/arch/x86/cpu/microcode/amd.c     | 57 +++++++++++++---------------
 xen/arch/x86/cpu/microcode/core.c    |  5 +--
 xen/arch/x86/cpu/microcode/intel.c   | 35 ++++++++---------
 xen/arch/x86/cpu/microcode/private.h | 21 +++++-----
 4 files changed, 54 insertions(+), 64 deletions(-)
Signature · 1 line
2.39.5
#15 lore raw

PATCH 1/3 x86/ucode: Rework Intel's microcode_update_match()

This function is overloaded, creating complexity; 3 of 4 callers already only want it for it's "applicable to this CPU or not" answer, and handle revision calculations separately.

Change it to be microcode_fits_cpu(), returning a simple boolean.

Notably, this removes a path where cpu_request_microcode() inspects currently-loaded microcode revision, just to discard the answer.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/cpu/microcode/intel.c | 26 +++++++++++---------------
 1 file changed, 11 insertions(+), 15 deletions(-)
xen/arch/x86/cpu/microcode/intel.c +11 -15
index aad6a693e800..3f37792ab4b5 100644
@@ -248,9 +248,8 @@ static enum microcode_match_result compare_revisions(
     return OLD_UCODE;
 }
 
-/* Check an update against the CPU signature and current update revision */
-static enum microcode_match_result microcode_update_match(
-    const struct microcode_patch *mc)
+/* Check whether this microcode patch is applicable for the current CPU. */
+static bool microcode_fits_cpu(const struct microcode_patch *mc)
 {
     const struct extended_sigtable *ext;
     unsigned int i;
@@ -260,18 +259,15 @@ static enum microcode_match_result microcode_update_match(
 
     /* Check the main microcode signature. */
     if ( signature_matches(cpu_sig, mc->sig, mc->pf) )
-        goto found;
+        return true;
 
     /* If there is an extended signature table, check each of them. */
     if ( (ext = get_ext_sigtable(mc)) != NULL )
         for ( i = 0; i < ext->count; ++i )
             if ( signature_matches(cpu_sig, ext->sigs[i].sig, ext->sigs[i].pf) )
-                goto found;
-
-    return MIS_UCODE;
+                return true;
 
- found:
-    return compare_revisions(cpu_sig->rev, mc->rev);
+    return false;
 }
 
 static enum microcode_match_result cf_check compare_patch(
@@ -281,8 +277,8 @@ static enum microcode_match_result cf_check compare_patch(
      * Both patches to compare are supposed to be applicable to local CPU.
      * Just compare the revision number.
      */
-    ASSERT(microcode_update_match(old) != MIS_UCODE);
-    ASSERT(microcode_update_match(new) != MIS_UCODE);
+    ASSERT(microcode_fits_cpu(old));
+    ASSERT(microcode_fits_cpu(new));
 
     return compare_revisions(old->rev, new->rev);
 }
@@ -297,11 +293,11 @@ static int cf_check apply_microcode(const struct microcode_patch *patch,
     enum microcode_match_result result;
     bool ucode_force = flags & XENPF_UCODE_FORCE;
 
-    result = microcode_update_match(patch);
-
-    if ( result == MIS_UCODE )
+    if ( !microcode_fits_cpu(patch) )
         return -EINVAL;
 
+    result = compare_revisions(old_rev, patch->rev);
+
     if ( !ucode_force && (result == SAME_UCODE || result == OLD_UCODE) )
         return -EEXIST;
 
@@ -365,7 +361,7 @@ static struct microcode_patch *cf_check cpu_request_microcode(
          * If the new update covers current CPU, compare updates and store the
          * one with higher revision.
          */
-        if ( (microcode_update_match(mc) != MIS_UCODE) &&
+        if ( microcode_fits_cpu(mc) &&
              (!saved || compare_revisions(saved->rev, mc->rev) == NEW_UCODE) )
             saved = mc;
 
Signature · 1 line
2.39.5
Reviewed-by on v1 1/3
#16 lore raw

Re: [PATCH 1/3] x86/ucode: Rework Intel's microcode_update_match()

Quoted 4 lines · Andrew Cooper

This function is overloaded, creating complexity; 3 of 4 callers already only want it for it's "applicable to this CPU or not" answer, and handle revision calculations separately.

Quoted 8 lines

Change it to be microcode_fits_cpu(), returning a simple boolean.

Notably, this removes a path where cpu_request_microcode() inspects currently-loaded microcode revision, just to discard the answer.

No functional change.

#17 lore raw

PATCH 2/3 x86/ucode: Rework AMD's microcode_fits()

In reply to Andrew Cooper

This function is overloaded, creating complexity; 3 of 4 callers already only want it for it's "applicable to this CPU or not" answer, and handle revision calculations separately.

Change it to be microcode_fits_cpu(), returning a simple boolean. The checking of the equiv table can be simplified substantially too; A mapping will only be inserted if it's correct for the CPU, so any nonzero equiv.sig suffices to know that equiv.id is correct.

Drop compare_header() too, which is simiarly overloaded, and use compare_revisions() directly.

Notably, this removes a path where cpu_request_microcode() inspects currently-loaded microcode revision, just to discard the answer.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/cpu/microcode/amd.c | 49 ++++++++++++++++----------------
 1 file changed, 24 insertions(+), 25 deletions(-)
xen/arch/x86/cpu/microcode/amd.c +24 -25
index c7a779c1d885..3861fec6565a 100644
@@ -182,36 +182,31 @@ static enum microcode_match_result compare_revisions(
     return OLD_UCODE;
 }
 
-static enum microcode_match_result microcode_fits(
-    const struct microcode_patch *patch)
-{
-    unsigned int cpu = smp_processor_id();
-    const struct cpu_signature *sig = &per_cpu(cpu_sig, cpu);
-
-    if ( equiv.sig != sig->sig ||
-         equiv.id  != patch->processor_rev_id )
-        return MIS_UCODE;
-
-    return compare_revisions(sig->rev, patch->patch_id);
-}
-
-static enum microcode_match_result compare_header(
-    const struct microcode_patch *new, const struct microcode_patch *old)
+/*
+ * Check whether this microcode patch is applicable for the current CPU.
+ *
+ * AMD microcode blobs only have the "equivalent CPU identifier" which is a 16
+ * bit contraction of the 32 bit Family/Model/Stepping.
+ *
+ * We expect to only be run after scan_equiv_cpu_table() has found a valid
+ * mapping for the current CPU.  If this is violated, the 0 in equiv.id will
+ * cause the patch to be rejected too.
+ */
+static bool microcode_fits_cpu(const struct microcode_patch *patch)
 {
-    if ( new->processor_rev_id != old->processor_rev_id )
-        return MIS_UCODE;
+    ASSERT(equiv.sig);
 
-    return compare_revisions(old->patch_id, new->patch_id);
+    return equiv.id == patch->processor_rev_id;
 }
 
 static enum microcode_match_result cf_check compare_patch(
     const struct microcode_patch *new, const struct microcode_patch *old)
 {
     /* Both patches to compare are supposed to be applicable to local CPU. */
-    ASSERT(microcode_fits(new) != MIS_UCODE);
-    ASSERT(microcode_fits(old) != MIS_UCODE);
+    ASSERT(microcode_fits_cpu(new));
+    ASSERT(microcode_fits_cpu(old));
 
-    return compare_header(new, old);
+    return compare_revisions(old->patch_id, new->patch_id);
 }
 
 static int cf_check apply_microcode(const struct microcode_patch *patch,
@@ -221,12 +216,14 @@ static int cf_check apply_microcode(const struct microcode_patch *patch,
     unsigned int cpu = smp_processor_id();
     struct cpu_signature *sig = &per_cpu(cpu_sig, cpu);
     uint32_t rev, old_rev = sig->rev;
-    enum microcode_match_result result = microcode_fits(patch);
+    enum microcode_match_result result;
     bool ucode_force = flags & XENPF_UCODE_FORCE;
 
-    if ( result == MIS_UCODE )
+    if ( !microcode_fits_cpu(patch) )
         return -EINVAL;
 
+    result = compare_revisions(old_rev, patch->patch_id);
+
     /*
      * Allow application of the same revision to pick up SMT-specific changes
      * even if the revision of the other SMT thread is already up-to-date.
@@ -396,8 +393,10 @@ static struct microcode_patch *cf_check cpu_request_microcode(
              * If the new ucode covers current CPU, compare ucodes and store the
              * one with higher revision.
              */
-            if ( (microcode_fits(mc->patch) != MIS_UCODE) &&
-                 (!saved || (compare_header(mc->patch, saved) == NEW_UCODE)) )
+            if ( microcode_fits_cpu(mc->patch) &&
+                 (!saved ||
+                  compare_revisions(saved->patch_id,
+                                    mc->patch->patch_id) == NEW_UCODE) )
             {
                 saved = mc->patch;
                 saved_size = mc->len;
Signature · 1 line
2.39.5
Reviewed-by on v1 2/3
#18 lore raw

Re: [PATCH 2/3] x86/ucode: Rework AMD's microcode_fits()

Quoted 12 lines · Andrew Cooper

This function is overloaded, creating complexity; 3 of 4 callers already only want it for it's "applicable to this CPU or not" answer, and handle revision calculations separately.

Change it to be microcode_fits_cpu(), returning a simple boolean. The checking of the equiv table can be simplified substantially too; A mapping will only be inserted if it's correct for the CPU, so any nonzero equiv.sig suffices to know that equiv.id is correct.

Drop compare_header() too, which is simiarly overloaded, and use compare_revisions() directly.

Quoted 6 lines

Notably, this removes a path where cpu_request_microcode() inspects currently-loaded microcode revision, just to discard the answer.

No functional change.

#19 lore raw

PATCH 3/3 x86/ucode: Drop MIS_UCODE and microcode_match_result

In reply to Andrew Cooper

All uses of MIS_UCODE, have been removed, leaving only a simple ordering relation, and microcode_match_result being a stale name.

Drop the enum entirely, and use a simple int -1/0/1 scheme like other standard ordering primitives in C.

Swap the order or parameters to compare_patch(), to reduce cognitive complexity; all other logic operates the other way around.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

I don't particular like keeping "result" as a variable name, but nothing better comes to mind.

---
 xen/arch/x86/cpu/microcode/amd.c     | 10 ++++------
 xen/arch/x86/cpu/microcode/core.c    |  5 ++---
 xen/arch/x86/cpu/microcode/intel.c   |  9 ++++-----
 xen/arch/x86/cpu/microcode/private.h | 21 ++++++++++-----------
 4 files changed, 20 insertions(+), 25 deletions(-)
xen/arch/x86/cpu/microcode/amd.c +4 -6
index 3861fec6565a..366c8c59e93a 100644
@@ -170,8 +170,7 @@ static bool check_final_patch_levels(const struct cpu_signature *sig)
     return false;
 }
 
-static enum microcode_match_result compare_revisions(
-    uint32_t old_rev, uint32_t new_rev)
+static int compare_revisions(uint32_t old_rev, uint32_t new_rev)
 {
     if ( new_rev > old_rev )
         return NEW_UCODE;
@@ -199,8 +198,8 @@ static bool microcode_fits_cpu(const struct microcode_patch *patch)
     return equiv.id == patch->processor_rev_id;
 }
 
-static enum microcode_match_result cf_check compare_patch(
-    const struct microcode_patch *new, const struct microcode_patch *old)
+static int cf_check compare_patch(
+    const struct microcode_patch *old, const struct microcode_patch *new)
 {
     /* Both patches to compare are supposed to be applicable to local CPU. */
     ASSERT(microcode_fits_cpu(new));
@@ -212,11 +211,10 @@ static enum microcode_match_result cf_check compare_patch(
 static int cf_check apply_microcode(const struct microcode_patch *patch,
                                     unsigned int flags)
 {
-    int hw_err;
+    int hw_err, result;
     unsigned int cpu = smp_processor_id();
     struct cpu_signature *sig = &per_cpu(cpu_sig, cpu);
     uint32_t rev, old_rev = sig->rev;
-    enum microcode_match_result result;
     bool ucode_force = flags & XENPF_UCODE_FORCE;
 
     if ( !microcode_fits_cpu(patch) )
xen/arch/x86/cpu/microcode/core.c +2 -3
index 0cc5daa251e2..05d0d68d8158 100644
@@ -470,8 +470,7 @@ struct ucode_buf {
 static long cf_check microcode_update_helper(void *data)
 {
     struct microcode_patch *patch = NULL;
-    enum microcode_match_result result;
-    int ret;
+    int ret, result;
     struct ucode_buf *buffer = data;
     unsigned int cpu, updated;
     struct patch_with_flags patch_with_flags;
@@ -527,7 +526,7 @@ static long cf_check microcode_update_helper(void *data)
     spin_lock(&microcode_mutex);
     if ( microcode_cache )
     {
-        result = alternative_call(ucode_ops.compare_patch, patch, microcode_cache);
+        result = alternative_call(ucode_ops.compare_patch, microcode_cache, patch);
 
         if ( result != NEW_UCODE &&
              !(ucode_force && (result == OLD_UCODE || result == SAME_UCODE)) )
xen/arch/x86/cpu/microcode/intel.c +4 -5
index 3f37792ab4b5..9616a5e9db4b 100644
@@ -229,8 +229,7 @@ static int microcode_sanity_check(const struct microcode_patch *patch)
  * Production microcode has a positive revision.  Pre-production microcode has
  * a negative revision.
  */
-static enum microcode_match_result compare_revisions(
-    int32_t old_rev, int32_t new_rev)
+static int compare_revisions(int32_t old_rev, int32_t new_rev)
 {
     if ( new_rev > old_rev )
         return NEW_UCODE;
@@ -270,8 +269,8 @@ static bool microcode_fits_cpu(const struct microcode_patch *mc)
     return false;
 }
 
-static enum microcode_match_result cf_check compare_patch(
-    const struct microcode_patch *new, const struct microcode_patch *old)
+static int cf_check compare_patch(
+    const struct microcode_patch *old, const struct microcode_patch *new)
 {
     /*
      * Both patches to compare are supposed to be applicable to local CPU.
@@ -290,7 +289,7 @@ static int cf_check apply_microcode(const struct microcode_patch *patch,
     unsigned int cpu = smp_processor_id();
     struct cpu_signature *sig = &this_cpu(cpu_sig);
     uint32_t rev, old_rev = sig->rev;
-    enum microcode_match_result result;
+    int result;
     bool ucode_force = flags & XENPF_UCODE_FORCE;
 
     if ( !microcode_fits_cpu(patch) )
xen/arch/x86/cpu/microcode/private.h +10 -11
index c9dd8ba066f9..957d4d4293d0 100644
@@ -5,13 +5,6 @@
 
 #include <asm/microcode.h>
 
-enum microcode_match_result {
-    OLD_UCODE, /* signature matched, but revision id is older */
-    SAME_UCODE, /* signature matched, but revision id is the same */
-    NEW_UCODE, /* signature matched, but revision id is newer */
-    MIS_UCODE, /* signature mismatched */
-};
-
 /* Opaque.  Internals are vendor-specific. */
 struct microcode_patch;
 
@@ -54,11 +47,17 @@ struct microcode_ops {
                            unsigned int flags);
 
     /*
-     * Given two patches, are they both applicable to the current CPU, and is
-     * new a higher revision than old?
+     * Given a current patch, and a proposed new patch, order them based on revision.
+     *
+     * This operation is not necessarily symmetrical.  In some cases, a debug
+     * "new" patch will always considered to be newer, on the expectation that
+     * whomever is using debug patches knows exactly what they're doing.
      */
-    enum microcode_match_result (*compare_patch)(
-        const struct microcode_patch *new, const struct microcode_patch *old);
+#define OLD_UCODE  -1
+#define SAME_UCODE  0
+#define NEW_UCODE   1
+    int (*compare_patch)(const struct microcode_patch *old,
+                         const struct microcode_patch *new);
 
     /*
      * For Linux inird microcode compatibliity.
Signature · 1 line
2.39.5