]> git.proxmox.com Git - mirror_edk2.git/commitdiff
UefiCpuPkg/MicrocodeUpdate: Add MicrocodeUpdate component.
authorJiewen Yao <jiewen.yao@intel.com>
Wed, 21 Sep 2016 03:15:03 +0000 (11:15 +0800)
committerJiewen Yao <jiewen.yao@intel.com>
Tue, 8 Nov 2016 14:43:22 +0000 (22:43 +0800)
MicrocodeUpdate supports update Microcode region via UEFI FMP capsule.

MicrocodeUpdate SetImage() will perform the Microcode version,
ProcessorSignature/ProcessorFlag, and try to load microcode.
If and only if the Microcode is loaded successfully, and new Microcode
will be updated to system flash region.

Cc: Jeff Fan <jeff.fan@intel.com>
Cc: Feng Tian <feng.tian@intel.com>
Cc: Star Zeng <star.zeng@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Chao Zhang <chao.b.zhang@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Jiewen Yao <jiewen.yao@intel.com>
Reviewed-by: Jeff Fan <jeff.fan@intel.com>
Reviewed-by: Michael Kinney <michael.d.kinney@intel.com>
UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeFmp.c [new file with mode: 0644]
UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdate.c [new file with mode: 0644]
UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdate.h [new file with mode: 0644]
UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxe.inf [new file with mode: 0644]
UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxe.uni [new file with mode: 0644]
UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxeExtra.uni [new file with mode: 0644]

diff --git a/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeFmp.c b/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeFmp.c
new file mode 100644 (file)
index 0000000..df3563d
--- /dev/null
@@ -0,0 +1,537 @@
+/** @file\r
+  Produce FMP instance for Microcode.\r
+\r
+  Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>\r
+  This program and the accompanying materials\r
+  are licensed and made available under the terms and conditions of the BSD License\r
+  which accompanies this distribution.  The full text of the license may be found at\r
+  http://opensource.org/licenses/bsd-license.php\r
+\r
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#include "MicrocodeUpdate.h"\r
+\r
+//\r
+// MicrocodeFmp driver private data\r
+//\r
+MICROCODE_FMP_PRIVATE_DATA *mMicrocodeFmpPrivate = NULL;\r
+\r
+EFI_FIRMWARE_MANAGEMENT_PROTOCOL mFirmwareManagementProtocol = {\r
+  FmpGetImageInfo,\r
+  FmpGetImage,\r
+  FmpSetImage,\r
+  FmpCheckImage,\r
+  FmpGetPackageInfo,\r
+  FmpSetPackageInfo\r
+};\r
+\r
+/**\r
+  Initialize Microcode Descriptor.\r
+\r
+  @param[in] MicrocodeFmpPrivate private data structure to be initialized.\r
+\r
+  @return EFI_SUCCESS Microcode Descriptor is initialized.\r
+**/\r
+EFI_STATUS\r
+InitializeMicrocodeDescriptor (\r
+  IN MICROCODE_FMP_PRIVATE_DATA  *MicrocodeFmpPrivate\r
+  );\r
+\r
+/**\r
+  Returns information about the current firmware image(s) of the device.\r
+\r
+  This function allows a copy of the current firmware image to be created and saved.\r
+  The saved copy could later been used, for example, in firmware image recovery or rollback.\r
+\r
+  @param[in]      This               A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in, out] ImageInfoSize      A pointer to the size, in bytes, of the ImageInfo buffer.\r
+                                     On input, this is the size of the buffer allocated by the caller.\r
+                                     On output, it is the size of the buffer returned by the firmware\r
+                                     if the buffer was large enough, or the size of the buffer needed\r
+                                     to contain the image(s) information if the buffer was too small.\r
+  @param[in, out] ImageInfo          A pointer to the buffer in which firmware places the current image(s)\r
+                                     information. The information is an array of EFI_FIRMWARE_IMAGE_DESCRIPTORs.\r
+  @param[out]     DescriptorVersion  A pointer to the location in which firmware returns the version number\r
+                                     associated with the EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out]     DescriptorCount    A pointer to the location in which firmware returns the number of\r
+                                     descriptors or firmware images within this device.\r
+  @param[out]     DescriptorSize     A pointer to the location in which firmware returns the size, in bytes,\r
+                                     of an individual EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out]     PackageVersion     A version number that represents all the firmware images in the device.\r
+                                     The format is vendor specific and new version must have a greater value\r
+                                     than the old version. If PackageVersion is not supported, the value is\r
+                                     0xFFFFFFFF. A value of 0xFFFFFFFE indicates that package version comparison\r
+                                     is to be performed using PackageVersionName. A value of 0xFFFFFFFD indicates\r
+                                     that package version update is in progress.\r
+  @param[out]     PackageVersionName A pointer to a pointer to a null-terminated string representing the\r
+                                     package version name. The buffer is allocated by this function with\r
+                                     AllocatePool(), and it is the caller's responsibility to free it with a call\r
+                                     to FreePool().\r
+\r
+  @retval EFI_SUCCESS                The device was successfully updated with the new image.\r
+  @retval EFI_BUFFER_TOO_SMALL       The ImageInfo buffer was too small. The current buffer size\r
+                                     needed to hold the image(s) information is returned in ImageInfoSize.\r
+  @retval EFI_INVALID_PARAMETER      ImageInfoSize is NULL.\r
+  @retval EFI_DEVICE_ERROR           Valid information could not be returned. Possible corrupted image.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpGetImageInfo (\r
+  IN        EFI_FIRMWARE_MANAGEMENT_PROTOCOL  *This,\r
+  IN OUT    UINTN                             *ImageInfoSize,\r
+  IN OUT    EFI_FIRMWARE_IMAGE_DESCRIPTOR     *ImageInfo,\r
+  OUT       UINT32                            *DescriptorVersion,\r
+  OUT       UINT8                             *DescriptorCount,\r
+  OUT       UINTN                             *DescriptorSize,\r
+  OUT       UINT32                            *PackageVersion,\r
+  OUT       CHAR16                            **PackageVersionName\r
+  )\r
+{\r
+  MICROCODE_FMP_PRIVATE_DATA *MicrocodeFmpPrivate;\r
+  UINTN                      Index;\r
+\r
+  MicrocodeFmpPrivate = MICROCODE_FMP_PRIVATE_DATA_FROM_FMP(This);\r
+\r
+  if(ImageInfoSize == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (*ImageInfoSize < sizeof(EFI_FIRMWARE_IMAGE_DESCRIPTOR) * MicrocodeFmpPrivate->DescriptorCount) {\r
+    *ImageInfoSize = sizeof(EFI_FIRMWARE_IMAGE_DESCRIPTOR) * MicrocodeFmpPrivate->DescriptorCount;\r
+    return EFI_BUFFER_TOO_SMALL;\r
+  }\r
+\r
+  if (ImageInfo == NULL ||\r
+      DescriptorVersion == NULL ||\r
+      DescriptorCount == NULL ||\r
+      DescriptorSize == NULL ||\r
+      PackageVersion == NULL ||\r
+      PackageVersionName == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  *ImageInfoSize      = sizeof(EFI_FIRMWARE_IMAGE_DESCRIPTOR) * MicrocodeFmpPrivate->DescriptorCount;\r
+  *DescriptorSize     = sizeof(EFI_FIRMWARE_IMAGE_DESCRIPTOR);\r
+  *DescriptorCount    = MicrocodeFmpPrivate->DescriptorCount;\r
+  *DescriptorVersion  = EFI_FIRMWARE_IMAGE_DESCRIPTOR_VERSION;\r
+\r
+  //\r
+  // supports 1 ImageInfo descriptor\r
+  //\r
+  CopyMem(&ImageInfo[0], MicrocodeFmpPrivate->ImageDescriptor, sizeof(EFI_FIRMWARE_IMAGE_DESCRIPTOR) * MicrocodeFmpPrivate->DescriptorCount);\r
+  for (Index = 0; Index < MicrocodeFmpPrivate->DescriptorCount; Index++) {\r
+    if ((ImageInfo[Index].AttributesSetting & IMAGE_ATTRIBUTE_IN_USE) != 0) {\r
+      ImageInfo[Index].LastAttemptVersion = MicrocodeFmpPrivate->LastAttempt.LastAttemptVersion;\r
+      ImageInfo[Index].LastAttemptStatus = MicrocodeFmpPrivate->LastAttempt.LastAttemptStatus;\r
+    }\r
+  }\r
+\r
+  //\r
+  // package version\r
+  //\r
+  *PackageVersion = MicrocodeFmpPrivate->PackageVersion;\r
+  if (MicrocodeFmpPrivate->PackageVersionName != NULL) {\r
+    *PackageVersionName = AllocateCopyPool(StrSize(MicrocodeFmpPrivate->PackageVersionName), MicrocodeFmpPrivate->PackageVersionName);\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Retrieves a copy of the current firmware image of the device.\r
+\r
+  This function allows a copy of the current firmware image to be created and saved.\r
+  The saved copy could later been used, for example, in firmware image recovery or rollback.\r
+\r
+  @param[in]     This            A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in]     ImageIndex      A unique number identifying the firmware image(s) within the device.\r
+                                 The number is between 1 and DescriptorCount.\r
+  @param[in,out] Image           Points to the buffer where the current image is copied to.\r
+  @param[in,out] ImageSize       On entry, points to the size of the buffer pointed to by Image, in bytes.\r
+                                 On return, points to the length of the image, in bytes.\r
+\r
+  @retval EFI_SUCCESS            The device was successfully updated with the new image.\r
+  @retval EFI_BUFFER_TOO_SMALL   The buffer specified by ImageSize is too small to hold the\r
+                                 image. The current buffer size needed to hold the image is returned\r
+                                 in ImageSize.\r
+  @retval EFI_INVALID_PARAMETER  The Image was NULL.\r
+  @retval EFI_NOT_FOUND          The current image is not copied to the buffer.\r
+  @retval EFI_UNSUPPORTED        The operation is not supported.\r
+  @retval EFI_SECURITY_VIOLATIO  The operation could not be performed due to an authentication failure.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpGetImage (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL  *This,\r
+  IN  UINT8                             ImageIndex,\r
+  IN  OUT  VOID                         *Image,\r
+  IN  OUT  UINTN                        *ImageSize\r
+  )\r
+{\r
+  MICROCODE_FMP_PRIVATE_DATA *MicrocodeFmpPrivate;\r
+  EFI_STATUS                 Status;\r
+\r
+  if (Image == NULL || ImageSize == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  MicrocodeFmpPrivate = MICROCODE_FMP_PRIVATE_DATA_FROM_FMP(This);\r
+\r
+  if (ImageIndex == 0 || ImageIndex > MicrocodeFmpPrivate->DescriptorCount || ImageSize == NULL || Image == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Status = MicrocodeRead(ImageIndex, (VOID *)Image, ImageSize);\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Updates the firmware image of the device.\r
+\r
+  This function updates the hardware with the new firmware image.\r
+  This function returns EFI_UNSUPPORTED if the firmware image is not updatable.\r
+  If the firmware image is updatable, the function should perform the following minimal validations\r
+  before proceeding to do the firmware image update.\r
+  - Validate the image authentication if image has attribute\r
+    IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED. The function returns\r
+    EFI_SECURITY_VIOLATION if the validation fails.\r
+  - Validate the image is a supported image for this device. The function returns EFI_ABORTED if\r
+    the image is unsupported. The function can optionally provide more detailed information on\r
+    why the image is not a supported image.\r
+  - Validate the data from VendorCode if not null. Image validation must be performed before\r
+    VendorCode data validation. VendorCode data is ignored or considered invalid if image\r
+    validation failed. The function returns EFI_ABORTED if the data is invalid.\r
+\r
+  VendorCode enables vendor to implement vendor-specific firmware image update policy. Null if\r
+  the caller did not specify the policy or use the default policy. As an example, vendor can implement\r
+  a policy to allow an option to force a firmware image update when the abort reason is due to the new\r
+  firmware image version is older than the current firmware image version or bad image checksum.\r
+  Sensitive operations such as those wiping the entire firmware image and render the device to be\r
+  non-functional should be encoded in the image itself rather than passed with the VendorCode.\r
+  AbortReason enables vendor to have the option to provide a more detailed description of the abort\r
+  reason to the caller.\r
+\r
+  @param[in]  This               A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in]  ImageIndex         A unique number identifying the firmware image(s) within the device.\r
+                                 The number is between 1 and DescriptorCount.\r
+  @param[in]  Image              Points to the new image.\r
+  @param[in]  ImageSize          Size of the new image in bytes.\r
+  @param[in]  VendorCode         This enables vendor to implement vendor-specific firmware image update policy.\r
+                                 Null indicates the caller did not specify the policy or use the default policy.\r
+  @param[in]  Progress           A function used by the driver to report the progress of the firmware update.\r
+  @param[out] AbortReason        A pointer to a pointer to a null-terminated string providing more\r
+                                 details for the aborted operation. The buffer is allocated by this function\r
+                                 with AllocatePool(), and it is the caller's responsibility to free it with a\r
+                                 call to FreePool().\r
+\r
+  @retval EFI_SUCCESS            The device was successfully updated with the new image.\r
+  @retval EFI_ABORTED            The operation is aborted.\r
+  @retval EFI_INVALID_PARAMETER  The Image was NULL.\r
+  @retval EFI_UNSUPPORTED        The operation is not supported.\r
+  @retval EFI_SECURITY_VIOLATIO  The operation could not be performed due to an authentication failure.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpSetImage (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL                 *This,\r
+  IN  UINT8                                            ImageIndex,\r
+  IN  CONST VOID                                       *Image,\r
+  IN  UINTN                                            ImageSize,\r
+  IN  CONST VOID                                       *VendorCode,\r
+  IN  EFI_FIRMWARE_MANAGEMENT_UPDATE_IMAGE_PROGRESS    Progress,\r
+  OUT CHAR16                                           **AbortReason\r
+  )\r
+{\r
+  EFI_STATUS                 Status;\r
+  EFI_STATUS                 VarStatus;\r
+  MICROCODE_FMP_PRIVATE_DATA *MicrocodeFmpPrivate;\r
+\r
+  if (Image == NULL || AbortReason == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  MicrocodeFmpPrivate = MICROCODE_FMP_PRIVATE_DATA_FROM_FMP(This);\r
+  *AbortReason     = NULL;\r
+\r
+  if (ImageIndex == 0 || ImageIndex > MicrocodeFmpPrivate->DescriptorCount || Image == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Status = MicrocodeWrite(ImageIndex, (VOID *)Image, ImageSize, &MicrocodeFmpPrivate->LastAttempt.LastAttemptVersion, &MicrocodeFmpPrivate->LastAttempt.LastAttemptStatus, AbortReason);\r
+  DEBUG((DEBUG_INFO, "SetImage - LastAttemp Version - 0x%x, State - 0x%x\n", MicrocodeFmpPrivate->LastAttempt.LastAttemptVersion, MicrocodeFmpPrivate->LastAttempt.LastAttemptStatus));\r
+  VarStatus = gRT->SetVariable(\r
+                     MICROCODE_FMP_LAST_ATTEMPT_VARIABLE_NAME,\r
+                     &gEfiCallerIdGuid,\r
+                     EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,\r
+                     sizeof(MicrocodeFmpPrivate->LastAttempt),\r
+                     &MicrocodeFmpPrivate->LastAttempt\r
+                     );\r
+  DEBUG((DEBUG_INFO, "SetLastAttemp - %r\n", VarStatus));\r
+\r
+  if (!EFI_ERROR(Status)) {\r
+    InitializeMicrocodeDescriptor(MicrocodeFmpPrivate);\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Checks if the firmware image is valid for the device.\r
+\r
+  This function allows firmware update application to validate the firmware image without\r
+  invoking the SetImage() first.\r
+\r
+  @param[in]  This               A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in]  ImageIndex         A unique number identifying the firmware image(s) within the device.\r
+                                 The number is between 1 and DescriptorCount.\r
+  @param[in]  Image              Points to the new image.\r
+  @param[in]  ImageSize          Size of the new image in bytes.\r
+  @param[out] ImageUpdatable     Indicates if the new image is valid for update. It also provides,\r
+                                 if available, additional information if the image is invalid.\r
+\r
+  @retval EFI_SUCCESS            The image was successfully checked.\r
+  @retval EFI_INVALID_PARAMETER  The Image was NULL.\r
+  @retval EFI_UNSUPPORTED        The operation is not supported.\r
+  @retval EFI_SECURITY_VIOLATIO  The operation could not be performed due to an authentication failure.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpCheckImage (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL  *This,\r
+  IN  UINT8                             ImageIndex,\r
+  IN  CONST VOID                        *Image,\r
+  IN  UINTN                             ImageSize,\r
+  OUT UINT32                            *ImageUpdatable\r
+  )\r
+{\r
+  return EFI_UNSUPPORTED;\r
+}\r
+\r
+/**\r
+  Returns information about the firmware package.\r
+\r
+  This function returns package information.\r
+\r
+  @param[in]  This                     A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[out] PackageVersion           A version number that represents all the firmware images in the device.\r
+                                       The format is vendor specific and new version must have a greater value\r
+                                       than the old version. If PackageVersion is not supported, the value is\r
+                                       0xFFFFFFFF. A value of 0xFFFFFFFE indicates that package version\r
+                                       comparison is to be performed using PackageVersionName. A value of\r
+                                       0xFFFFFFFD indicates that package version update is in progress.\r
+  @param[out] PackageVersionName       A pointer to a pointer to a null-terminated string representing\r
+                                       the package version name. The buffer is allocated by this function with\r
+                                       AllocatePool(), and it is the caller's responsibility to free it with a\r
+                                       call to FreePool().\r
+  @param[out] PackageVersionNameMaxLen The maximum length of package version name if device supports update of\r
+                                       package version name. A value of 0 indicates the device does not support\r
+                                       update of package version name. Length is the number of Unicode characters,\r
+                                       including the terminating null character.\r
+  @param[out] AttributesSupported      Package attributes that are supported by this device. See 'Package Attribute\r
+                                       Definitions' for possible returned values of this parameter. A value of 1\r
+                                       indicates the attribute is supported and the current setting value is\r
+                                       indicated in AttributesSetting. A value of 0 indicates the attribute is not\r
+                                       supported and the current setting value in AttributesSetting is meaningless.\r
+  @param[out] AttributesSetting        Package attributes. See 'Package Attribute Definitions' for possible returned\r
+                                       values of this parameter\r
+\r
+  @retval EFI_SUCCESS                  The package information was successfully returned.\r
+  @retval EFI_UNSUPPORTED              The operation is not supported.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpGetPackageInfo (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL *This,\r
+  OUT UINT32                           *PackageVersion,\r
+  OUT CHAR16                           **PackageVersionName,\r
+  OUT UINT32                           *PackageVersionNameMaxLen,\r
+  OUT UINT64                           *AttributesSupported,\r
+  OUT UINT64                           *AttributesSetting\r
+  )\r
+{\r
+  return EFI_UNSUPPORTED;\r
+}\r
+\r
+/**\r
+  Updates information about the firmware package.\r
+\r
+  This function updates package information.\r
+  This function returns EFI_UNSUPPORTED if the package information is not updatable.\r
+  VendorCode enables vendor to implement vendor-specific package information update policy.\r
+  Null if the caller did not specify this policy or use the default policy.\r
+\r
+  @param[in]  This               A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in]  Image              Points to the authentication image.\r
+                                 Null if authentication is not required.\r
+  @param[in]  ImageSize          Size of the authentication image in bytes.\r
+                                 0 if authentication is not required.\r
+  @param[in]  VendorCode         This enables vendor to implement vendor-specific firmware\r
+                                 image update policy.\r
+                                 Null indicates the caller did not specify this policy or use\r
+                                 the default policy.\r
+  @param[in]  PackageVersion     The new package version.\r
+  @param[in]  PackageVersionName A pointer to the new null-terminated Unicode string representing\r
+                                 the package version name.\r
+                                 The string length is equal to or less than the value returned in\r
+                                 PackageVersionNameMaxLen.\r
+\r
+  @retval EFI_SUCCESS            The device was successfully updated with the new package\r
+                                 information.\r
+  @retval EFI_INVALID_PARAMETER  The PackageVersionName length is longer than the value\r
+                                 returned in PackageVersionNameMaxLen.\r
+  @retval EFI_UNSUPPORTED        The operation is not supported.\r
+  @retval EFI_SECURITY_VIOLATIO  The operation could not be performed due to an authentication failure.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpSetPackageInfo (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL   *This,\r
+  IN  CONST VOID                         *Image,\r
+  IN  UINTN                              ImageSize,\r
+  IN  CONST VOID                         *VendorCode,\r
+  IN  UINT32                             PackageVersion,\r
+  IN  CONST CHAR16                       *PackageVersionName\r
+  )\r
+{\r
+  return EFI_UNSUPPORTED;\r
+}\r
+\r
+/**\r
+  Initialize Microcode Descriptor.\r
+\r
+  @param[in] MicrocodeFmpPrivate private data structure to be initialized.\r
+\r
+  @return EFI_SUCCESS Microcode Descriptor is initialized.\r
+**/\r
+EFI_STATUS\r
+InitializeMicrocodeDescriptor (\r
+  IN MICROCODE_FMP_PRIVATE_DATA *MicrocodeFmpPrivate\r
+  )\r
+{\r
+  UINT8  CurrentMicrocodeCount;\r
+\r
+  CurrentMicrocodeCount = (UINT8)GetMicrocodeInfo(NULL, 0);\r
+\r
+  if (CurrentMicrocodeCount > MicrocodeFmpPrivate->DescriptorCount) {\r
+    if (MicrocodeFmpPrivate->ImageDescriptor != NULL) {\r
+      FreePool(MicrocodeFmpPrivate->ImageDescriptor);\r
+      MicrocodeFmpPrivate->ImageDescriptor = NULL;\r
+    }\r
+  } else {\r
+    ZeroMem(MicrocodeFmpPrivate->ImageDescriptor, MicrocodeFmpPrivate->DescriptorCount * sizeof(EFI_FIRMWARE_IMAGE_DESCRIPTOR));\r
+  }\r
+\r
+  MicrocodeFmpPrivate->DescriptorCount = CurrentMicrocodeCount;\r
+\r
+  if (MicrocodeFmpPrivate->ImageDescriptor == NULL) {\r
+    MicrocodeFmpPrivate->ImageDescriptor = AllocateZeroPool(MicrocodeFmpPrivate->DescriptorCount * sizeof(EFI_FIRMWARE_IMAGE_DESCRIPTOR));\r
+    if (MicrocodeFmpPrivate->ImageDescriptor == NULL) {\r
+      return EFI_OUT_OF_RESOURCES;\r
+    }\r
+  }\r
+\r
+  CurrentMicrocodeCount = (UINT8)GetMicrocodeInfo(MicrocodeFmpPrivate->ImageDescriptor, MicrocodeFmpPrivate->DescriptorCount);\r
+  ASSERT(CurrentMicrocodeCount == MicrocodeFmpPrivate->DescriptorCount);\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Initialize MicrocodeFmpDriver private data structure.\r
+\r
+  @param[in] MicrocodeFmpPrivate private data structure to be initialized.\r
+\r
+  @return EFI_SUCCESS private data is initialized.\r
+**/\r
+EFI_STATUS\r
+InitializePrivateData (\r
+  IN MICROCODE_FMP_PRIVATE_DATA  *MicrocodeFmpPrivate\r
+  )\r
+{\r
+  EFI_STATUS       Status;\r
+  EFI_STATUS       VarStatus;\r
+  UINTN            VarSize;\r
+\r
+  MicrocodeFmpPrivate->Signature       = MICROCODE_FMP_PRIVATE_DATA_SIGNATURE;\r
+  MicrocodeFmpPrivate->Handle          = NULL;\r
+  CopyMem(&MicrocodeFmpPrivate->Fmp, &mFirmwareManagementProtocol, sizeof(EFI_FIRMWARE_MANAGEMENT_PROTOCOL));\r
+\r
+  MicrocodeFmpPrivate->PackageVersion = 0x1;\r
+  MicrocodeFmpPrivate->PackageVersionName = L"Microcode";\r
+\r
+  MicrocodeFmpPrivate->LastAttempt.LastAttemptVersion = 0x0;\r
+  MicrocodeFmpPrivate->LastAttempt.LastAttemptStatus = 0x0;\r
+  VarSize = sizeof(MicrocodeFmpPrivate->LastAttempt);\r
+  VarStatus = gRT->GetVariable(\r
+                     MICROCODE_FMP_LAST_ATTEMPT_VARIABLE_NAME,\r
+                     &gEfiCallerIdGuid,\r
+                     NULL,\r
+                     &VarSize,\r
+                     &MicrocodeFmpPrivate->LastAttempt\r
+                     );\r
+  DEBUG((DEBUG_INFO, "GetLastAttemp - %r\n", VarStatus));\r
+  DEBUG((DEBUG_INFO, "GetLastAttemp Version - 0x%x, State - 0x%x\n", MicrocodeFmpPrivate->LastAttempt.LastAttemptVersion, MicrocodeFmpPrivate->LastAttempt.LastAttemptStatus));\r
+\r
+  Status = InitializeMicrocodeDescriptor(MicrocodeFmpPrivate);\r
+\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Microcode FMP module entrypoint\r
+\r
+  @param[in]  ImageHandle       The firmware allocated handle for the EFI image.\r
+  @param[in]  SystemTable       A pointer to the EFI System Table.\r
+\r
+  @return EFI_SUCCESS Microcode FMP module is initialized.\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MicrocodeFmpMain (\r
+  IN EFI_HANDLE                         ImageHandle,\r
+  IN EFI_SYSTEM_TABLE                   *SystemTable\r
+  )\r
+{\r
+  EFI_STATUS                            Status;\r
+\r
+  //\r
+  // Initialize MicrocodeFmpPrivateData\r
+  //\r
+  mMicrocodeFmpPrivate = AllocateZeroPool (sizeof(MICROCODE_FMP_PRIVATE_DATA));\r
+  if (mMicrocodeFmpPrivate == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  Status = InitializePrivateData(mMicrocodeFmpPrivate);\r
+  if (EFI_ERROR(Status)) {\r
+    FreePool(mMicrocodeFmpPrivate);\r
+    mMicrocodeFmpPrivate = NULL;\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Install FMP protocol.\r
+  //\r
+  Status = gBS->InstallProtocolInterface (\r
+                  &mMicrocodeFmpPrivate->Handle,\r
+                  &gEfiFirmwareManagementProtocolGuid,\r
+                  EFI_NATIVE_INTERFACE,\r
+                  &mMicrocodeFmpPrivate->Fmp\r
+                  );\r
+  if (EFI_ERROR (Status)) {\r
+    FreePool(mMicrocodeFmpPrivate);\r
+    mMicrocodeFmpPrivate = NULL;\r
+    return Status;\r
+  }\r
+\r
+  return Status;\r
+}\r
diff --git a/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdate.c b/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdate.c
new file mode 100644 (file)
index 0000000..2b2d3ac
--- /dev/null
@@ -0,0 +1,784 @@
+/** @file\r
+  SetImage instance to update Microcode.\r
+\r
+  Caution: This module requires additional review when modified.\r
+  This module will have external input - capsule image.\r
+  This external input must be validated carefully to avoid security issue like\r
+  buffer overflow, integer overflow.\r
+\r
+  MicrocodeWrite() and VerifyMicrocode() will receive untrusted input and do basic validation.\r
+\r
+  Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>\r
+  This program and the accompanying materials\r
+  are licensed and made available under the terms and conditions of the BSD License\r
+  which accompanies this distribution.  The full text of the license may be found at\r
+  http://opensource.org/licenses/bsd-license.php\r
+\r
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#include "MicrocodeUpdate.h"\r
+\r
+/**\r
+  Get Microcode Region.\r
+\r
+  @param[out] MicrocodePatchAddress      The address of Microcode\r
+  @param[out] MicrocodePatchRegionSize   The region size of Microcode\r
+\r
+  @retval TRUE   The Microcode region is returned.\r
+  @retval FALSE  No Microcode region.\r
+**/\r
+BOOLEAN\r
+GetMicrocodeRegion (\r
+  OUT UINT64   *MicrocodePatchAddress,\r
+  OUT UINT64   *MicrocodePatchRegionSize\r
+  )\r
+{\r
+  *MicrocodePatchAddress = PcdGet64(PcdCpuMicrocodePatchAddress);\r
+  *MicrocodePatchRegionSize = PcdGet64(PcdCpuMicrocodePatchRegionSize);\r
+\r
+  if ((*MicrocodePatchAddress == 0) || (*MicrocodePatchRegionSize == 0)) {\r
+    return FALSE;\r
+  }\r
+\r
+  return TRUE;\r
+}\r
+\r
+/**\r
+  Get Microcode update signature of currently loaded Microcode update.\r
+\r
+  @return  Microcode signature.\r
+\r
+**/\r
+UINT32\r
+GetCurrentMicrocodeSignature (\r
+  VOID\r
+  )\r
+{\r
+  UINT64 Signature;\r
+\r
+  AsmWriteMsr64(MSR_IA32_BIOS_SIGN_ID, 0);\r
+  AsmCpuid(CPUID_VERSION_INFO, NULL, NULL, NULL, NULL);\r
+  Signature = AsmReadMsr64(MSR_IA32_BIOS_SIGN_ID);\r
+  return (UINT32)RShiftU64(Signature, 32);\r
+}\r
+\r
+/**\r
+  Get current processor signature.\r
+\r
+  @return current processor signature.\r
+**/\r
+UINT32\r
+GetCurrentProcessorSignature (\r
+  VOID\r
+  )\r
+{\r
+  UINT32                                  RegEax;\r
+  AsmCpuid(CPUID_VERSION_INFO, &RegEax, NULL, NULL, NULL);\r
+  return RegEax;\r
+}\r
+\r
+/**\r
+  Get current platform ID.\r
+\r
+  @return current platform ID.\r
+**/\r
+UINT8\r
+GetCurrentPlatformId (\r
+  VOID\r
+  )\r
+{\r
+  UINT8                                   PlatformId;\r
+\r
+  PlatformId = (UINT8)AsmMsrBitFieldRead64(MSR_IA32_PLATFORM_ID, 50, 52);\r
+  return PlatformId;\r
+}\r
+\r
+/**\r
+  Load new Microcode.\r
+\r
+  @param[in] Address  The address of new Microcode.\r
+\r
+  @return  Loaded Microcode signature.\r
+\r
+**/\r
+UINT32\r
+LoadMicrocode (\r
+  IN UINT64  Address\r
+  )\r
+{\r
+  AsmWriteMsr64(MSR_IA32_BIOS_UPDT_TRIG, Address);\r
+  return GetCurrentMicrocodeSignature();\r
+}\r
+\r
+/**\r
+  Get current Microcode information.\r
+\r
+  @param[out]  ImageDescriptor  Microcode ImageDescriptor\r
+  @param[in]   DescriptorCount  The count of Microcode ImageDescriptor allocated.\r
+\r
+  @return Microcode count\r
+**/\r
+UINTN\r
+GetMicrocodeInfo (\r
+  OUT EFI_FIRMWARE_IMAGE_DESCRIPTOR  *ImageDescriptor, OPTIONAL\r
+  IN  UINTN                          DescriptorCount   OPTIONAL\r
+  )\r
+{\r
+  BOOLEAN                                 Result;\r
+  UINT64                                  MicrocodePatchAddress;\r
+  UINT64                                  MicrocodePatchRegionSize;\r
+  CPU_MICROCODE_HEADER                    *MicrocodeEntryPoint;\r
+  UINTN                                   MicrocodeEnd;\r
+  UINTN                                   TotalSize;\r
+  UINTN                                   Count;\r
+  UINT64                                  ImageAttributes;\r
+  UINT32                                  CurrentRevision;\r
+\r
+  Result = GetMicrocodeRegion(&MicrocodePatchAddress, &MicrocodePatchRegionSize);\r
+  if (!Result) {\r
+    DEBUG((DEBUG_ERROR, "Fail to get Microcode Region\n"));\r
+    return 0;\r
+  }\r
+  DEBUG((DEBUG_INFO, "Microcode Region - 0x%lx - 0x%lx\n", MicrocodePatchAddress, MicrocodePatchRegionSize));\r
+\r
+  Count = 0;\r
+  CurrentRevision = GetCurrentMicrocodeSignature();\r
+\r
+  MicrocodeEnd = (UINTN)(MicrocodePatchAddress + MicrocodePatchRegionSize);\r
+  MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (UINTN) MicrocodePatchAddress;\r
+  do {\r
+    if (MicrocodeEntryPoint->HeaderVersion == 0x1 && MicrocodeEntryPoint->LoaderRevision == 0x1) {\r
+      //\r
+      // It is the microcode header. It is not the padding data between microcode patches\r
+      // becasue the padding data should not include 0x00000001 and it should be the repeated\r
+      // byte format (like 0xXYXYXYXY....).\r
+      //\r
+      if (MicrocodeEntryPoint->DataSize == 0) {\r
+        TotalSize = 2048;\r
+      } else {\r
+        TotalSize = MicrocodeEntryPoint->TotalSize;\r
+      }\r
+\r
+      if (ImageDescriptor != NULL && DescriptorCount > Count) {\r
+        ImageDescriptor[Count].ImageIndex = (UINT8)(Count + 1);\r
+        CopyGuid (&ImageDescriptor[Count].ImageTypeId, &gMicrocodeFmpImageTypeIdGuid);\r
+        ImageDescriptor[Count].ImageId = LShiftU64(MicrocodeEntryPoint->ProcessorFlags, 32) + MicrocodeEntryPoint->ProcessorSignature.Uint32;\r
+        ImageDescriptor[Count].ImageIdName = NULL;\r
+        ImageDescriptor[Count].Version = MicrocodeEntryPoint->UpdateRevision;\r
+        ImageDescriptor[Count].VersionName = NULL;\r
+        ImageDescriptor[Count].Size = TotalSize;\r
+        ImageAttributes = IMAGE_ATTRIBUTE_IMAGE_UPDATABLE | IMAGE_ATTRIBUTE_RESET_REQUIRED;\r
+        if (CurrentRevision == MicrocodeEntryPoint->UpdateRevision) {\r
+          ImageAttributes |= IMAGE_ATTRIBUTE_IN_USE;\r
+        }\r
+        ImageDescriptor[Count].AttributesSupported = ImageAttributes | IMAGE_ATTRIBUTE_IN_USE;\r
+        ImageDescriptor[Count].AttributesSetting = ImageAttributes;\r
+        ImageDescriptor[Count].Compatibilities = 0;\r
+        ImageDescriptor[Count].LowestSupportedImageVersion = MicrocodeEntryPoint->UpdateRevision; // do not support rollback\r
+        ImageDescriptor[Count].LastAttemptVersion = 0;\r
+        ImageDescriptor[Count].LastAttemptStatus = 0;\r
+        ImageDescriptor[Count].HardwareInstance = 0;\r
+      }\r
+    } else {\r
+      //\r
+      // It is the padding data between the microcode patches for microcode patches alignment.\r
+      // Because the microcode patch is the multiple of 1-KByte, the padding data should not\r
+      // exist if the microcode patch alignment value is not larger than 1-KByte. So, the microcode\r
+      // alignment value should be larger than 1-KByte. We could skip SIZE_1KB padding data to\r
+      // find the next possible microcode patch header.\r
+      //\r
+      MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + SIZE_1KB);\r
+      continue;\r
+    }\r
+\r
+    Count++;\r
+    ASSERT(Count < 0xFF);\r
+\r
+    //\r
+    // Get the next patch.\r
+    //\r
+    MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + TotalSize);\r
+  } while (((UINTN) MicrocodeEntryPoint < MicrocodeEnd));\r
+\r
+  return Count;\r
+}\r
+\r
+/**\r
+  Read Microcode.\r
+\r
+  @param[in]       ImageIndex The index of Microcode image.\r
+  @param[in, out]  Image      The Microcode image buffer.\r
+  @param[in, out]  ImageSize  The size of Microcode image buffer in bytes.\r
+\r
+  @retval EFI_SUCCESS    The Microcode image is read.\r
+  @retval EFI_NOT_FOUND  The Microcode image is not found.\r
+**/\r
+EFI_STATUS\r
+MicrocodeRead (\r
+  IN UINTN      ImageIndex,\r
+  IN OUT VOID   *Image,\r
+  IN OUT UINTN  *ImageSize\r
+  )\r
+{\r
+  BOOLEAN                                 Result;\r
+  UINT64                                  MicrocodePatchAddress;\r
+  UINT64                                  MicrocodePatchRegionSize;\r
+  CPU_MICROCODE_HEADER                    *MicrocodeEntryPoint;\r
+  UINTN                                   MicrocodeEnd;\r
+  UINTN                                   TotalSize;\r
+  UINTN                                   Count;\r
+\r
+  Result = GetMicrocodeRegion(&MicrocodePatchAddress, &MicrocodePatchRegionSize);\r
+  if (!Result) {\r
+    DEBUG((DEBUG_ERROR, "Fail to get Microcode Region\n"));\r
+    return EFI_NOT_FOUND;\r
+  }\r
+  DEBUG((DEBUG_INFO, "Microcode Region - 0x%lx - 0x%lx\n", MicrocodePatchAddress, MicrocodePatchRegionSize));\r
+\r
+  Count = 0;\r
+\r
+  MicrocodeEnd = (UINTN)(MicrocodePatchAddress + MicrocodePatchRegionSize);\r
+  MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(UINTN)MicrocodePatchAddress;\r
+  do {\r
+    if (MicrocodeEntryPoint->HeaderVersion == 0x1 && MicrocodeEntryPoint->LoaderRevision == 0x1) {\r
+      //\r
+      // It is the microcode header. It is not the padding data between microcode patches\r
+      // becasue the padding data should not include 0x00000001 and it should be the repeated\r
+      // byte format (like 0xXYXYXYXY....).\r
+      //\r
+      if (MicrocodeEntryPoint->DataSize == 0) {\r
+        TotalSize = 2048;\r
+      } else {\r
+        TotalSize = MicrocodeEntryPoint->TotalSize;\r
+      }\r
+\r
+    } else {\r
+      //\r
+      // It is the padding data between the microcode patches for microcode patches alignment.\r
+      // Because the microcode patch is the multiple of 1-KByte, the padding data should not\r
+      // exist if the microcode patch alignment value is not larger than 1-KByte. So, the microcode\r
+      // alignment value should be larger than 1-KByte. We could skip SIZE_1KB padding data to\r
+      // find the next possible microcode patch header.\r
+      //\r
+      MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(((UINTN)MicrocodeEntryPoint) + SIZE_1KB);\r
+      continue;\r
+    }\r
+\r
+    Count++;\r
+    ASSERT(Count < 0xFF);\r
+\r
+    //\r
+    // Get the next patch.\r
+    //\r
+    MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(((UINTN)MicrocodeEntryPoint) + TotalSize);\r
+  } while (((UINTN)MicrocodeEntryPoint < MicrocodeEnd));\r
+\r
+  return EFI_NOT_FOUND;\r
+}\r
+\r
+/**\r
+  Verify Microcode.\r
+\r
+  Caution: This function may receive untrusted input.\r
+\r
+  @param[in]  Image              The Microcode image buffer.\r
+  @param[in]  ImageSize          The size of Microcode image buffer in bytes.\r
+  @param[in]  TryLoad            Try to load Microcode or not.\r
+  @param[out] LastAttemptStatus  The last attempt status, which will be recorded in ESRT and FMP EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out] AbortReason        A pointer to a pointer to a null-terminated string providing more\r
+                                 details for the aborted operation. The buffer is allocated by this function\r
+                                 with AllocatePool(), and it is the caller's responsibility to free it with a\r
+                                 call to FreePool().\r
+\r
+  @retval EFI_SUCCESS               The Microcode image passes verification.\r
+  @retval EFI_VOLUME_CORRUPTED      The Microcode image is corrupt.\r
+  @retval EFI_INCOMPATIBLE_VERSION  The Microcode image version is incorrect.\r
+  @retval EFI_UNSUPPORTED           The Microcode ProcessorSignature or ProcessorFlags is incorrect.\r
+  @retval EFI_SECURITY_VIOLATION    The Microcode image fails to load.\r
+**/\r
+EFI_STATUS\r
+VerifyMicrocode (\r
+  IN VOID    *Image,\r
+  IN UINTN   ImageSize,\r
+  IN BOOLEAN TryLoad,\r
+  OUT UINT32 *LastAttemptStatus,\r
+  OUT CHAR16 **AbortReason\r
+  )\r
+{\r
+  UINTN                                   Index;\r
+  CPU_MICROCODE_HEADER                    *MicrocodeEntryPoint;\r
+  UINTN                                   TotalSize;\r
+  UINTN                                   DataSize;\r
+  UINT32                                  CurrentRevision;\r
+  UINT32                                  CurrentProcessorSignature;\r
+  UINT8                                   CurrentPlatformId;\r
+  UINT32                                  CheckSum32;\r
+  UINTN                                   ExtendedTableLength;\r
+  UINT32                                  ExtendedTableCount;\r
+  CPU_MICROCODE_EXTENDED_TABLE            *ExtendedTable;\r
+  CPU_MICROCODE_EXTENDED_TABLE_HEADER     *ExtendedTableHeader;\r
+  BOOLEAN                                 CorrectMicrocode;\r
+\r
+  //\r
+  // Check HeaderVersion\r
+  //\r
+  MicrocodeEntryPoint = Image;\r
+  if (MicrocodeEntryPoint->HeaderVersion != 0x1) {\r
+    DEBUG((DEBUG_ERROR, "VerifyMicrocode - fail on HeaderVersion\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;\r
+    if (AbortReason != NULL) {\r
+      *AbortReason = AllocateCopyPool(sizeof(L"InvalidHeaderVersion"), L"InvalidHeaderVersion");\r
+    }\r
+    return EFI_INCOMPATIBLE_VERSION;\r
+  }\r
+  //\r
+  // Check LoaderRevision\r
+  //\r
+  if (MicrocodeEntryPoint->LoaderRevision != 0x1) {\r
+    DEBUG((DEBUG_ERROR, "VerifyMicrocode - fail on LoaderRevision\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;\r
+    if (AbortReason != NULL) {\r
+      *AbortReason = AllocateCopyPool(sizeof(L"InvalidLoaderVersion"), L"InvalidLoaderVersion");\r
+    }\r
+    return EFI_INCOMPATIBLE_VERSION;\r
+  }\r
+  //\r
+  // Check Size\r
+  //\r
+  if (MicrocodeEntryPoint->DataSize == 0) {\r
+    TotalSize = 2048;\r
+  } else {\r
+    TotalSize = MicrocodeEntryPoint->TotalSize;\r
+  }\r
+  if (TotalSize <= sizeof(CPU_MICROCODE_HEADER)) {\r
+    DEBUG((DEBUG_ERROR, "VerifyMicrocode - TotalSize too small\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;\r
+    if (AbortReason != NULL) {\r
+      *AbortReason = AllocateCopyPool(sizeof(L"InvalidTotalSize"), L"InvalidTotalSize");\r
+    }\r
+    return EFI_VOLUME_CORRUPTED;\r
+  }\r
+  if (TotalSize != ImageSize) {\r
+    DEBUG((DEBUG_ERROR, "VerifyMicrocode - fail on TotalSize\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;\r
+    if (AbortReason != NULL) {\r
+      *AbortReason = AllocateCopyPool(sizeof(L"InvalidTotalSize"), L"InvalidTotalSize");\r
+    }\r
+    return EFI_VOLUME_CORRUPTED;\r
+  }\r
+  //\r
+  // Check CheckSum32\r
+  //\r
+  if (MicrocodeEntryPoint->DataSize == 0) {\r
+    DataSize = 2048 - sizeof(CPU_MICROCODE_HEADER);\r
+  } else {\r
+    DataSize = MicrocodeEntryPoint->DataSize;\r
+  }\r
+  if (DataSize > TotalSize - sizeof(CPU_MICROCODE_HEADER)) {\r
+    DEBUG((DEBUG_ERROR, "VerifyMicrocode - DataSize too big\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;\r
+    if (AbortReason != NULL) {\r
+      *AbortReason = AllocateCopyPool(sizeof(L"InvalidDataSize"), L"InvalidDataSize");\r
+    }\r
+    return EFI_VOLUME_CORRUPTED;\r
+  }\r
+  if ((DataSize & 0x3) != 0) {\r
+    DEBUG((DEBUG_ERROR, "VerifyMicrocode - DataSize not aligned\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;\r
+    if (AbortReason != NULL) {\r
+      *AbortReason = AllocateCopyPool(sizeof(L"InvalidDataSize"), L"InvalidDataSize");\r
+    }\r
+    return EFI_VOLUME_CORRUPTED;\r
+  }\r
+  CheckSum32 = CalculateSum32((UINT32 *)MicrocodeEntryPoint, DataSize + sizeof(CPU_MICROCODE_HEADER));\r
+  if (CheckSum32 != 0) {\r
+    DEBUG((DEBUG_ERROR, "VerifyMicrocode - fail on CheckSum32\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;\r
+    if (AbortReason != NULL) {\r
+      *AbortReason = AllocateCopyPool(sizeof(L"InvalidChecksum"), L"InvalidChecksum");\r
+    }\r
+    return EFI_VOLUME_CORRUPTED;\r
+  }\r
+\r
+  //\r
+  // Check ProcessorSignature/ProcessorFlags\r
+  //\r
+  CorrectMicrocode = FALSE;\r
+  CurrentProcessorSignature = GetCurrentProcessorSignature();\r
+  CurrentPlatformId = GetCurrentPlatformId();\r
+  if ((MicrocodeEntryPoint->ProcessorSignature.Uint32 != CurrentProcessorSignature) ||\r
+      ((MicrocodeEntryPoint->ProcessorFlags & (1 << CurrentPlatformId)) == 0)) {\r
+    ExtendedTableLength = TotalSize - (DataSize + sizeof(CPU_MICROCODE_HEADER));\r
+    if (ExtendedTableLength != 0) {\r
+      //\r
+      // Extended Table exist, check if the CPU in support list\r
+      //\r
+      ExtendedTableHeader = (CPU_MICROCODE_EXTENDED_TABLE_HEADER *)((UINT8 *)(MicrocodeEntryPoint) + DataSize + sizeof(CPU_MICROCODE_HEADER));\r
+      //\r
+      // Calculate Extended Checksum\r
+      //\r
+      if ((ExtendedTableLength > sizeof(CPU_MICROCODE_EXTENDED_TABLE_HEADER)) && ((ExtendedTableLength & 0x3) != 0)) {\r
+        CheckSum32 = CalculateSum32((UINT32 *)ExtendedTableHeader, ExtendedTableLength);\r
+        if (CheckSum32 == 0) {\r
+          //\r
+          // Checksum correct\r
+          //\r
+          ExtendedTableCount = ExtendedTableHeader->ExtendedSignatureCount;\r
+          if (ExtendedTableCount <= (ExtendedTableLength - sizeof(CPU_MICROCODE_EXTENDED_TABLE_HEADER)) / sizeof(CPU_MICROCODE_EXTENDED_TABLE)) {\r
+            ExtendedTable = (CPU_MICROCODE_EXTENDED_TABLE *)(ExtendedTableHeader + 1);\r
+            for (Index = 0; Index < ExtendedTableCount; Index++) {\r
+              CheckSum32 = CalculateSum32((UINT32 *)ExtendedTable, sizeof(CPU_MICROCODE_EXTENDED_TABLE));\r
+              if (CheckSum32 == 0) {\r
+                //\r
+                // Verify Header\r
+                //\r
+                if ((ExtendedTable->ProcessorSignature.Uint32 == CurrentProcessorSignature) &&\r
+                    (ExtendedTable->ProcessorFlag & (1 << CurrentPlatformId))) {\r
+                  //\r
+                  // Find one\r
+                  //\r
+                  CorrectMicrocode = TRUE;\r
+                  break;\r
+                }\r
+              }\r
+              ExtendedTable++;\r
+            }\r
+          }\r
+        }\r
+      }\r
+    }\r
+    if (!CorrectMicrocode) {\r
+      DEBUG((DEBUG_ERROR, "VerifyMicrocode - fail on CurrentProcessorSignature/ProcessorFlags\n"));\r
+      *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INCORRECT_VERSION;\r
+      if (AbortReason != NULL) {\r
+        if (MicrocodeEntryPoint->ProcessorSignature.Uint32 != CurrentProcessorSignature) {\r
+          *AbortReason = AllocateCopyPool(sizeof(L"UnsupportedProcessSignature"), L"UnsupportedProcessSignature");\r
+        } else {\r
+          *AbortReason = AllocateCopyPool(sizeof(L"UnsupportedProcessorFlags"), L"UnsupportedProcessorFlags");\r
+        }\r
+      }\r
+      return EFI_UNSUPPORTED;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Check UpdateRevision\r
+  //\r
+  CurrentRevision = GetCurrentMicrocodeSignature();\r
+  if (MicrocodeEntryPoint->UpdateRevision < CurrentRevision) {\r
+    DEBUG((DEBUG_ERROR, "VerifyMicrocode - fail on UpdateRevision\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INCORRECT_VERSION;\r
+    if (AbortReason != NULL) {\r
+      *AbortReason = AllocateCopyPool(sizeof(L"IncorrectRevision"), L"IncorrectRevision");\r
+    }\r
+    return EFI_INCOMPATIBLE_VERSION;\r
+  }\r
+\r
+  //\r
+  // try load MCU\r
+  //\r
+  if (TryLoad) {\r
+    CurrentRevision = LoadMicrocode((UINTN)MicrocodeEntryPoint + sizeof(CPU_MICROCODE_HEADER));\r
+    if (MicrocodeEntryPoint->UpdateRevision != CurrentRevision) {\r
+      DEBUG((DEBUG_ERROR, "VerifyMicrocode - fail on LoadMicrocode\n"));\r
+      *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_AUTH_ERROR;\r
+      if (AbortReason != NULL) {\r
+        *AbortReason = AllocateCopyPool(sizeof(L"InvalidData"), L"InvalidData");\r
+      }\r
+      return EFI_SECURITY_VIOLATION;\r
+    }\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Get current Microcode in used.\r
+\r
+  @return current Microcode in used.\r
+**/\r
+VOID *\r
+GetCurrentMicrocodeInUse (\r
+  VOID\r
+  )\r
+{\r
+  BOOLEAN                                 Result;\r
+  EFI_STATUS                              Status;\r
+  UINT64                                  MicrocodePatchAddress;\r
+  UINT64                                  MicrocodePatchRegionSize;\r
+  CPU_MICROCODE_HEADER                    *MicrocodeEntryPoint;\r
+  UINTN                                   MicrocodeEnd;\r
+  UINTN                                   TotalSize;\r
+  UINTN                                   Count;\r
+  UINT32                                  AttemptStatus;\r
+\r
+  Result = GetMicrocodeRegion(&MicrocodePatchAddress, &MicrocodePatchRegionSize);\r
+  if (!Result) {\r
+    DEBUG((DEBUG_ERROR, "Fail to get Microcode Region\n"));\r
+    return NULL;\r
+  }\r
+  DEBUG((DEBUG_INFO, "Microcode Region - 0x%lx - 0x%lx\n", MicrocodePatchAddress, MicrocodePatchRegionSize));\r
+\r
+  Count = 0;\r
+\r
+  MicrocodeEnd = (UINTN)(MicrocodePatchAddress + MicrocodePatchRegionSize);\r
+  MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(UINTN)MicrocodePatchAddress;\r
+  do {\r
+    if (MicrocodeEntryPoint->HeaderVersion == 0x1 && MicrocodeEntryPoint->LoaderRevision == 0x1) {\r
+      //\r
+      // It is the microcode header. It is not the padding data between microcode patches\r
+      // becasue the padding data should not include 0x00000001 and it should be the repeated\r
+      // byte format (like 0xXYXYXYXY....).\r
+      //\r
+      if (MicrocodeEntryPoint->DataSize == 0) {\r
+        TotalSize = 2048;\r
+      } else {\r
+        TotalSize = MicrocodeEntryPoint->TotalSize;\r
+      }\r
+      Status = VerifyMicrocode(MicrocodeEntryPoint, TotalSize, FALSE, &AttemptStatus, NULL);\r
+      if (!EFI_ERROR(Status)) {\r
+        return MicrocodeEntryPoint;\r
+      }\r
+\r
+    } else {\r
+      //\r
+      // It is the padding data between the microcode patches for microcode patches alignment.\r
+      // Because the microcode patch is the multiple of 1-KByte, the padding data should not\r
+      // exist if the microcode patch alignment value is not larger than 1-KByte. So, the microcode\r
+      // alignment value should be larger than 1-KByte. We could skip SIZE_1KB padding data to\r
+      // find the next possible microcode patch header.\r
+      //\r
+      MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(((UINTN)MicrocodeEntryPoint) + SIZE_1KB);\r
+      continue;\r
+    }\r
+\r
+    Count++;\r
+    ASSERT(Count < 0xFF);\r
+\r
+    //\r
+    // Get the next patch.\r
+    //\r
+    MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(((UINTN)MicrocodeEntryPoint) + TotalSize);\r
+  } while (((UINTN)MicrocodeEntryPoint < MicrocodeEnd));\r
+\r
+  return NULL;\r
+}\r
+\r
+/**\r
+  Get current Microcode used region size.\r
+\r
+  @return current Microcode used region size.\r
+**/\r
+UINTN\r
+GetCurrentMicrocodeUsedRegionSize (\r
+  VOID\r
+  )\r
+{\r
+  BOOLEAN                                 Result;\r
+  UINT64                                  MicrocodePatchAddress;\r
+  UINT64                                  MicrocodePatchRegionSize;\r
+  CPU_MICROCODE_HEADER                    *MicrocodeEntryPoint;\r
+  UINTN                                   MicrocodeEnd;\r
+  UINTN                                   TotalSize;\r
+  UINTN                                   Count;\r
+  UINTN                                   MicrocodeUsedEnd;\r
+\r
+  Result = GetMicrocodeRegion(&MicrocodePatchAddress, &MicrocodePatchRegionSize);\r
+  if (!Result) {\r
+    DEBUG((DEBUG_ERROR, "Fail to get Microcode Region\n"));\r
+    return 0;\r
+  }\r
+  DEBUG((DEBUG_INFO, "Microcode Region - 0x%lx - 0x%lx\n", MicrocodePatchAddress, MicrocodePatchRegionSize));\r
+\r
+  MicrocodeUsedEnd = (UINTN)MicrocodePatchAddress;\r
+  Count = 0;\r
+\r
+  MicrocodeEnd = (UINTN)(MicrocodePatchAddress + MicrocodePatchRegionSize);\r
+  MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(UINTN)MicrocodePatchAddress;\r
+  do {\r
+    if (MicrocodeEntryPoint->HeaderVersion == 0x1 && MicrocodeEntryPoint->LoaderRevision == 0x1) {\r
+      //\r
+      // It is the microcode header. It is not the padding data between microcode patches\r
+      // becasue the padding data should not include 0x00000001 and it should be the repeated\r
+      // byte format (like 0xXYXYXYXY....).\r
+      //\r
+      if (MicrocodeEntryPoint->DataSize == 0) {\r
+        TotalSize = 2048;\r
+      } else {\r
+        TotalSize = MicrocodeEntryPoint->TotalSize;\r
+      }\r
+\r
+    } else {\r
+      //\r
+      // It is the padding data between the microcode patches for microcode patches alignment.\r
+      // Because the microcode patch is the multiple of 1-KByte, the padding data should not\r
+      // exist if the microcode patch alignment value is not larger than 1-KByte. So, the microcode\r
+      // alignment value should be larger than 1-KByte. We could skip SIZE_1KB padding data to\r
+      // find the next possible microcode patch header.\r
+      //\r
+      MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(((UINTN)MicrocodeEntryPoint) + SIZE_1KB);\r
+      continue;\r
+    }\r
+\r
+    Count++;\r
+    ASSERT(Count < 0xFF);\r
+    MicrocodeUsedEnd = (UINTN)MicrocodeEntryPoint;\r
+\r
+    //\r
+    // Get the next patch.\r
+    //\r
+    MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(((UINTN)MicrocodeEntryPoint) + TotalSize);\r
+  } while (((UINTN)MicrocodeEntryPoint < MicrocodeEnd));\r
+\r
+  return MicrocodeUsedEnd - (UINTN)MicrocodePatchAddress;\r
+}\r
+\r
+/**\r
+  Update Microcode.\r
+\r
+  @param[in]   Address            The flash address of Microcode.\r
+  @param[in]   Image              The Microcode image buffer.\r
+  @param[in]   ImageSize          The size of Microcode image buffer in bytes.\r
+  @param[out]  LastAttemptStatus  The last attempt status, which will be recorded in ESRT and FMP EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+\r
+  @retval EFI_SUCCESS           The Microcode image is updated.\r
+  @retval EFI_WRITE_PROTECTED   The flash device is read only.\r
+**/\r
+EFI_STATUS\r
+UpdateMicrocode (\r
+  IN UINT64   Address,\r
+  IN VOID     *Image,\r
+  IN UINTN    ImageSize,\r
+  OUT UINT32  *LastAttemptStatus\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  DEBUG((DEBUG_INFO, "PlatformUpdate:"));\r
+  DEBUG((DEBUG_INFO, "  Address - 0x%lx,", Address));\r
+  DEBUG((DEBUG_INFO, "  Legnth - 0x%x\n", ImageSize));\r
+\r
+  Status = MicrocodeFlashWrite (\r
+             Address,\r
+             Image,\r
+             ImageSize\r
+             );\r
+  if (!EFI_ERROR(Status)) {\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_SUCCESS;\r
+  } else {\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL;\r
+  }\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Write Microcode.\r
+\r
+  Caution: This function may receive untrusted input.\r
+\r
+  @param[in]   ImageIndex         The index of Microcode image.\r
+  @param[in]   Image              The Microcode image buffer.\r
+  @param[in]   ImageSize          The size of Microcode image buffer in bytes.\r
+  @param[out]  LastAttemptVersion The last attempt version, which will be recorded in ESRT and FMP EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out]  LastAttemptStatus  The last attempt status, which will be recorded in ESRT and FMP EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out]  AbortReason        A pointer to a pointer to a null-terminated string providing more\r
+                             details for the aborted operation. The buffer is allocated by this function\r
+                             with AllocatePool(), and it is the caller's responsibility to free it with a\r
+                             call to FreePool().\r
+\r
+  @retval EFI_SUCCESS               The Microcode image is written.\r
+  @retval EFI_VOLUME_CORRUPTED      The Microcode image is corrupt.\r
+  @retval EFI_INCOMPATIBLE_VERSION  The Microcode image version is incorrect.\r
+  @retval EFI_SECURITY_VIOLATION    The Microcode image fails to load.\r
+  @retval EFI_WRITE_PROTECTED   The flash device is read only.\r
+**/\r
+EFI_STATUS\r
+MicrocodeWrite (\r
+  IN  UINTN   ImageIndex,\r
+  IN  VOID    *Image,\r
+  IN  UINTN   ImageSize,\r
+  OUT UINT32  *LastAttemptVersion,\r
+  OUT UINT32  *LastAttemptStatus,\r
+  OUT CHAR16  **AbortReason\r
+  )\r
+{\r
+  BOOLEAN                                 Result;\r
+  EFI_STATUS                              Status;\r
+  UINT64                                  MicrocodePatchAddress;\r
+  UINT64                                  MicrocodePatchRegionSize;\r
+  CPU_MICROCODE_HEADER                    *CurrentMicrocodeEntryPoint;\r
+  UINTN                                   CurrentTotalSize;\r
+  UINTN                                   UsedRegionSize;\r
+  VOID                                    *AlignedImage;\r
+\r
+  Result = GetMicrocodeRegion(&MicrocodePatchAddress, &MicrocodePatchRegionSize);\r
+  if (!Result) {\r
+    DEBUG((DEBUG_ERROR, "Fail to get Microcode Region\n"));\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  CurrentTotalSize = 0;\r
+  CurrentMicrocodeEntryPoint = GetCurrentMicrocodeInUse();\r
+  if (CurrentMicrocodeEntryPoint != NULL) {\r
+    if (CurrentMicrocodeEntryPoint->DataSize == 0) {\r
+      CurrentTotalSize = 2048;\r
+    } else {\r
+      CurrentTotalSize = CurrentMicrocodeEntryPoint->TotalSize;\r
+    }\r
+  }\r
+\r
+  //\r
+  // MCU must be 16 bytes aligned\r
+  //\r
+  AlignedImage = AllocateCopyPool(ImageSize, Image);\r
+  if (AlignedImage == NULL) {\r
+    DEBUG((DEBUG_ERROR, "Fail to allocate aligned image\n"));\r
+    *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INSUFFICIENT_RESOURCES;\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  *LastAttemptVersion = ((CPU_MICROCODE_HEADER *)Image)->UpdateRevision;\r
+  Status = VerifyMicrocode(AlignedImage, ImageSize, TRUE, LastAttemptStatus, AbortReason);\r
+  if (EFI_ERROR(Status)) {\r
+    DEBUG((DEBUG_ERROR, "Fail to verify Microcode Region\n"));\r
+    FreePool(AlignedImage);\r
+    return Status;\r
+  }\r
+  DEBUG((DEBUG_INFO, "Pass VerifyMicrocode\n"));\r
+\r
+  if (CurrentTotalSize < ImageSize) {\r
+    UsedRegionSize = GetCurrentMicrocodeUsedRegionSize();\r
+    if (MicrocodePatchRegionSize - UsedRegionSize >= ImageSize) {\r
+      //\r
+      // Append\r
+      //\r
+      DEBUG((DEBUG_INFO, "Append new microcode\n"));\r
+      Status = UpdateMicrocode(MicrocodePatchAddress + UsedRegionSize, AlignedImage, ImageSize, LastAttemptStatus);\r
+    } else if (MicrocodePatchRegionSize >= ImageSize) {\r
+      //\r
+      // Ignor all others and just add this one from beginning.\r
+      //\r
+      DEBUG((DEBUG_INFO, "Add new microcode from beginning\n"));\r
+      Status = UpdateMicrocode(MicrocodePatchAddress, AlignedImage, ImageSize, LastAttemptStatus);\r
+    } else {\r
+      DEBUG((DEBUG_ERROR, "Microcode too big\n"));\r
+      *LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INSUFFICIENT_RESOURCES;\r
+      Status = EFI_OUT_OF_RESOURCES;\r
+    }\r
+  } else {\r
+    //\r
+    // Replace\r
+    //\r
+    DEBUG((DEBUG_INFO, "Replace old microcode\n"));\r
+    Status = UpdateMicrocode((UINTN)CurrentMicrocodeEntryPoint, AlignedImage, ImageSize, LastAttemptStatus);\r
+  }\r
+\r
+  FreePool(AlignedImage);\r
+\r
+  return Status;\r
+}\r
+\r
+\r
diff --git a/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdate.h b/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdate.h
new file mode 100644 (file)
index 0000000..77e8441
--- /dev/null
@@ -0,0 +1,403 @@
+/** @file\r
+  Microcode update header file.\r
+\r
+  Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>\r
+  This program and the accompanying materials\r
+  are licensed and made available under the terms and conditions of the BSD License\r
+  which accompanies this distribution.  The full text of the license may be found at\r
+  http://opensource.org/licenses/bsd-license.php\r
+\r
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#ifndef _MICROCODE_FMP_H_\r
+#define _MICROCODE_FMP_H_\r
+\r
+#include <PiDxe.h>\r
+\r
+#include <Guid/SystemResourceTable.h>\r
+#include <Guid/MicrocodeFmp.h>\r
+\r
+#include <Protocol/FirmwareManagement.h>\r
+\r
+#include <Library/BaseLib.h>\r
+#include <Library/BaseMemoryLib.h>\r
+#include <Library/DebugLib.h>\r
+#include <Library/MemoryAllocationLib.h>\r
+#include <Library/PcdLib.h>\r
+#include <Library/UefiBootServicesTableLib.h>\r
+#include <Library/UefiLib.h>\r
+#include <Library/UefiRuntimeServicesTableLib.h>\r
+#include <Library/UefiDriverEntryPoint.h>\r
+#include <Library/DevicePathLib.h>\r
+#include <Library/HobLib.h>\r
+#include <Library/MicrocodeFlashAccessLib.h>\r
+\r
+#include <Register/Cpuid.h>\r
+#include <Register/Msr.h>\r
+#include <Register/Microcode.h>\r
+\r
+#define MICROCODE_FMP_PRIVATE_DATA_SIGNATURE  SIGNATURE_32('M', 'C', 'U', 'F')\r
+\r
+//\r
+// Microcode FMP private data structure.\r
+//\r
+\r
+typedef struct {\r
+  UINT32 LastAttemptVersion;\r
+  UINT32 LastAttemptStatus;\r
+} MICROCODE_FMP_LAST_ATTEMPT_VARIABLE;\r
+\r
+struct _MICROCODE_FMP_PRIVATE_DATA {\r
+  UINT32                               Signature;\r
+  EFI_FIRMWARE_MANAGEMENT_PROTOCOL     Fmp;\r
+  EFI_HANDLE                           Handle;\r
+  UINT8                                DescriptorCount;\r
+  EFI_FIRMWARE_IMAGE_DESCRIPTOR        *ImageDescriptor;\r
+  UINT32                               PackageVersion;\r
+  CHAR16                               *PackageVersionName;\r
+  MICROCODE_FMP_LAST_ATTEMPT_VARIABLE  LastAttempt;\r
+};\r
+\r
+typedef struct _MICROCODE_FMP_PRIVATE_DATA  MICROCODE_FMP_PRIVATE_DATA;\r
+\r
+#define MICROCODE_FMP_LAST_ATTEMPT_VARIABLE_NAME  L"MicrocodeLastAttempVar"\r
+\r
+/**\r
+  Returns a pointer to the MICROCODE_FMP_PRIVATE_DATA structure from the input a as Fmp.\r
+\r
+  If the signatures matches, then a pointer to the data structure that contains\r
+  a specified field of that data structure is returned.\r
+\r
+  @param  a              Pointer to the field specified by ServiceBinding within\r
+                         a data structure of type MICROCODE_FMP_PRIVATE_DATA.\r
+\r
+**/\r
+#define MICROCODE_FMP_PRIVATE_DATA_FROM_FMP(a) \\r
+  CR ( \\r
+  (a), \\r
+  MICROCODE_FMP_PRIVATE_DATA, \\r
+  Fmp, \\r
+  MICROCODE_FMP_PRIVATE_DATA_SIGNATURE \\r
+  )\r
+\r
+/**\r
+  Get current Microcode information.\r
+\r
+  @param[out]  ImageDescriptor  Microcode ImageDescriptor\r
+  @param[in]   DescriptorCount  The count of Microcode ImageDescriptor allocated.\r
+\r
+  @return Microcode count\r
+**/\r
+UINTN\r
+GetMicrocodeInfo (\r
+  OUT EFI_FIRMWARE_IMAGE_DESCRIPTOR  *ImageDescriptor, OPTIONAL\r
+  IN  UINTN                          DescriptorCount   OPTIONAL\r
+  );\r
+\r
+/**\r
+  Read Microcode.\r
+\r
+  @param[in]       ImageIndex The index of Microcode image.\r
+  @param[in, out]  Image      The Microcode image buffer.\r
+  @param[in, out]  ImageSize  The size of Microcode image buffer in bytes.\r
+\r
+  @retval EFI_SUCCESS    The Microcode image is read.\r
+  @retval EFI_NOT_FOUND  The Microcode image is not found.\r
+**/\r
+EFI_STATUS\r
+MicrocodeRead (\r
+  IN UINTN      ImageIndex,\r
+  IN OUT VOID   *Image,\r
+  IN OUT UINTN  *ImageSize\r
+  );\r
+\r
+/**\r
+  Write Microcode.\r
+\r
+  @param[in]   ImageIndex         The index of Microcode image.\r
+  @param[in]   Image              The Microcode image buffer.\r
+  @param[in]   ImageSize          The size of Microcode image buffer in bytes.\r
+  @param[out]  LastAttemptVersion The last attempt version, which will be recorded in ESRT and FMP EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out]  LastAttemptStatus  The last attempt status, which will be recorded in ESRT and FMP EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out]  AbortReason        A pointer to a pointer to a null-terminated string providing more\r
+                                  details for the aborted operation. The buffer is allocated by this function\r
+                                  with AllocatePool(), and it is the caller's responsibility to free it with a\r
+                                  call to FreePool().\r
+\r
+  @retval EFI_SUCCESS               The Microcode image is written.\r
+  @retval EFI_VOLUME_CORRUPTED      The Microcode image is corrupt.\r
+  @retval EFI_INCOMPATIBLE_VERSION  The Microcode image version is incorrect.\r
+  @retval EFI_SECURITY_VIOLATION    The Microcode image fails to load.\r
+  @retval EFI_WRITE_PROTECTED   The flash device is read only.\r
+**/\r
+EFI_STATUS\r
+MicrocodeWrite (\r
+  IN UINTN    ImageIndex,\r
+  IN VOID     *Image,\r
+  IN UINTN    ImageSize,\r
+  OUT UINT32  *LastAttemptVersion,\r
+  OUT UINT32  *LastAttemptStatus,\r
+  OUT CHAR16  **AbortReason\r
+  );\r
+\r
+/**\r
+  Returns information about the current firmware image(s) of the device.\r
+\r
+  This function allows a copy of the current firmware image to be created and saved.\r
+  The saved copy could later been used, for example, in firmware image recovery or rollback.\r
+\r
+  @param[in]      This               A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in, out] ImageInfoSize      A pointer to the size, in bytes, of the ImageInfo buffer.\r
+                                     On input, this is the size of the buffer allocated by the caller.\r
+                                     On output, it is the size of the buffer returned by the firmware\r
+                                     if the buffer was large enough, or the size of the buffer needed\r
+                                     to contain the image(s) information if the buffer was too small.\r
+  @param[in, out] ImageInfo          A pointer to the buffer in which firmware places the current image(s)\r
+                                     information. The information is an array of EFI_FIRMWARE_IMAGE_DESCRIPTORs.\r
+  @param[out]     DescriptorVersion  A pointer to the location in which firmware returns the version number\r
+                                     associated with the EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out]     DescriptorCount    A pointer to the location in which firmware returns the number of\r
+                                     descriptors or firmware images within this device.\r
+  @param[out]     DescriptorSize     A pointer to the location in which firmware returns the size, in bytes,\r
+                                     of an individual EFI_FIRMWARE_IMAGE_DESCRIPTOR.\r
+  @param[out]     PackageVersion     A version number that represents all the firmware images in the device.\r
+                                     The format is vendor specific and new version must have a greater value\r
+                                     than the old version. If PackageVersion is not supported, the value is\r
+                                     0xFFFFFFFF. A value of 0xFFFFFFFE indicates that package version comparison\r
+                                     is to be performed using PackageVersionName. A value of 0xFFFFFFFD indicates\r
+                                     that package version update is in progress.\r
+  @param[out]     PackageVersionName A pointer to a pointer to a null-terminated string representing the\r
+                                     package version name. The buffer is allocated by this function with\r
+                                     AllocatePool(), and it is the caller's responsibility to free it with a call\r
+                                     to FreePool().\r
+\r
+  @retval EFI_SUCCESS                The device was successfully updated with the new image.\r
+  @retval EFI_BUFFER_TOO_SMALL       The ImageInfo buffer was too small. The current buffer size\r
+                                     needed to hold the image(s) information is returned in ImageInfoSize.\r
+  @retval EFI_INVALID_PARAMETER      ImageInfoSize is NULL.\r
+  @retval EFI_DEVICE_ERROR           Valid information could not be returned. Possible corrupted image.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpGetImageInfo (\r
+  IN EFI_FIRMWARE_MANAGEMENT_PROTOCOL       *This,\r
+  IN OUT    UINTN                           *ImageInfoSize,\r
+  IN OUT    EFI_FIRMWARE_IMAGE_DESCRIPTOR   *ImageInfo,\r
+  OUT       UINT32                          *DescriptorVersion,\r
+  OUT       UINT8                           *DescriptorCount,\r
+  OUT       UINTN                           *DescriptorSize,\r
+  OUT       UINT32                          *PackageVersion,\r
+  OUT       CHAR16                          **PackageVersionName\r
+  );\r
+\r
+/**\r
+  Retrieves a copy of the current firmware image of the device.\r
+\r
+  This function allows a copy of the current firmware image to be created and saved.\r
+  The saved copy could later been used, for example, in firmware image recovery or rollback.\r
+\r
+  @param[in]     This            A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in]     ImageIndex      A unique number identifying the firmware image(s) within the device.\r
+                                 The number is between 1 and DescriptorCount.\r
+  @param[in,out] Image           Points to the buffer where the current image is copied to.\r
+  @param[in,out] ImageSize       On entry, points to the size of the buffer pointed to by Image, in bytes.\r
+                                 On return, points to the length of the image, in bytes.\r
+\r
+  @retval EFI_SUCCESS            The device was successfully updated with the new image.\r
+  @retval EFI_BUFFER_TOO_SMALL   The buffer specified by ImageSize is too small to hold the\r
+                                 image. The current buffer size needed to hold the image is returned\r
+                                 in ImageSize.\r
+  @retval EFI_INVALID_PARAMETER  The Image was NULL.\r
+  @retval EFI_NOT_FOUND          The current image is not copied to the buffer.\r
+  @retval EFI_UNSUPPORTED        The operation is not supported.\r
+  @retval EFI_SECURITY_VIOLATIO  The operation could not be performed due to an authentication failure.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpGetImage (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL  *This,\r
+  IN  UINT8                             ImageIndex,\r
+  IN  OUT  VOID                         *Image,\r
+  IN  OUT  UINTN                        *ImageSize\r
+  );\r
+\r
+/**\r
+  Updates the firmware image of the device.\r
+\r
+  This function updates the hardware with the new firmware image.\r
+  This function returns EFI_UNSUPPORTED if the firmware image is not updatable.\r
+  If the firmware image is updatable, the function should perform the following minimal validations\r
+  before proceeding to do the firmware image update.\r
+  - Validate the image authentication if image has attribute\r
+    IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED. The function returns\r
+    EFI_SECURITY_VIOLATION if the validation fails.\r
+  - Validate the image is a supported image for this device. The function returns EFI_ABORTED if\r
+    the image is unsupported. The function can optionally provide more detailed information on\r
+    why the image is not a supported image.\r
+  - Validate the data from VendorCode if not null. Image validation must be performed before\r
+    VendorCode data validation. VendorCode data is ignored or considered invalid if image\r
+    validation failed. The function returns EFI_ABORTED if the data is invalid.\r
+\r
+  VendorCode enables vendor to implement vendor-specific firmware image update policy. Null if\r
+  the caller did not specify the policy or use the default policy. As an example, vendor can implement\r
+  a policy to allow an option to force a firmware image update when the abort reason is due to the new\r
+  firmware image version is older than the current firmware image version or bad image checksum.\r
+  Sensitive operations such as those wiping the entire firmware image and render the device to be\r
+  non-functional should be encoded in the image itself rather than passed with the VendorCode.\r
+  AbortReason enables vendor to have the option to provide a more detailed description of the abort\r
+  reason to the caller.\r
+\r
+  @param[in]  This               A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in]  ImageIndex         A unique number identifying the firmware image(s) within the device.\r
+                                 The number is between 1 and DescriptorCount.\r
+  @param[in]  Image              Points to the new image.\r
+  @param[in]  ImageSize          Size of the new image in bytes.\r
+  @param[in]  VendorCode         This enables vendor to implement vendor-specific firmware image update policy.\r
+                                 Null indicates the caller did not specify the policy or use the default policy.\r
+  @param[in]  Progress           A function used by the driver to report the progress of the firmware update.\r
+  @param[out] AbortReason        A pointer to a pointer to a null-terminated string providing more\r
+                                 details for the aborted operation. The buffer is allocated by this function\r
+                                 with AllocatePool(), and it is the caller's responsibility to free it with a\r
+                                 call to FreePool().\r
+\r
+  @retval EFI_SUCCESS            The device was successfully updated with the new image.\r
+  @retval EFI_ABORTED            The operation is aborted.\r
+  @retval EFI_INVALID_PARAMETER  The Image was NULL.\r
+  @retval EFI_UNSUPPORTED        The operation is not supported.\r
+  @retval EFI_SECURITY_VIOLATIO  The operation could not be performed due to an authentication failure.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpSetImage (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL                 *This,\r
+  IN  UINT8                                            ImageIndex,\r
+  IN  CONST VOID                                       *Image,\r
+  IN  UINTN                                            ImageSize,\r
+  IN  CONST VOID                                       *VendorCode,\r
+  IN  EFI_FIRMWARE_MANAGEMENT_UPDATE_IMAGE_PROGRESS    Progress,\r
+  OUT CHAR16                                           **AbortReason\r
+  );\r
+\r
+/**\r
+  Checks if the firmware image is valid for the device.\r
+\r
+  This function allows firmware update application to validate the firmware image without\r
+  invoking the SetImage() first.\r
+\r
+  @param[in]  This               A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in]  ImageIndex         A unique number identifying the firmware image(s) within the device.\r
+                                 The number is between 1 and DescriptorCount.\r
+  @param[in]  Image              Points to the new image.\r
+  @param[in]  ImageSize          Size of the new image in bytes.\r
+  @param[out] ImageUpdatable     Indicates if the new image is valid for update. It also provides,\r
+                                 if available, additional information if the image is invalid.\r
+\r
+  @retval EFI_SUCCESS            The image was successfully checked.\r
+  @retval EFI_INVALID_PARAMETER  The Image was NULL.\r
+  @retval EFI_UNSUPPORTED        The operation is not supported.\r
+  @retval EFI_SECURITY_VIOLATIO  The operation could not be performed due to an authentication failure.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpCheckImage (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL  *This,\r
+  IN  UINT8                             ImageIndex,\r
+  IN  CONST VOID                        *Image,\r
+  IN  UINTN                             ImageSize,\r
+  OUT UINT32                            *ImageUpdatable\r
+  );\r
+\r
+/**\r
+  Returns information about the firmware package.\r
+\r
+  This function returns package information.\r
+\r
+  @param[in]  This                     A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[out] PackageVersion           A version number that represents all the firmware images in the device.\r
+                                       The format is vendor specific and new version must have a greater value\r
+                                       than the old version. If PackageVersion is not supported, the value is\r
+                                       0xFFFFFFFF. A value of 0xFFFFFFFE indicates that package version\r
+                                       comparison is to be performed using PackageVersionName. A value of\r
+                                       0xFFFFFFFD indicates that package version update is in progress.\r
+  @param[out] PackageVersionName       A pointer to a pointer to a null-terminated string representing\r
+                                       the package version name. The buffer is allocated by this function with\r
+                                       AllocatePool(), and it is the caller's responsibility to free it with a\r
+                                       call to FreePool().\r
+  @param[out] PackageVersionNameMaxLen The maximum length of package version name if device supports update of\r
+                                       package version name. A value of 0 indicates the device does not support\r
+                                       update of package version name. Length is the number of Unicode characters,\r
+                                       including the terminating null character.\r
+  @param[out] AttributesSupported      Package attributes that are supported by this device. See 'Package Attribute\r
+                                       Definitions' for possible returned values of this parameter. A value of 1\r
+                                       indicates the attribute is supported and the current setting value is\r
+                                       indicated in AttributesSetting. A value of 0 indicates the attribute is not\r
+                                       supported and the current setting value in AttributesSetting is meaningless.\r
+  @param[out] AttributesSetting        Package attributes. See 'Package Attribute Definitions' for possible returned\r
+                                       values of this parameter\r
+\r
+  @retval EFI_SUCCESS                  The package information was successfully returned.\r
+  @retval EFI_UNSUPPORTED              The operation is not supported.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpGetPackageInfo (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL *This,\r
+  OUT UINT32                           *PackageVersion,\r
+  OUT CHAR16                           **PackageVersionName,\r
+  OUT UINT32                           *PackageVersionNameMaxLen,\r
+  OUT UINT64                           *AttributesSupported,\r
+  OUT UINT64                           *AttributesSetting\r
+  );\r
+\r
+/**\r
+  Updates information about the firmware package.\r
+\r
+  This function updates package information.\r
+  This function returns EFI_UNSUPPORTED if the package information is not updatable.\r
+  VendorCode enables vendor to implement vendor-specific package information update policy.\r
+  Null if the caller did not specify this policy or use the default policy.\r
+\r
+  @param[in]  This               A pointer to the EFI_FIRMWARE_MANAGEMENT_PROTOCOL instance.\r
+  @param[in]  Image              Points to the authentication image.\r
+                                 Null if authentication is not required.\r
+  @param[in]  ImageSize          Size of the authentication image in bytes.\r
+                                 0 if authentication is not required.\r
+  @param[in]  VendorCode         This enables vendor to implement vendor-specific firmware\r
+                                 image update policy.\r
+                                 Null indicates the caller did not specify this policy or use\r
+                                 the default policy.\r
+  @param[in]  PackageVersion     The new package version.\r
+  @param[in]  PackageVersionName A pointer to the new null-terminated Unicode string representing\r
+                                 the package version name.\r
+                                 The string length is equal to or less than the value returned in\r
+                                 PackageVersionNameMaxLen.\r
+\r
+  @retval EFI_SUCCESS            The device was successfully updated with the new package\r
+                                 information.\r
+  @retval EFI_INVALID_PARAMETER  The PackageVersionName length is longer than the value\r
+                                 returned in PackageVersionNameMaxLen.\r
+  @retval EFI_UNSUPPORTED        The operation is not supported.\r
+  @retval EFI_SECURITY_VIOLATIO  The operation could not be performed due to an authentication failure.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+FmpSetPackageInfo (\r
+  IN  EFI_FIRMWARE_MANAGEMENT_PROTOCOL   *This,\r
+  IN  CONST VOID                         *Image,\r
+  IN  UINTN                              ImageSize,\r
+  IN  CONST VOID                         *VendorCode,\r
+  IN  UINT32                             PackageVersion,\r
+  IN  CONST CHAR16                       *PackageVersionName\r
+  );\r
+\r
+#endif\r
+\r
diff --git a/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxe.inf b/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxe.inf
new file mode 100644 (file)
index 0000000..437d300
--- /dev/null
@@ -0,0 +1,68 @@
+## @file\r
+# Microcode FMP update driver.\r
+#\r
+# Produce FMP instance to update Microcode.\r
+#\r
+#  Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>\r
+#  This program and the accompanying materials\r
+#  are licensed and made available under the terms and conditions of the BSD License\r
+#  which accompanies this distribution.  The full text of the license may be found at\r
+#  http://opensource.org/licenses/bsd-license.php\r
+#\r
+#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+#\r
+##\r
+\r
+[Defines]\r
+  INF_VERSION                    = 0x00010005\r
+  BASE_NAME                      = MicrocodeUpdateDxe\r
+  MODULE_UNI_FILE                = MicrocodeUpdateDxe.uni\r
+  FILE_GUID                      = 0565365C-2FE1-4F88-B3BE-624C04623A20\r
+  MODULE_TYPE                    = DXE_DRIVER\r
+  VERSION_STRING                 = 1.0\r
+  ENTRY_POINT                    = MicrocodeFmpMain\r
+\r
+#\r
+# The following information is for reference only and not required by the build tools.\r
+#\r
+#  VALID_ARCHITECTURES           = X64\r
+#\r
+\r
+[Sources]\r
+  MicrocodeFmp.c\r
+  MicrocodeUpdate.c\r
+\r
+[Packages]\r
+  MdePkg/MdePkg.dec\r
+  UefiCpuPkg/UefiCpuPkg.dec\r
+\r
+[LibraryClasses]\r
+  BaseLib\r
+  UefiLib\r
+  BaseMemoryLib\r
+  DebugLib\r
+  PcdLib\r
+  MemoryAllocationLib\r
+  UefiBootServicesTableLib\r
+  HobLib\r
+  UefiRuntimeServicesTableLib\r
+  UefiDriverEntryPoint\r
+  MicrocodeFlashAccessLib\r
+\r
+[Guids]\r
+  gMicrocodeFmpImageTypeIdGuid\r
+\r
+[Protocols]\r
+  gEfiFirmwareManagementProtocolGuid            ## SOMTIMES_PRODUCE\r
+\r
+[Pcd]\r
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress            ## CONSUMES\r
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize         ## CONSUMES\r
+\r
+[Depex]\r
+  gEfiVariableArchProtocolGuid\r
+\r
+[UserExtensions.TianoCore."ExtraFiles"]\r
+  MicrocodeUpdateDxeExtra.uni\r
+\r
diff --git a/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxe.uni b/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxe.uni
new file mode 100644 (file)
index 0000000..1b0d494
--- /dev/null
@@ -0,0 +1,21 @@
+// /** @file\r
+// Microcode FMP update driver.\r
+//\r
+// Produce FMP instance to update Microcode.\r
+//\r
+// Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>\r
+//\r
+// This program and the accompanying materials\r
+// are licensed and made available under the terms and conditions of the BSD License\r
+// which accompanies this distribution.  The full text of the license may be found at\r
+// http://opensource.org/licenses/bsd-license.php\r
+//\r
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+//\r
+// **/\r
+\r
+\r
+#string STR_MODULE_ABSTRACT             #language en-US "Microcode FMP update driver."\r
+\r
+#string STR_MODULE_DESCRIPTION          #language en-US "Produce FMP instance to update Microcode."\r
diff --git a/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxeExtra.uni b/UefiCpuPkg/Feature/Capsule/MicrocodeUpdateDxe/MicrocodeUpdateDxeExtra.uni
new file mode 100644 (file)
index 0000000..b667f12
--- /dev/null
@@ -0,0 +1,20 @@
+// /** @file\r
+// MicrocodeUpdateDxe Localized Strings and Content\r
+//\r
+// Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>\r
+//\r
+// This program and the accompanying materials\r
+// are licensed and made available under the terms and conditions of the BSD License\r
+// which accompanies this distribution.  The full text of the license may be found at\r
+// http://opensource.org/licenses/bsd-license.php\r
+//\r
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+//\r
+// **/\r
+\r
+#string STR_PROPERTIES_MODULE_NAME\r
+#language en-US\r
+"MicrocodeUpdate DXE Driver"\r
+\r
+\r