summaryrefslogtreecommitdiff
path: root/Vlv2TbltDevicePkg/UpdateDriverDxe/UpdateDispatcher.c
blob: f189bc109dc3ebd5b95614de2fe83e9292421c5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
/** @file
  Functions in this file will mainly focus on looking through the capsule
  for the image to be programmed, and the flash area that is going to be
  programed.

  Copyright (c) 2004 - 2016, Intel Corporation. All rights reserved.<BR>

  This program and the accompanying materials
  are licensed and made available under the terms and conditions of the BSD License
  which accompanies this distribution.  The full text of the license may be found at
  http://opensource.org/licenses/bsd-license.php.

  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/

#include "UpdateDriver.h"

EFI_HII_HANDLE  gHiiHandle;
EFI_SYSTEM_RESOURCE_ENTRY NewEsrtTemplate = 
  // System Firmware Entry
  {
    SYSTEM_FW_CLASS_GUID,
    ESRT_FW_TYPE_SYSTEMFIRMWARE,
    0x0003,
    0x0001,
    0x0000,
    0x0003,
    LAST_ATTEMPT_STATUS_SUCCESS
  };

/**
  Update the whole FV, or certain files in the FV.
  
  @param ConfigData      Pointer to the config data on updating file.
  @param ImageBuffer     Image buffer to be updated.
  @param ImageSize       Image size.
  @param FileType        FFS file type.
  @param FileAttributes  FFS file attribute.

  @retval EFI_NOT_FOUND  The matched FVB protocol is not found.
  @retval EFI_SUCCESS    The image buffer is updated into FV.

**/
EFI_STATUS
PerformUpdateOnFirmwareVolume (
  IN UPDATE_CONFIG_DATA                 *ConfigData,
  IN UINT8                              *ImageBuffer,
  IN UINTN                              ImageSize,
  IN EFI_FV_FILETYPE                    FileType,
  IN EFI_FV_FILE_ATTRIBUTES             FileAttributes
  )
{
  EFI_STATUS                            Status;
  BOOLEAN                               Found;
  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *FvbProtocol;
  UINTN                                 Index;
  UINTN                                 NumOfHandles;
  EFI_HANDLE                            *HandleBuffer;
  EFI_PHYSICAL_ADDRESS                  BaseAddress;
  EFI_FVB_ATTRIBUTES_2                  Attributes;

  //
  // Locate all Fvb protocol
  //
  HandleBuffer = NULL;
  Status          = gBS->LocateHandleBuffer (
                           ByProtocol,
                           &gEfiFirmwareVolumeBlockProtocolGuid,
                           NULL,
                           &NumOfHandles,
                           &HandleBuffer
                           );
  if ((EFI_ERROR (Status)) || (NumOfHandles == 0) || (HandleBuffer == NULL)) {
    if (HandleBuffer != NULL) {
      FreePool (HandleBuffer);
    }
    return EFI_NOT_FOUND;
  }

  //
  // Check the FVB protocol one by one
  //
  Found               = FALSE;
  FvbProtocol         = NULL;
  for (Index = 0; Index < NumOfHandles; Index++) {
    Status            = gBS->HandleProtocol (
                               HandleBuffer[Index],
                               &gEfiFirmwareVolumeBlockProtocolGuid,
                               (VOID **) &FvbProtocol
                               );
    if (EFI_ERROR (Status)) {
      break;
    }

    //
    // Ensure this FVB protocol supported Write operation.
    //
    Status = FvbProtocol->GetAttributes (FvbProtocol, &Attributes);
    if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
      continue;     
    }

    Status            = FvbProtocol->GetPhysicalAddress (
                                       FvbProtocol,
                                       &BaseAddress
                                      );
    if (EFI_ERROR (Status)) {
      break;
    }
    if (BaseAddress == ConfigData->BaseAddress) {
      Found           = TRUE;
      break;
    }
  }

  if (!Found) {
    if (HandleBuffer != NULL) {
      FreePool (HandleBuffer);
      HandleBuffer = NULL;
    }
    return EFI_NOT_FOUND;
  }

  //
  // Now we have got the corresponding FVB protocol. Use the FVB protocol
  // to update the whole FV, or certain files in the FV.
  //
  if (ConfigData->UpdateType == UpdateWholeFV) {
    if (FileType != EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) {
      Status    = EFI_INVALID_PARAMETER;
    } else {
      Status    = PerformUpdateOnWholeFv (
                    HandleBuffer[Index],
                    FvbProtocol,
                    ConfigData,
                    ImageBuffer,
                    ImageSize
                    );
    }
  } else if (ConfigData->UpdateType == UpdateFvFile) {
    Status = PerformUpdateOnFvFile (
               HandleBuffer[Index],
               FvbProtocol,
               ConfigData,
               ImageBuffer,
               ImageSize,
               FileType,
               FileAttributes
               );
  }

  if (HandleBuffer != NULL) {
    FreePool (HandleBuffer);
    HandleBuffer = NULL;
  }

  return Status;
}

/**
  Update the file directly into flash area.

  @param ConfigData      Pointer to the config data on updating file.
  @param ImageBuffer     Image buffer to be updated.
  @param ImageSize       Image size.

  @retval EFI_SUCCESS    The file is updated into flash area.
  @retval EFI_NOT_FOUND  The FVB protocol for the updated flash area is not found.

**/
EFI_STATUS
PerformUpdateOnFlashArea (
  IN UPDATE_CONFIG_DATA                 *ConfigData,
  IN UINT8                              *ImageBuffer,
  IN UINTN                              ImageSize
  )
{
  EFI_STATUS                            Status;
  UINTN                                 SizeLeft;
  EFI_PHYSICAL_ADDRESS                  FlashAddress;
  UINT8                                 *PtrImage;
  BOOLEAN                               Found;
  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *FvbProtocol;
  UINTN                                 Index;
  UINTN                                 NumOfHandles;
  EFI_HANDLE                            *HandleBuffer;
  EFI_PHYSICAL_ADDRESS                  BaseAddress;
  EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader;
  EFI_HANDLE                            FvbHandle;
  UINTN                                 SizeUpdated;
  CHAR16                                *TmpStr;
  EFI_FVB_ATTRIBUTES_2                  Attributes;

  SizeLeft              = ImageSize;
  PtrImage              = ImageBuffer;
  FlashAddress          = ConfigData->BaseAddress;
  Status                = EFI_SUCCESS;
  HandleBuffer          = NULL;

  //
  // Print on screen
  //
  TmpStr = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_FLASH_RANGE), NULL);
  if (TmpStr != NULL) {
    Print (TmpStr, FlashAddress, ((UINT64)SizeLeft + FlashAddress));
    FreePool (TmpStr);
  }
  
  //
  // Locate all Fvb protocol
  //
  Status          = gBS->LocateHandleBuffer (
                           ByProtocol,
                           &gEfiFirmwareVolumeBlockProtocolGuid,
                           NULL,
                           &NumOfHandles,
                           &HandleBuffer
                           );
  if ((EFI_ERROR (Status)) || (NumOfHandles == 0) || (HandleBuffer == NULL)) {
    if (HandleBuffer != NULL) {
      FreePool (HandleBuffer);
    }
    return EFI_NOT_FOUND;
  }

  while (SizeLeft > 0) {
    //
    // First get the FVB protocols. If the flash area is a FV, or sub FV,
    // we can directly locate all the FVB protocol. Otherwise we should use
    // implementation specific method to get the alternate FVB protocol
    //
    Found               = FALSE;
    FvbProtocol         = NULL;

    //
    // Check the FVB protocol one by one
    //
    for (Index = 0; Index < NumOfHandles; Index++) {
      Status        = gBS->HandleProtocol (
                             HandleBuffer[Index],
                             &gEfiFirmwareVolumeBlockProtocolGuid,
                             (VOID **) &FvbProtocol
                             );
      if (EFI_ERROR (Status)) {
        break;
      }

      //
      // Ensure this FVB protocol supported Write operation.
      //
      Status = FvbProtocol->GetAttributes (FvbProtocol, &Attributes);
      if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
        continue;     
      }

      Status        = FvbProtocol->GetPhysicalAddress (
                                     FvbProtocol,
                                     &BaseAddress
                                     );
      if (EFI_ERROR (Status)) {
        break;
      }
      FwVolHeader   = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress;

      //
      // This sub area entry falls in the range of the FV
      //
      if ((FlashAddress >= BaseAddress) && (FlashAddress < (BaseAddress + FwVolHeader->FvLength))) {
        Found       = TRUE;
        break;
      }
    }

    if (!Found) {
      if (HandleBuffer != NULL) {
        FreePool (HandleBuffer);
        HandleBuffer    = NULL;
      }
      return EFI_NOT_FOUND;
    }

    FvbHandle           = HandleBuffer[Index];
    SizeUpdated         = 0;

    //
    // If the flash area is boot required, the update must be fault tolerant
    //
    if (ConfigData->FaultTolerant) {
      //
      // Finally we are here. We have got the corresponding FVB protocol. Now
      // we need to convert the physical address to LBA and offset and call
      // FTW write. Also check if the flash range is larger than the FV.
      //
      Status            = FaultTolerantUpdateOnPartFv (
                            PtrImage,
                            SizeLeft,
                            &SizeUpdated,
                            ConfigData,
                            FlashAddress,
                            FvbProtocol,
                            FvbHandle
                            );
    } else {
      //
      // Finally we are here. We have got the corresponding FVB protocol. Now
      // we need to convert the physical address to LBA and offset and call
      // FVB write. Also check if the flash range is larger than the FV.
      //
      Status            = NonFaultTolerantUpdateOnPartFv (
                            PtrImage,
                            SizeLeft,
                            &SizeUpdated,
                            FlashAddress,
                            FvbProtocol,
                            FvbHandle
                            );
    }

    if (EFI_ERROR (Status)) {
      return Status;
    }

    //
    // As part of the FV has been replaced, the FV driver shall re-parse
    // the firmware volume. So re-install FVB protocol here
    //
    Status                =  gBS->ReinstallProtocolInterface (
                                    FvbHandle,
                                    &gEfiFirmwareVolumeBlockProtocolGuid,
                                    FvbProtocol,
                                    FvbProtocol
                                    );

    if (EFI_ERROR (Status)) {
      return Status;
    }
 
    //
    // Check if we are done with the update
    //
    SizeLeft            = SizeLeft - SizeUpdated;
    FlashAddress        = FlashAddress + SizeUpdated;
    PtrImage            = PtrImage + SizeUpdated;
  }

  if (HandleBuffer != NULL) {
    FreePool (HandleBuffer);
    HandleBuffer = NULL;
  }

  return Status;
}

/**
  Find the updated file, and program it into the flash area based on the config data.

  @param FwVolProtocol   Pointer to FV protocol that contains the updated file.
  @param ConfigData      Pointer to the Config Data on updating file.

  @retval EFI_INVALID_PARAMETER  The update operation is not valid.
  @retval EFI_NOT_FOUND          The updated file is not found.
  @retval EFI_SUCCESS            The file is updated into the flash area.

**/
EFI_STATUS
PerformUpdate (
  IN EFI_FIRMWARE_VOLUME2_PROTOCOL      *FwVolProtocol,
  IN UPDATE_CONFIG_DATA                 *ConfigData
  )
{
  EFI_STATUS                            Status;
  UINT8                                 *FileBuffer;
  UINTN                                 FileBufferSize;
  EFI_FV_FILETYPE                       FileType;
  EFI_FV_FILE_ATTRIBUTES                Attrib;
  EFI_SECTION_TYPE                      SectionType;
  UINT32                                AuthenticationStatus;
  CHAR16                                *TmpStr;
  BOOLEAN                               StartToUpdate;

  Status            = EFI_SUCCESS;
  FileBuffer        = NULL;
  FileBufferSize    = 0;
  Status            = FwVolProtocol->ReadFile (
                                       FwVolProtocol,
                                       &(ConfigData->FileGuid),
                                       (VOID **) &FileBuffer,
                                       &FileBufferSize,
                                       &FileType,
                                       &Attrib,
                                       &AuthenticationStatus
                                       );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  StartToUpdate = FALSE;

  //
  // Check if the update image is the one we require
  // and then perform the update
  //
  switch (ConfigData->UpdateType) {

    case UpdateWholeFV:

      //
      // For UpdateWholeFv, the update file shall be a firmware volume
      // image file.
      //
      if (FileType != EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) {
        DEBUG ((EFI_D_UPDATE, "UpdateDriver: Data file should be of TYPE EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE\n"));
        Status          = EFI_INVALID_PARAMETER;
      } else {
        if (FileBuffer != NULL) {
          FreePool (FileBuffer);
        }
        SectionType     = EFI_SECTION_FIRMWARE_VOLUME_IMAGE;
        FileBuffer      = NULL;
        FileBufferSize  = 0;
        Status          = FwVolProtocol->ReadSection (
                                           FwVolProtocol,
                                           &(ConfigData->FileGuid),
                                           SectionType,
                                           0,
                                           (VOID **) &FileBuffer,
                                           &FileBufferSize,
                                           &AuthenticationStatus
                                           );
        if (!EFI_ERROR (Status)) {
          //
          // Execute the update. For UpdateWholeFv, the update
          // will always execute on a whole FV
          //
          StartToUpdate = TRUE;
          Status        = PerformUpdateOnFirmwareVolume (
                            ConfigData,
                            FileBuffer,
                            FileBufferSize,
                            FileType,
                            Attrib
                            );

        } else {
          DEBUG ((EFI_D_UPDATE, "UpdateDriver: Data file should be sectioned with TYPE EFI_SECTION_FIRMWARE_VOLUME_IMAGE\n"));
        }
      }
      break;

    case UpdateFvRange:

      //
      // For UpdateFvRange, the update file shall be a raw file
      // which does not contain any sections. The contents of the file
      // will be directly programmed.
      //
      if (FileType != EFI_FV_FILETYPE_RAW) {
        DEBUG ((EFI_D_UPDATE, "UpdateDriver: Data file should of TYPE EFI_FV_FILETYPE_RAW\n"));
        Status          = EFI_INVALID_PARAMETER;
      } else {
        //
        // For UpdateFvRange, the update may be performed on a sub area
        // of a certain FV, or a flash area that is not FV, or part of FV.
        // The update may also go across more than one FVs.
        //
        StartToUpdate   = TRUE;
        Status          = PerformUpdateOnFlashArea (
                            ConfigData,
                            FileBuffer,
                            FileBufferSize
                          );
      }
      break;

    case UpdateFvFile:

      //
      // No check will be done the the file got. The contents of the file
      // will be directly programmed.
      // Though UpdateFvFile will only update a single file, but the update
      // will always execute on a FV
      //
      StartToUpdate = TRUE;
      Status        = PerformUpdateOnFirmwareVolume (
                        ConfigData,
                        FileBuffer,
                        FileBufferSize,
                        FileType,
                        Attrib
                        );
      break;

    default:
      Status        = EFI_INVALID_PARAMETER;
  }

  if (StartToUpdate) {
    if (EFI_ERROR (Status)) {
      TmpStr  = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_DRIVER_ABORTED), NULL);
    } else {
      TmpStr  = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_DRIVER_DONE), NULL);
    }
    if (TmpStr != NULL) {
      Print (TmpStr);
      FreePool (TmpStr);
    }
  }

  if (FileBuffer != NULL) {
    FreePool(FileBuffer);
    FileBuffer = NULL;
  }

  return Status;
}

/**
  Process the input firmware volume by using DXE service ProcessFirmwareVolume.

  @param DataBuffer      Point to the FV image to be processed.
  @param BufferSize      Size of the FV image buffer.
  @param FwVolProtocol   Point to the installed FV protocol for the input FV image.

  @retval EFI_OUT_OF_RESOURCES   No enough memory is allocated.
  @retval EFI_VOLUME_CORRUPTED   FV image is corrupted.
  @retval EFI_SUCCESS            FV image is processed and FV protocol is installed.

**/
EFI_STATUS
ProcessUpdateImage (
  UINT8                                 *DataBuffer,
  UINTN                                 BufferSize,
  EFI_FIRMWARE_VOLUME2_PROTOCOL          **FwVolProtocol
  )
{
  EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader;
  EFI_HANDLE                            FwVolHandle;
  EFI_STATUS                            Status;
  UINT8                                 *ProcessedDataBuffer;
  UINT32                                FvAlignment;

  ProcessedDataBuffer = NULL;
  FwVolHeader   = (EFI_FIRMWARE_VOLUME_HEADER *) DataBuffer;
  if (FwVolHeader->FvLength != BufferSize) {
    return EFI_VOLUME_CORRUPTED;
  }

  FvAlignment = 1 << ((FwVolHeader->Attributes & EFI_FVB2_ALIGNMENT) >> 16);
  //
  // FvAlignment must be greater than or equal to 8 bytes of the minimum FFS alignment value.
  // 
  if (FvAlignment < 8) {
    FvAlignment = 8;
  }
  //
  // Check FvImage Align is required.
  //
  if (((UINTN) FwVolHeader % FvAlignment) == 0) {
    ProcessedDataBuffer = DataBuffer;
  } else {
    //
    // Allocate new aligned buffer to store DataBuffer.
    //
    ProcessedDataBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES (BufferSize), (UINTN) FvAlignment);
    if (ProcessedDataBuffer == NULL) {
      return EFI_OUT_OF_RESOURCES;
    }
    CopyMem (ProcessedDataBuffer, DataBuffer, BufferSize);
  }
  //
  // Process the firmware volume
  //
  gDS->ProcessFirmwareVolume (
         ProcessedDataBuffer,
         BufferSize,
         &FwVolHandle
         );

  //
  // Get the FwVol protocol
  //
  Status = gBS->HandleProtocol (
                  FwVolHandle,
                  &gEfiFirmwareVolume2ProtocolGuid,
                  (VOID **) FwVolProtocol
                  );

  return Status;
}

/**
  Find the image in the same FV and program it in a target Firmware Volume device.
  After update image, it will reset system and no return.
  
  @param ImageHandle   A handle for the image that is initializing this driver
  @param SystemTable   A pointer to the EFI system table

  @retval EFI_ABORTED    System reset failed.
  @retval EFI_NOT_FOUND  The updated image is not found in the same FV.

**/
EFI_STATUS
EFIAPI
InitializeUpdateDriver (
  IN EFI_HANDLE                         ImageHandle,
  IN EFI_SYSTEM_TABLE                   *SystemTable
  )
{
  EFI_STATUS                            Status;
  EFI_STATUS                            StatusEsrt;
  EFI_LOADED_IMAGE_PROTOCOL             *LoadedImageProtocol;
  EFI_FIRMWARE_VOLUME2_PROTOCOL         *FwVolProtocol;
  EFI_FIRMWARE_VOLUME2_PROTOCOL         *DataFwVolProtocol;
  MEDIA_FW_VOL_FILEPATH_DEVICE_PATH     *FwVolFilePathNode; 
  MEDIA_FW_VOL_FILEPATH_DEVICE_PATH     *AlignedDevPathNode;
  EFI_DEVICE_PATH_PROTOCOL              *FilePathNode;
  EFI_SECTION_TYPE                      SectionType;
  UINT8                                 *FileBuffer;
  UINTN                                 FileBufferSize;
  EFI_FV_FILETYPE                       FileType;
  EFI_FV_FILE_ATTRIBUTES                Attrib;
  UINT32                                AuthenticationStatus;
  UPDATE_CONFIG_DATA                    *ConfigData;
  UPDATE_CONFIG_DATA                    *UpdateConfigData;
  UINTN                                 NumOfUpdates;
  UINTN                                 Index;
  CHAR16                                *TmpStr;
  ESRT_MANAGEMENT_PROTOCOL              *EsrtManagement;


  ConfigData         = NULL;
  FileBuffer         = NULL;
  AlignedDevPathNode = NULL;

  NewEsrtTemplate.CapsuleFlags = PcdGet16(PcdSystemRebootAfterCapsuleProcessFlag);

  //
  // Clear screen
  //
  //if (gST->ConOut != NULL) {
  //  gST->ConOut->ClearScreen (gST->ConOut);
  //  gST->ConOut->SetAttribute (gST->ConOut, EFI_YELLOW | EFI_BRIGHT);
  //  gST->ConOut->EnableCursor (gST->ConOut, FALSE);
  //}

  gHiiHandle = HiiAddPackages (
                 &gEfiCallerIdGuid,
                 NULL,
                 UpdateDriverDxeStrings,
                 NULL
                 );
  if (gHiiHandle == NULL){
    NewEsrtTemplate.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL;
    Status = EFI_OUT_OF_RESOURCES;
    goto EXIT;
  }

  //
  // In order to look for the update data file and programmed image file
  // from the same volume which this driver is dispatched from, we need
  // to get the device path of this driver image. It is done by first
  // locate the LoadedImageProtocol and then get its device path
  //
  Status            = gBS->OpenProtocol (
                             ImageHandle,
                             &gEfiLoadedImageProtocolGuid,
                             (VOID **)&LoadedImageProtocol,
                             ImageHandle,
                             NULL,
                             EFI_OPEN_PROTOCOL_GET_PROTOCOL
                             );
  if (EFI_ERROR (Status)) {
    NewEsrtTemplate.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL;
    goto EXIT;
  }
  //
  // Get the firmware volume protocol where this file resides
  //
  Status            = gBS->HandleProtocol (
                             LoadedImageProtocol->DeviceHandle,
                             &gEfiFirmwareVolume2ProtocolGuid,
                             (VOID **)  &FwVolProtocol
                             );
  if (EFI_ERROR (Status)) {
    NewEsrtTemplate.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL;
    goto EXIT;
  }

  //
  // Shall do some extra check to see if it is really contained in the FV?
  // Should be able to find the section of this driver in the the FV.
  //
  FilePathNode      = LoadedImageProtocol->FilePath;
  FwVolFilePathNode = NULL;
  while (!IsDevicePathEnd (FilePathNode)) {
    if (EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)FilePathNode)!= NULL) {
      FwVolFilePathNode = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) FilePathNode;
      break;
    }
    FilePathNode    = NextDevicePathNode (FilePathNode);
  }

  if (FwVolFilePathNode == NULL){
    NewEsrtTemplate.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL;
    Status = EFI_NOT_FOUND;
    goto EXIT;
  }

  AlignedDevPathNode = AllocateCopyPool (DevicePathNodeLength (FwVolFilePathNode), FwVolFilePathNode);

  SectionType     = EFI_SECTION_PE32;
  FileBuffer      = NULL;
  FileBufferSize  = 0;
  Status          = FwVolProtocol->ReadSection (
                                     FwVolProtocol,
                                     &(AlignedDevPathNode->FvFileName),
                                     SectionType,
                                     0,
                                     (VOID **) &FileBuffer,
                                     &FileBufferSize,
                                     &AuthenticationStatus
                                     );
  if (EFI_ERROR (Status)) {
    NewEsrtTemplate.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;
    goto EXIT;
  }

  if (FileBuffer != NULL) {
    FreePool(FileBuffer);
    FileBuffer = NULL;
  }

  //
  // Check the NameGuid of the udpate driver so that it can be
  // used as the CallerId in fault tolerant write protocol
  //
  if (!CompareGuid (&gEfiCallerIdGuid, &(AlignedDevPathNode->FvFileName))) {
    NewEsrtTemplate.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;
    Status = EFI_NOT_FOUND;
    goto EXIT;
  }

  FreePool (AlignedDevPathNode);
  AlignedDevPathNode = NULL;
   



  //
  // Now try to find the script file. The script file is usually
  // a raw data file which does not contain any sections.
  //
  FileBuffer        = NULL;
  FileBufferSize    = 0;
  Status            = FwVolProtocol->ReadFile (
                                       FwVolProtocol,
                                       &gEfiConfigFileNameGuid,
                                       (VOID **) &FileBuffer,
                                       &FileBufferSize,
                                       &FileType,
                                       &Attrib,
                                       &AuthenticationStatus
                                       );
  if (EFI_ERROR (Status)) {
    NewEsrtTemplate.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT;
    goto EXIT;
  }
  if (FileType != EFI_FV_FILETYPE_RAW) {
    return EFI_NOT_FOUND;
  }

  //
  // Parse the configuration file.
  //
  ConfigData        = NULL;
  NumOfUpdates      = 0;
  Status            = ParseUpdateDataFile (
                        FileBuffer,
                        FileBufferSize,
                        &NumOfUpdates,
                        &ConfigData
                        );
  if (FileBuffer != NULL) {
    FreePool (FileBuffer);
    FileBuffer = NULL;
  }
  if (EFI_ERROR (Status)) {
    return Status;
  }
  ASSERT (ConfigData != NULL);

  //
  // Now find the update image. The update image should be put in a FV, and then
  // encapsulated as a raw FFS file. This is to prevent the update image from
  // being dispatched. So the raw data we get here should be an FV. We need to
  // process this FV and read the files that is going to be updated.
  //
  FileBuffer        = NULL;
  FileBufferSize    = 0;
  Status            = FwVolProtocol->ReadFile (
                                       FwVolProtocol,
                                       &gEfiUpdateDataFileGuid,
                                       (VOID **) &FileBuffer,
                                       &FileBufferSize,
                                       &FileType,
                                       &Attrib,
                                       &AuthenticationStatus
                                       );
  if (EFI_ERROR (Status)) {
    return Status;
  }
  if (FileType != EFI_FV_FILETYPE_RAW) {
    return EFI_NOT_FOUND;
  }

  //
  // FileBuffer should be an FV. Process the FV
  //
  DataFwVolProtocol = NULL;
  Status            = ProcessUpdateImage (
                        FileBuffer,
                        FileBufferSize,
                        &DataFwVolProtocol
                        );
  if (EFI_ERROR (Status)) {
    FreePool (FileBuffer);
    return Status;
  }

  //
  // Print on screen
  //
  TmpStr  = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_PROCESS_DATA), NULL);
  if (TmpStr != NULL) {
    Print (TmpStr);
    FreePool(TmpStr);
  }

  //
  // Execute the update
  //
  Index = 0;
  UpdateConfigData = ConfigData;
  while (Index < NumOfUpdates) {
    Status = PerformUpdate (
               DataFwVolProtocol,
               UpdateConfigData
               );
    //
    // Shall updates be serialized so that if an update is not successfully completed, 
    // the remaining updates won't be performed.
    //
    if (EFI_ERROR (Status)) {
      NewEsrtTemplate.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL;
      goto EXIT;
    }

    Index++;
    UpdateConfigData++;
  }


EXIT:
  
  //
  // Sucessfully done update job.
  // Need to update system firmware Esrt entry
  //
  EsrtManagement = NULL;
  StatusEsrt = gBS->LocateProtocol (&gEsrtManagementProtocolGuid, NULL, (VOID **) &EsrtManagement);
  if (!EFI_ERROR(StatusEsrt)) {
    EsrtManagement->UpdateEsrtEntry(&NewEsrtTemplate);
  }

  //
  // Do cleanup.
  //
  if (gHiiHandle != NULL) {
    HiiRemovePackages (gHiiHandle);
  }

  if (AlignedDevPathNode != NULL) {
    FreePool (AlignedDevPathNode);
  }

  if (FileBuffer != NULL) {
    FreePool(FileBuffer);
  }

  if (ConfigData != NULL) {
    FreePool(ConfigData);
  }

  return Status;
}