summaryrefslogtreecommitdiff
path: root/EdkCompatibilityPkg/Compatibility/MpServicesOnFrameworkMpServicesThunk/MpServicesOnFrameworkMpServicesThunk.c
blob: f3db9f6b7c01b11037047a2e24d27507199bbed4 (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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
/** @file
Produces PI MP Services Protocol on top of Framework MP Services Protocol.

Intel's Framework MP Services Protocol is replaced by EFI_MP_SERVICES_PROTOCOL in PI 1.1.
This module produces PI MP Services Protocol on top of Framework MP Services Protocol.

Copyright (c) 2009 - 2010, 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.
Module Name:

**/

#include "MpServicesOnFrameworkMpServicesThunk.h"

EFI_HANDLE                          mHandle = NULL;
MP_SYSTEM_DATA                      mMPSystemData;
EFI_PHYSICAL_ADDRESS                mStartupVector;
MP_CPU_EXCHANGE_INFO                *mExchangeInfo;
VOID                                *mStackStartAddress;
BOOLEAN                             mStopCheckAPsStatus = FALSE;
UINTN                               mNumberOfProcessors;
EFI_GENERIC_MEMORY_TEST_PROTOCOL    *mGenMemoryTest;

FRAMEWORK_EFI_MP_SERVICES_PROTOCOL  *mFrameworkMpService;
EFI_MP_SERVICES_PROTOCOL            mMpService = {
  GetNumberOfProcessors,
  GetProcessorInfo,
  StartupAllAPs,
  StartupThisAP,
  SwitchBSP,
  EnableDisableAP,
  WhoAmI
};


/**
  Implementation of GetNumberOfProcessors() service of MP Services Protocol.

  This service retrieves the number of logical processor in the platform
  and the number of those logical processors that are enabled on this boot.
  This service may only be called from the BSP.

  @param  This                       A pointer to the EFI_MP_SERVICES_PROTOCOL instance.
  @param  NumberOfProcessors         Pointer to the total number of logical processors in the system,
                                     including the BSP and disabled APs.
  @param  NumberOfEnabledProcessors  Pointer to the number of enabled logical processors that exist
                                     in system, including the BSP.

  @retval EFI_SUCCESS	             Number of logical processors and enabled logical processors retrieved..
  @retval EFI_DEVICE_ERROR           Caller processor is AP.
  @retval EFI_INVALID_PARAMETER      NumberOfProcessors is NULL
  @retval EFI_INVALID_PARAMETER      NumberOfEnabledProcessors is NULL

**/
EFI_STATUS
EFIAPI
GetNumberOfProcessors (
  IN  EFI_MP_SERVICES_PROTOCOL     *This,
  OUT UINTN                        *NumberOfProcessors,
  OUT UINTN                        *NumberOfEnabledProcessors
  )
{
  EFI_STATUS      Status;
  UINTN           CallerNumber;

  //
  // Check whether caller processor is BSP
  //
  WhoAmI (This, &CallerNumber);
  if (CallerNumber != GetBspNumber ()) {
    return EFI_DEVICE_ERROR;
  }

  //
  // Check parameter NumberOfProcessors
  //
  if (NumberOfProcessors == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Check parameter NumberOfEnabledProcessors
  //
  if (NumberOfEnabledProcessors == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Status = mFrameworkMpService->GetGeneralMPInfo (
                                  mFrameworkMpService,
                                  NumberOfProcessors,
                                  NULL,
                                  NumberOfEnabledProcessors,
                                  NULL,
                                  NULL
                                  );
  ASSERT_EFI_ERROR (Status);

  return EFI_SUCCESS;
}

/**
  Implementation of GetNumberOfProcessors() service of MP Services Protocol.

  Gets detailed MP-related information on the requested processor at the
  instant this call is made. This service may only be called from the BSP.

  @param  This                  A pointer to the EFI_MP_SERVICES_PROTOCOL instance.
  @param  ProcessorNumber       The handle number of processor.
  @param  ProcessorInfoBuffer   A pointer to the buffer where information for the requested processor is deposited.

  @retval EFI_SUCCESS           Processor information successfully returned.
  @retval EFI_DEVICE_ERROR      Caller processor is AP.
  @retval EFI_INVALID_PARAMETER ProcessorInfoBuffer is NULL
  @retval EFI_NOT_FOUND         Processor with the handle specified by ProcessorNumber does not exist.

**/
EFI_STATUS
EFIAPI
GetProcessorInfo (
  IN       EFI_MP_SERVICES_PROTOCOL     *This,
  IN       UINTN                        ProcessorNumber,
  OUT      EFI_PROCESSOR_INFORMATION    *ProcessorInfoBuffer
  )
{
  EFI_STATUS                 Status;
  UINTN                      CallerNumber;
  UINTN                      BufferSize;
  EFI_MP_PROC_CONTEXT        ProcessorContextBuffer;

  //
  // Check whether caller processor is BSP
  //
  WhoAmI (This, &CallerNumber);
  if (CallerNumber != GetBspNumber ()) {
    return EFI_DEVICE_ERROR;
  }

  //
  // Check parameter ProcessorInfoBuffer
  //
  if (ProcessorInfoBuffer == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Check whether processor with the handle specified by ProcessorNumber exists
  //
  if (ProcessorNumber >= mNumberOfProcessors) {
    return EFI_NOT_FOUND;
  }

  BufferSize = sizeof (EFI_MP_PROC_CONTEXT);
  Status = mFrameworkMpService->GetProcessorContext (
                                  mFrameworkMpService,
                                  ProcessorNumber,
                                  &BufferSize,
                                  &ProcessorContextBuffer
                                  );
  ASSERT_EFI_ERROR (Status);

  ProcessorInfoBuffer->ProcessorId = (UINT64) ProcessorContextBuffer.ApicID;

  //
  // Get Status Flag of specified processor
  //
  ProcessorInfoBuffer->StatusFlag = 0;

  if (ProcessorContextBuffer.Enabled) {
    ProcessorInfoBuffer->StatusFlag |= PROCESSOR_ENABLED_BIT;
  }

  if (ProcessorContextBuffer.Designation == EfiCpuBSP) {
    ProcessorInfoBuffer->StatusFlag |= PROCESSOR_AS_BSP_BIT;
  }

  if (ProcessorContextBuffer.Health.Flags.Uint32 == 0) {
    ProcessorInfoBuffer->StatusFlag |= PROCESSOR_HEALTH_STATUS_BIT;
  }

  ProcessorInfoBuffer->Location.Package = (UINT32) ProcessorContextBuffer.PackageNumber;
  ProcessorInfoBuffer->Location.Core    = (UINT32) ProcessorContextBuffer.NumberOfCores;
  ProcessorInfoBuffer->Location.Thread  = (UINT32) ProcessorContextBuffer.NumberOfThreads;

  return EFI_SUCCESS;
}

/**
  Implementation of StartupAllAPs() service of MP Services Protocol.

  This service lets the caller get all enabled APs to execute a caller-provided function.
  This service may only be called from the BSP.

  @param  This                  A pointer to the EFI_MP_SERVICES_PROTOCOL instance.
  @param  Procedure             A pointer to the function to be run on enabled APs of the system.
  @param  SingleThread          Indicates whether to execute the function simultaneously or one by one..
  @param  WaitEvent             The event created by the caller.
                                If it is NULL, then execute in blocking mode.
                                If it is not NULL, then execute in non-blocking mode.
  @param  TimeoutInMicroSeconds The time limit in microseconds for this AP to finish the function.
                                Zero means infinity.
  @param  ProcedureArgument     Pointer to the optional parameter of the assigned function.
  @param  FailedCpuList         The list of processor numbers that fail to finish the function before
                                TimeoutInMicrosecsond expires.

  @retval EFI_SUCCESS           In blocking mode, all APs have finished before the timeout expired.
  @retval EFI_SUCCESS           In non-blocking mode, function has been dispatched to all enabled APs.
  @retval EFI_DEVICE_ERROR      Caller processor is AP.
  @retval EFI_NOT_STARTED       No enabled AP exists in the system.
  @retval EFI_NOT_READY         Any enabled AP is busy.
  @retval EFI_TIMEOUT           In blocking mode, The timeout expired before all enabled APs have finished.
  @retval EFI_INVALID_PARAMETER Procedure is NULL.

**/
EFI_STATUS
EFIAPI
StartupAllAPs (
  IN  EFI_MP_SERVICES_PROTOCOL   *This,
  IN  EFI_AP_PROCEDURE           Procedure,
  IN  BOOLEAN                    SingleThread,
  IN  EFI_EVENT                  WaitEvent             OPTIONAL,
  IN  UINTN                      TimeoutInMicroSeconds,
  IN  VOID                       *ProcedureArgument    OPTIONAL,
  OUT UINTN                      **FailedCpuList       OPTIONAL
  )
{
  EFI_STATUS      Status;
  UINTN           ProcessorNumber;
  CPU_DATA_BLOCK  *CpuData;
  BOOLEAN         Blocking;
  UINTN           BspNumber;

  if (FailedCpuList != NULL) {
    *FailedCpuList = NULL;
  }

  //
  // Check whether caller processor is BSP
  //
  BspNumber = GetBspNumber ();
  WhoAmI (This, &ProcessorNumber);
  if (ProcessorNumber != BspNumber) {
    return EFI_DEVICE_ERROR;
  }

  //
  // Check parameter Procedure
  //
  if (Procedure == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Temporarily suppress CheckAPsStatus()
  //
  mStopCheckAPsStatus = TRUE;

  //
  // Check whether all enabled APs are idle.
  // If any enabled AP is not idle, return EFI_NOT_READY.
  //
  for (ProcessorNumber = 0; ProcessorNumber < mNumberOfProcessors; ProcessorNumber++) {

    CpuData = &mMPSystemData.CpuData[ProcessorNumber];

    mMPSystemData.CpuList[ProcessorNumber] = FALSE;
    if (ProcessorNumber != BspNumber) {
      if (CpuData->State != CpuStateDisabled) {
        if (CpuData->State != CpuStateIdle) {
          mStopCheckAPsStatus = FALSE;
          return EFI_NOT_READY;
        } else {
          //
          // Mark this processor as responsible for current calling.
          //
          mMPSystemData.CpuList[ProcessorNumber] = TRUE;
        }
      }
    }
  }

  mMPSystemData.FinishCount = 0;
  mMPSystemData.StartCount  = 0;
  Blocking                  = FALSE;
  //
  // Go through all enabled APs to wakeup them for Procedure.
  // If in Single Thread mode, then only one AP is woken up, and others are waiting.
  //
  for (ProcessorNumber = 0; ProcessorNumber < mNumberOfProcessors; ProcessorNumber++) {

    CpuData = &mMPSystemData.CpuData[ProcessorNumber];
    //
    // Check whether this processor is responsible for current calling.
    //
    if (mMPSystemData.CpuList[ProcessorNumber]) {

      mMPSystemData.StartCount++;

      AcquireSpinLock (&CpuData->CpuDataLock);
      CpuData->State = CpuStateReady;
      ReleaseSpinLock (&CpuData->CpuDataLock);

      if (!Blocking) {
        WakeUpAp (
          ProcessorNumber,
          Procedure,
          ProcedureArgument
          );
      }

      if (SingleThread) {
        Blocking = TRUE;
      }
    }
  }

  //
  // If no enabled AP exists, return EFI_NOT_STARTED.
  //
  if (mMPSystemData.StartCount == 0) {
    mStopCheckAPsStatus = FALSE;
    return EFI_NOT_STARTED;
  }

  //
  // If WaitEvent is not NULL, execute in non-blocking mode.
  // BSP saves data for CheckAPsStatus(), and returns EFI_SUCCESS.
  // CheckAPsStatus() will check completion and timeout periodically.
  //
  mMPSystemData.Procedure      = Procedure;
  mMPSystemData.ProcArguments  = ProcedureArgument;
  mMPSystemData.SingleThread   = SingleThread;
  mMPSystemData.FailedCpuList  = FailedCpuList;
  mMPSystemData.ExpectedTime   = CalculateTimeout (TimeoutInMicroSeconds, &mMPSystemData.CurrentTime);
  mMPSystemData.WaitEvent      = WaitEvent;

  //
  // Allow CheckAPsStatus()
  //
  mStopCheckAPsStatus = FALSE;

  if (WaitEvent != NULL) {
    return EFI_SUCCESS;
  }

  //
  // If WaitEvent is NULL, execute in blocking mode.
  // BSP checks APs'state until all APs finish or TimeoutInMicrosecsond expires.
  //
  do {
    Status = CheckAllAPs ();
  } while (Status == EFI_NOT_READY);

  return Status;
}

/**
  Implementation of StartupThisAP() service of MP Services Protocol.

  This service lets the caller get one enabled AP to execute a caller-provided function.
  This service may only be called from the BSP.

  @param  This                  A pointer to the EFI_MP_SERVICES_PROTOCOL instance.
  @param  Procedure             A pointer to the function to be run on the designated AP.
  @param  ProcessorNumber       The handle number of AP..
  @param  WaitEvent             The event created by the caller.
                                If it is NULL, then execute in blocking mode.
                                If it is not NULL, then execute in non-blocking mode.
  @param  TimeoutInMicroseconds The time limit in microseconds for this AP to finish the function.
                                Zero means infinity.
  @param  ProcedureArgument     Pointer to the optional parameter of the assigned function.
  @param  Finished              Indicates whether AP has finished assigned function.
                                In blocking mode, it is ignored.

  @retval EFI_SUCCESS           In blocking mode, specified AP has finished before the timeout expires.
  @retval EFI_SUCCESS           In non-blocking mode, function has been dispatched to specified AP.
  @retval EFI_DEVICE_ERROR      Caller processor is AP.
  @retval EFI_TIMEOUT           In blocking mode, the timeout expires before specified AP has finished.
  @retval EFI_NOT_READY         Specified AP is busy.
  @retval EFI_NOT_FOUND         Processor with the handle specified by ProcessorNumber does not exist.
  @retval EFI_INVALID_PARAMETER ProcessorNumber specifies the BSP or disabled AP.
  @retval EFI_INVALID_PARAMETER Procedure is NULL.

**/
EFI_STATUS
EFIAPI
StartupThisAP (
  IN  EFI_MP_SERVICES_PROTOCOL   *This,
  IN  EFI_AP_PROCEDURE           Procedure,
  IN  UINTN                      ProcessorNumber,
  IN  EFI_EVENT                  WaitEvent OPTIONAL,
  IN  UINTN                      TimeoutInMicroseconds,
  IN  VOID                       *ProcedureArgument OPTIONAL,
  OUT BOOLEAN                    *Finished OPTIONAL
  )
{
  CPU_DATA_BLOCK  *CpuData;
  UINTN           CallerNumber;
  EFI_STATUS      Status;
  UINTN           BspNumber;

  if (Finished != NULL) {
    *Finished = TRUE;
  }

  //
  // Check whether caller processor is BSP
  //
  BspNumber = GetBspNumber ();
  WhoAmI (This, &CallerNumber);
  if (CallerNumber != BspNumber) {
    return EFI_DEVICE_ERROR;
  }

  //
  // Check whether processor with the handle specified by ProcessorNumber exists
  //
  if (ProcessorNumber >= mNumberOfProcessors) {
    return EFI_NOT_FOUND;
  }

  //
  // Check whether specified processor is BSP
  //
  if (ProcessorNumber == BspNumber) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Check parameter Procedure
  //
  if (Procedure == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  CpuData = &mMPSystemData.CpuData[ProcessorNumber];

  //
  // Temporarily suppress CheckAPsStatus()
  //
  mStopCheckAPsStatus = TRUE;

  //
  // Check whether specified AP is disabled
  //
  if (CpuData->State == CpuStateDisabled) {
    mStopCheckAPsStatus = FALSE;
    return EFI_INVALID_PARAMETER;
  }

  //
  // Check whether specified AP is busy
  //
  if (CpuData->State != CpuStateIdle) {
    mStopCheckAPsStatus = FALSE;
    return EFI_NOT_READY;
  }

  //
  // Wakeup specified AP for Procedure.
  //
  AcquireSpinLock (&CpuData->CpuDataLock);
  CpuData->State = CpuStateReady;
  ReleaseSpinLock (&CpuData->CpuDataLock);

  WakeUpAp (
    ProcessorNumber,
    Procedure,
    ProcedureArgument
    );

  //
  // If WaitEvent is not NULL, execute in non-blocking mode.
  // BSP saves data for CheckAPsStatus(), and returns EFI_SUCCESS.
  // CheckAPsStatus() will check completion and timeout periodically.
  //
  CpuData->WaitEvent      = WaitEvent;
  CpuData->Finished       = Finished;
  CpuData->ExpectedTime   = CalculateTimeout (TimeoutInMicroseconds, &CpuData->CurrentTime);

  //
  // Allow CheckAPsStatus()
  //
  mStopCheckAPsStatus = FALSE;

  if (WaitEvent != NULL) {
    return EFI_SUCCESS;
  }

  //
  // If WaitEvent is NULL, execute in blocking mode.
  // BSP checks AP's state until it finishes or TimeoutInMicrosecsond expires.
  //
  do {
    Status = CheckThisAP (ProcessorNumber);
  } while (Status == EFI_NOT_READY);

  return Status;
}

/**
  Implementation of SwitchBSP() service of MP Services Protocol.

  This service switches the requested AP to be the BSP from that point onward.
  This service may only be called from the current BSP.

  @param  This                  A pointer to the EFI_MP_SERVICES_PROTOCOL instance.
  @param  ProcessorNumber       The handle number of processor.
  @param  EnableOldBSP          Whether to enable or disable the original BSP.

  @retval EFI_SUCCESS           BSP successfully switched.
  @retval EFI_DEVICE_ERROR      Caller processor is AP.
  @retval EFI_NOT_FOUND         Processor with the handle specified by ProcessorNumber does not exist.
  @retval EFI_INVALID_PARAMETER ProcessorNumber specifies the BSP or disabled AP.
  @retval EFI_NOT_READY         Specified AP is busy.

**/
EFI_STATUS
EFIAPI
SwitchBSP (
  IN  EFI_MP_SERVICES_PROTOCOL            *This,
  IN  UINTN                               ProcessorNumber,
  IN  BOOLEAN                             EnableOldBSP
  )
{
  EFI_STATUS            Status;
  CPU_DATA_BLOCK        *CpuData;
  UINTN                 CallerNumber;
  UINTN                 BspNumber;
  UINTN                 ApicBase;
  UINT32                CurrentTimerValue;
  UINT32                CurrentTimerRegister;
  UINT32                CurrentTimerDivide;
  UINT64                CurrentTscValue;
  BOOLEAN               OldInterruptState;

  //
  // Check whether caller processor is BSP
  //
  BspNumber = GetBspNumber ();
  WhoAmI (This, &CallerNumber);
  if (CallerNumber != BspNumber) {
    return EFI_DEVICE_ERROR;
  }

  //
  // Check whether processor with the handle specified by ProcessorNumber exists
  //
  if (ProcessorNumber >= mNumberOfProcessors) {
    return EFI_NOT_FOUND;
  }

  //
  // Check whether specified processor is BSP
  //
  if (ProcessorNumber == BspNumber) {
    return EFI_INVALID_PARAMETER;
  }

  CpuData = &mMPSystemData.CpuData[ProcessorNumber];

  //
  // Check whether specified AP is disabled
  //
  if (CpuData->State == CpuStateDisabled) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Check whether specified AP is busy
  //
  if (CpuData->State != CpuStateIdle) {
    return EFI_NOT_READY;
  }

  //
  // Save and disable interrupt.
  //
  OldInterruptState = SaveAndDisableInterrupts ();
	
  //
  // Record the current local APIC timer setting of BSP
  //
  ApicBase = (UINTN)AsmMsrBitFieldRead64 (MSR_IA32_APIC_BASE, 12, 35) << 12;
  CurrentTimerValue     = MmioRead32 (ApicBase + APIC_REGISTER_TIMER_COUNT);
  CurrentTimerRegister  = MmioRead32 (ApicBase + APIC_REGISTER_LVT_TIMER);
  CurrentTimerDivide    = MmioRead32 (ApicBase + APIC_REGISTER_TIMER_DIVIDE);
  //
  // Set mask bit (BIT 16) of LVT Timer Register to disable its interrupt
  //
  MmioBitFieldWrite32 (ApicBase + APIC_REGISTER_LVT_TIMER, 16, 16, 1);

  //
  // Record the current TSC value
  //
  CurrentTscValue = AsmReadTsc ();
  
  Status = mFrameworkMpService->SwitchBSP (
                                  mFrameworkMpService,
                                  ProcessorNumber,
                                  EnableOldBSP
                                  );
  ASSERT_EFI_ERROR (Status);

  //
  // Restore TSC value
  //
  AsmWriteMsr64 (MSR_IA32_TIME_STAMP_COUNTER, CurrentTscValue);

  //
  // Restore local APIC timer setting to new BSP
  //
  MmioWrite32 (ApicBase + APIC_REGISTER_TIMER_DIVIDE, CurrentTimerDivide);
  MmioWrite32 (ApicBase + APIC_REGISTER_TIMER_INIT_COUNT, CurrentTimerValue);
  MmioWrite32 (ApicBase + APIC_REGISTER_LVT_TIMER, CurrentTimerRegister);

  //
  // Restore interrupt state.
  //
  SetInterruptState (OldInterruptState);
  
  ChangeCpuState (BspNumber, EnableOldBSP);

  return EFI_SUCCESS;
}

/**
  Implementation of EnableDisableAP() service of MP Services Protocol.

  This service lets the caller enable or disable an AP.
  This service may only be called from the BSP.

  @param  This                   A pointer to the EFI_MP_SERVICES_PROTOCOL instance.
  @param  ProcessorNumber        The handle number of processor.
  @param  EnableAP               Indicates whether the newstate of the AP is enabled or disabled.
  @param  HealthFlag             Indicates new health state of the AP..

  @retval EFI_SUCCESS            AP successfully enabled or disabled.
  @retval EFI_DEVICE_ERROR       Caller processor is AP.
  @retval EFI_NOT_FOUND          Processor with the handle specified by ProcessorNumber does not exist.
  @retval EFI_INVALID_PARAMETERS ProcessorNumber specifies the BSP.

**/
EFI_STATUS
EFIAPI
EnableDisableAP (
  IN  EFI_MP_SERVICES_PROTOCOL            *This,
  IN  UINTN                               ProcessorNumber,
  IN  BOOLEAN                             EnableAP,
  IN  UINT32                              *HealthFlag OPTIONAL
  )
{
  EFI_STATUS      Status;
  UINTN           CallerNumber;
  EFI_MP_HEALTH   HealthState;
  EFI_MP_HEALTH   *HealthStatePointer;
  UINTN           BspNumber;

  //
  // Check whether caller processor is BSP
  //
  BspNumber = GetBspNumber ();
  WhoAmI (This, &CallerNumber);
  if (CallerNumber != BspNumber) {
    return EFI_DEVICE_ERROR;
  }

  //
  // Check whether processor with the handle specified by ProcessorNumber exists
  //
  if (ProcessorNumber >= mNumberOfProcessors) {
    return EFI_NOT_FOUND;
  }

  //
  // Check whether specified processor is BSP
  //
  if (ProcessorNumber == BspNumber) {
    return EFI_INVALID_PARAMETER;
  }

  if (HealthFlag == NULL) {
    HealthStatePointer = NULL;
  } else {
    if ((*HealthFlag & PROCESSOR_HEALTH_STATUS_BIT) == 0) {
      HealthState.Flags.Uint32 = 1;
    } else {
      HealthState.Flags.Uint32 = 0;
    }
    HealthState.TestStatus = 0;

    HealthStatePointer = &HealthState;
  }

  Status = mFrameworkMpService->EnableDisableAP (
                                  mFrameworkMpService,
                                  ProcessorNumber,
                                  EnableAP,
                                  HealthStatePointer
                                  );
  ASSERT_EFI_ERROR (Status);

  ChangeCpuState (ProcessorNumber, EnableAP);

  return EFI_SUCCESS;
}

/**
  Implementation of WhoAmI() service of MP Services Protocol.

  This service lets the caller processor get its handle number.
  This service may be called from the BSP and APs.

  @param  This                  A pointer to the EFI_MP_SERVICES_PROTOCOL instance.
  @param  ProcessorNumber       Pointer to the handle number of AP.

  @retval EFI_SUCCESS           Processor number successfully returned.
  @retval EFI_INVALID_PARAMETER ProcessorNumber is NULL

**/
EFI_STATUS
EFIAPI
WhoAmI (
  IN  EFI_MP_SERVICES_PROTOCOL            *This,
  OUT UINTN                               *ProcessorNumber
  )
{
  EFI_STATUS  Status;

  if (ProcessorNumber == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Status = mFrameworkMpService->WhoAmI (
                                  mFrameworkMpService,
                                  ProcessorNumber
                                  );
  ASSERT_EFI_ERROR (Status);

  return EFI_SUCCESS;
}

/**
  Checks APs' status periodically.

  This function is triggerred by timer perodically to check the
  state of APs for StartupAllAPs() and StartupThisAP() executed
  in non-blocking mode.

  @param  Event    Event triggered.
  @param  Context  Parameter passed with the event.

**/
VOID
EFIAPI
CheckAPsStatus (
  IN  EFI_EVENT                           Event,
  IN  VOID                                *Context
  )
{
  UINTN           ProcessorNumber;
  CPU_DATA_BLOCK  *CpuData;
  EFI_STATUS      Status;

  //
  // If CheckAPsStatus() is stopped, then return immediately.
  //
  if (mStopCheckAPsStatus) {
    return;
  }

  //
  // First, check whether pending StartupAllAPs() exists.
  //
  if (mMPSystemData.WaitEvent != NULL) {

    Status = CheckAllAPs ();
    //
    // If all APs finish for StartupAllAPs(), signal the WaitEvent for it..
    //
    if (Status != EFI_NOT_READY) {
      Status = gBS->SignalEvent (mMPSystemData.WaitEvent);
      mMPSystemData.WaitEvent = NULL;
    }
  }

  //
  // Second, check whether pending StartupThisAPs() callings exist.
  //
  for (ProcessorNumber = 0; ProcessorNumber < mNumberOfProcessors; ProcessorNumber++) {

    CpuData = &mMPSystemData.CpuData[ProcessorNumber];

    if (CpuData->WaitEvent == NULL) {
      continue;
    }

    Status = CheckThisAP (ProcessorNumber);

    if (Status != EFI_NOT_READY) {
      gBS->SignalEvent (CpuData->WaitEvent);
      CpuData->WaitEvent = NULL;
    }
  }
  return ;
}

/**
  Checks status of all APs.

  This function checks whether all APs have finished task assigned by StartupAllAPs(),
  and whether timeout expires.

  @retval EFI_SUCCESS           All APs have finished task assigned by StartupAllAPs().
  @retval EFI_TIMEOUT           The timeout expires.
  @retval EFI_NOT_READY         APs have not finished task and timeout has not expired.

**/
EFI_STATUS
CheckAllAPs (
  VOID
  )
{
  UINTN           ProcessorNumber;
  UINTN           NextProcessorNumber;
  UINTN           ListIndex;
  EFI_STATUS      Status;
  CPU_STATE       CpuState;
  CPU_DATA_BLOCK  *CpuData;

  NextProcessorNumber = 0;

  //
  // Go through all APs that are responsible for the StartupAllAPs().
  //
  for (ProcessorNumber = 0; ProcessorNumber < mNumberOfProcessors; ProcessorNumber++) {
    if (!mMPSystemData.CpuList[ProcessorNumber]) {
      continue;
    }

    CpuData = &mMPSystemData.CpuData[ProcessorNumber];

    //
    //  Check the CPU state of AP. If it is CpuStateFinished, then the AP has finished its task.
    //  Only BSP and corresponding AP access this unit of CPU Data. This means the AP will not modify the
    //  value of state after setting the it to CpuStateFinished, so BSP can safely make use of its value.
    //
    AcquireSpinLock (&CpuData->CpuDataLock);
    CpuState = CpuData->State;
    ReleaseSpinLock (&CpuData->CpuDataLock);

    if (CpuState == CpuStateFinished) {
      mMPSystemData.FinishCount++;
      mMPSystemData.CpuList[ProcessorNumber] = FALSE;

      AcquireSpinLock (&CpuData->CpuDataLock);
      CpuData->State = CpuStateIdle;
      ReleaseSpinLock (&CpuData->CpuDataLock);

      //
      // If in Single Thread mode, then search for the next waiting AP for execution.
      //
      if (mMPSystemData.SingleThread) {
        Status = GetNextWaitingProcessorNumber (&NextProcessorNumber);

        if (!EFI_ERROR (Status)) {
          WakeUpAp (
            NextProcessorNumber,
            mMPSystemData.Procedure,
            mMPSystemData.ProcArguments
            );
        }
      }
    }
  }

  //
  // If all APs finish, return EFI_SUCCESS.
  //
  if (mMPSystemData.FinishCount == mMPSystemData.StartCount) {
    return EFI_SUCCESS;
  }

  //
  // If timeout expires, report timeout.
  //
  if (CheckTimeout (&mMPSystemData.CurrentTime, &mMPSystemData.TotalTime, mMPSystemData.ExpectedTime)) {
    //
    // If FailedCpuList is not NULL, record all failed APs in it.
    //
    if (mMPSystemData.FailedCpuList != NULL) {
      *mMPSystemData.FailedCpuList = AllocatePool ((mMPSystemData.StartCount - mMPSystemData.FinishCount + 1) * sizeof(UINTN));
      ASSERT (*mMPSystemData.FailedCpuList != NULL);
    }
    ListIndex = 0;

    for (ProcessorNumber = 0; ProcessorNumber < mNumberOfProcessors; ProcessorNumber++) {
      //
      // Check whether this processor is responsible for StartupAllAPs().
      //
      if (mMPSystemData.CpuList[ProcessorNumber]) {
        //
        // Reset failed APs to idle state
        //
        ResetProcessorToIdleState (ProcessorNumber);
        mMPSystemData.CpuList[ProcessorNumber] = FALSE;
        if (mMPSystemData.FailedCpuList != NULL) {
          (*mMPSystemData.FailedCpuList)[ListIndex++] = ProcessorNumber;
        }
      }
    }
    if (mMPSystemData.FailedCpuList != NULL) {
      (*mMPSystemData.FailedCpuList)[ListIndex] = END_OF_CPU_LIST;
    }
    return EFI_TIMEOUT;
  }
  return EFI_NOT_READY;
}

/**
  Checks status of specified AP.

  This function checks whether specified AP has finished task assigned by StartupThisAP(),
  and whether timeout expires.

  @param  ProcessorNumber       The handle number of processor.

  @retval EFI_SUCCESS           Specified AP has finished task assigned by StartupThisAPs().
  @retval EFI_TIMEOUT           The timeout expires.
  @retval EFI_NOT_READY         Specified AP has not finished task and timeout has not expired.

**/
EFI_STATUS
CheckThisAP (
  UINTN  ProcessorNumber
  )
{
  CPU_DATA_BLOCK  *CpuData;
  CPU_STATE       CpuState;

  ASSERT (ProcessorNumber < mNumberOfProcessors);
  ASSERT (ProcessorNumber < MAX_CPU_NUMBER);

  CpuData = &mMPSystemData.CpuData[ProcessorNumber];

  //
  //  Check the CPU state of AP. If it is CpuStateFinished, then the AP has finished its task.
  //  Only BSP and corresponding AP access this unit of CPU Data. This means the AP will not modify the
  //  value of state after setting the it to CpuStateFinished, so BSP can safely make use of its value.
  //
  AcquireSpinLock (&CpuData->CpuDataLock);
  CpuState = CpuData->State;
  ReleaseSpinLock (&CpuData->CpuDataLock);

  //
  // If the APs finishes for StartupThisAP(), return EFI_SUCCESS.
  //
  if (CpuState == CpuStateFinished) {

    AcquireSpinLock (&CpuData->CpuDataLock);
    CpuData->State = CpuStateIdle;
    ReleaseSpinLock (&CpuData->CpuDataLock);

    if (CpuData->Finished != NULL) {
      *(CpuData->Finished) = TRUE;
    }
    return EFI_SUCCESS;
  } else {
    //
    // If timeout expires for StartupThisAP(), report timeout.
    //
    if (CheckTimeout (&CpuData->CurrentTime, &CpuData->TotalTime, CpuData->ExpectedTime)) {

      if (CpuData->Finished != NULL) {
        *(CpuData->Finished) = FALSE;
      }
      //
      // Reset failed AP to idle state
      //
      ResetProcessorToIdleState (ProcessorNumber);

      return EFI_TIMEOUT;
    }
  }
  return EFI_NOT_READY;
}

/**
  Calculate timeout value and return the current performance counter value.

  Calculate the number of performance counter ticks required for a timeout.
  If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
  as infinity.

  @param  TimeoutInMicroseconds   Timeout value in microseconds.
  @param  CurrentTime             Returns the current value of the performance counter.

  @return Expected timestamp counter for timeout.
          If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
          as infinity.

**/
UINT64
CalculateTimeout (
  IN  UINTN   TimeoutInMicroseconds,
  OUT UINT64  *CurrentTime
  )
{
  //
  // Read the current value of the performance counter
  //
  *CurrentTime = GetPerformanceCounter ();

  //
  // If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
  // as infinity.
  //
  if (TimeoutInMicroseconds == 0) {
    return 0;
  }

  //
  // GetPerformanceCounterProperties () returns the timestamp counter's frequency
  // in Hz. So multiply the return value with TimeoutInMicroseconds and then divide
  // it by 1,000,000, to get the number of ticks for the timeout value.
  //
  return DivU64x32 (
           MultU64x64 (
             GetPerformanceCounterProperties (NULL, NULL),
             TimeoutInMicroseconds
             ),
           1000000
           );
}

/**
  Checks whether timeout expires.

  Check whether the number of ellapsed performance counter ticks required for a timeout condition
  has been reached.  If Timeout is zero, which means infinity, return value is always FALSE.

  @param  PreviousTime         On input, the value of the performance counter when it was last read.
                               On output, the current value of the performance counter
  @param  TotalTime            The total amount of ellapsed time in performance counter ticks.
  @param  Timeout              The number of performance counter ticks required to reach a timeout condition.

  @retval TRUE                 A timeout condition has been reached.
  @retval FALSE                A timeout condition has not been reached.

**/
BOOLEAN
CheckTimeout (
  IN OUT UINT64  *PreviousTime,
  IN     UINT64  *TotalTime,
  IN     UINT64  Timeout
  )
{
  UINT64  Start;
  UINT64  End;
  UINT64  CurrentTime;
  INT64   Delta;
  INT64   Cycle;

  if (Timeout == 0) {
    return FALSE;
  }
  GetPerformanceCounterProperties (&Start, &End);
  Cycle = End - Start;
  if (Cycle < 0) {
    Cycle = -Cycle;
  }
  Cycle++;
  CurrentTime = GetPerformanceCounter();
  Delta = (INT64) (CurrentTime - *PreviousTime);
  if (Start > End) {
    Delta = -Delta;
  }
  if (Delta < 0) {
    Delta += Cycle;
  }
  *TotalTime += Delta;
  *PreviousTime = CurrentTime;
  if (*TotalTime > Timeout) {
    return TRUE;
  }
  return FALSE;
}

/**
  Searches for the next waiting AP.

  Search for the next AP that is put in waiting state by single-threaded StartupAllAPs().

  @param  NextProcessorNumber  Pointer to the processor number of the next waiting AP.

  @retval EFI_SUCCESS          The next waiting AP has been found.
  @retval EFI_NOT_FOUND        No waiting AP exists.

**/
EFI_STATUS
GetNextWaitingProcessorNumber (
  OUT UINTN                               *NextProcessorNumber
  )
{
  UINTN           ProcessorNumber;

  for (ProcessorNumber = 0; ProcessorNumber < mNumberOfProcessors; ProcessorNumber++) {

    if (mMPSystemData.CpuList[ProcessorNumber]) {
      *NextProcessorNumber = ProcessorNumber;
      return EFI_SUCCESS;
    }
  }

  return EFI_NOT_FOUND;
}

/**
  Programs Local APIC registers for virtual wire mode.

  This function programs Local APIC registers for virtual wire mode.

  @param  Bsp  Indicates whether the programmed processor is going to be BSP

**/
VOID
ProgramVirtualWireMode (
  BOOLEAN                       Bsp
  )
{
  UINTN                 ApicBase;
  UINT32                Value;

  ApicBase = (UINTN)AsmMsrBitFieldRead64 (MSR_IA32_APIC_BASE, 12, 35) << 12;

  //
  // Program the Spurious Vector entry
  // Set bit 8 (APIC Software Enable/Disable) to enable local APIC,
  // and set Spurious Vector as 0x0F.
  //
  MmioBitFieldWrite32 (ApicBase + APIC_REGISTER_SPURIOUS_VECTOR_OFFSET, 0, 9, 0x10F);

  //
  // Program the LINT0 vector entry as ExtInt
  // Set bits 8..10 to 7 as ExtInt Delivery Mode,
  // and clear bits for Delivery Status, Interrupt Input Pin Polarity, Remote IRR,
  // Trigger Mode, and Mask
  //
  if (!Bsp) {
    DisableInterrupts ();
  }
  Value = MmioRead32 (ApicBase + APIC_REGISTER_LINT0_VECTOR_OFFSET);
  Value = BitFieldWrite32 (Value, 8, 10, 7);
  Value = BitFieldWrite32 (Value, 12, 16, 0);
  if (!Bsp) {
    //
    // For APs, LINT0 is masked
    //
    Value = BitFieldWrite32 (Value, 16, 16, 1);
  }
  MmioWrite32 (ApicBase + APIC_REGISTER_LINT0_VECTOR_OFFSET, Value);

  //
  // Program the LINT1 vector entry as NMI
  // Set bits 8..10 to 4 as NMI Delivery Mode,
  // and clear bits for Delivery Status, Interrupt Input Pin Polarity, Remote IRR,
  // Trigger Mode.
  // For BSP clear Mask bit, and for AP set mask bit.
  //
  Value = MmioRead32 (ApicBase + APIC_REGISTER_LINT1_VECTOR_OFFSET);
  Value = BitFieldWrite32 (Value, 8, 10, 4);
  Value = BitFieldWrite32 (Value, 12, 16, 0);
  if (!Bsp) {
    //
    // For APs, LINT1 is masked
    //
    Value = BitFieldWrite32 (Value, 16, 16, 1);
  }
  MmioWrite32 (ApicBase + APIC_REGISTER_LINT1_VECTOR_OFFSET, Value);
}


/**
  Wrapper function for all procedures assigned to AP.

  Wrapper function for all procedures assigned to AP via MP service protocol.
  It controls states of AP and invokes assigned precedure.

**/
VOID
ApProcWrapper (
  VOID
  )
{
  EFI_AP_PROCEDURE      Procedure;
  VOID                  *Parameter;
  UINTN                 ProcessorNumber;
  CPU_DATA_BLOCK        *CpuData;

  //
  // Program virtual wire mode for AP, since it will be lost after AP wake up
  //
  ProgramVirtualWireMode (FALSE);

  //
  // Initialize Debug Agent to support source level debug on AP code.
  //
  InitializeDebugAgent (DEBUG_AGENT_INIT_DXE_AP, NULL, NULL);

  WhoAmI (&mMpService, &ProcessorNumber);
  CpuData = &mMPSystemData.CpuData[ProcessorNumber];

  AcquireSpinLock (&CpuData->CpuDataLock);
  CpuData->State = CpuStateBusy;
  ReleaseSpinLock (&CpuData->CpuDataLock);

  //
  // Now let us check it out.
  //
  AcquireSpinLock (&CpuData->CpuDataLock);
  Procedure = CpuData->Procedure;
  Parameter = CpuData->Parameter;
  ReleaseSpinLock (&CpuData->CpuDataLock);

  if (Procedure != NULL) {

    Procedure (Parameter);

    //
    // if BSP is switched to AP, it continue execute from here, but it carries register state
    // of the old AP, so need to reload CpuData (might be stored in a register after compiler
    // optimization) to make sure it points to the right data
    //
    WhoAmI (&mMpService, &ProcessorNumber);
    CpuData = &mMPSystemData.CpuData[ProcessorNumber];

    AcquireSpinLock (&CpuData->CpuDataLock);
    CpuData->Procedure = NULL;
    ReleaseSpinLock (&CpuData->CpuDataLock);
  }

  AcquireSpinLock (&CpuData->CpuDataLock);
  CpuData->State = CpuStateFinished;
  ReleaseSpinLock (&CpuData->CpuDataLock);
}

/**
  Sends INIT-SIPI-SIPI to AP.

  This function sends INIT-SIPI-SIPI to AP, and assign procedure specified by ApFunction.

  @param  Broadcast   If TRUE, broadcase IPI to all APs; otherwise, send to specified AP.
  @param  ApicID      The Local APIC ID of the specified AP. If Broadcast is TRUE, it is ignored.
  @param  ApFunction  The procedure for AP to work on.

**/
VOID
SendInitSipiSipi (
  IN BOOLEAN            Broadcast,
  IN UINT32             ApicID,
  IN VOID               *ApFunction
  )
{
  UINTN                 ApicBase;
  UINT32                ICRLow;
  UINT32                ICRHigh;

  UINT32                VectorNumber;
  UINT32                DeliveryMode;

  mExchangeInfo->ApFunction = ApFunction;
  mExchangeInfo->StackStart = mStackStartAddress;

  if (Broadcast) {
    ICRHigh = 0;
    ICRLow  = BROADCAST_MODE_ALL_EXCLUDING_SELF_BIT | TRIGGER_MODE_LEVEL_BIT | ASSERT_BIT;
  } else {
    ICRHigh = ApicID << 24;
    ICRLow  = SPECIFY_CPU_MODE_BIT | TRIGGER_MODE_LEVEL_BIT | ASSERT_BIT;
  }

  VectorNumber = 0;
  DeliveryMode = DELIVERY_MODE_INIT;
  ICRLow      |= VectorNumber | (DeliveryMode << 8);

  ApicBase = (UINTN)AsmMsrBitFieldRead64 (MSR_IA32_APIC_BASE, 12, 35) << 12;;

  //
  // Write Interrupt Command Registers to send INIT IPI.
  //
  MmioWrite32 (ApicBase + APIC_REGISTER_ICR_HIGH_OFFSET, ICRHigh);
  MmioWrite32 (ApicBase + APIC_REGISTER_ICR_LOW_OFFSET, ICRLow);

  MicroSecondDelay (10);

  VectorNumber = (UINT32) RShiftU64 (mStartupVector, 12);
  DeliveryMode = DELIVERY_MODE_SIPI;
  if (Broadcast) {
    ICRLow = BROADCAST_MODE_ALL_EXCLUDING_SELF_BIT | TRIGGER_MODE_LEVEL_BIT | ASSERT_BIT;
  } else {
    ICRLow = SPECIFY_CPU_MODE_BIT | TRIGGER_MODE_LEVEL_BIT | ASSERT_BIT;
  }

  ICRLow |= VectorNumber | (DeliveryMode << 8);

  //
  // Write Interrupt Command Register to send first SIPI IPI.
  //
  MmioWrite32 (ApicBase + APIC_REGISTER_ICR_LOW_OFFSET, ICRLow);

  MicroSecondDelay (200);

  //
  // Write Interrupt Command Register to send second SIPI IPI.
  //
  MmioWrite32 (ApicBase + APIC_REGISTER_ICR_LOW_OFFSET, ICRLow);
}

/**
  Function to wake up a specified AP and assign procedure to it.

  @param  ProcessorNumber  Handle number of the specified processor.
  @param  Procedure        Procedure to assign.
  @param  ProcArguments    Argument for Procedure.

**/
VOID
WakeUpAp (
  IN   UINTN                 ProcessorNumber,
  IN   EFI_AP_PROCEDURE      Procedure,
  IN   VOID                  *ProcArguments
  )
{
  EFI_STATUS                   Status;
  CPU_DATA_BLOCK               *CpuData;
  EFI_PROCESSOR_INFORMATION    ProcessorInfoBuffer;

  ASSERT (ProcessorNumber < mNumberOfProcessors);
  ASSERT (ProcessorNumber < MAX_CPU_NUMBER);

  CpuData = &mMPSystemData.CpuData[ProcessorNumber];

  AcquireSpinLock (&CpuData->CpuDataLock);
  CpuData->Parameter  = ProcArguments;
  CpuData->Procedure  = Procedure;
  ReleaseSpinLock (&CpuData->CpuDataLock);

  Status = GetProcessorInfo (
             &mMpService,
             ProcessorNumber,
             &ProcessorInfoBuffer
             );
  ASSERT_EFI_ERROR (Status);

  SendInitSipiSipi (
    FALSE,
    (UINT32) ProcessorInfoBuffer.ProcessorId,
    (VOID *) (UINTN) ApProcWrapper
    );
}

/**
  Terminate AP's task and set it to idle state.

  This function terminates AP's task due to timeout by sending INIT-SIPI,
  and sends it to idle state.

  @param  ProcessorNumber  Handle number of the specified processor.

**/
VOID
ResetProcessorToIdleState (
  UINTN      ProcessorNumber
  )
{
  EFI_STATUS                   Status;
  CPU_DATA_BLOCK               *CpuData;
  EFI_PROCESSOR_INFORMATION    ProcessorInfoBuffer;

  Status = GetProcessorInfo (
             &mMpService,
             ProcessorNumber,
             &ProcessorInfoBuffer
             );
  ASSERT_EFI_ERROR (Status);

  SendInitSipiSipi (
    FALSE,
    (UINT32) ProcessorInfoBuffer.ProcessorId,
    NULL
    );

  CpuData = &mMPSystemData.CpuData[ProcessorNumber];

  AcquireSpinLock (&CpuData->CpuDataLock);
  CpuData->State = CpuStateIdle;
  ReleaseSpinLock (&CpuData->CpuDataLock);
}

/**
  Worker function of EnableDisableAP ()

  Worker function of EnableDisableAP (). Changes state of specified processor.

  @param  ProcessorNumber Processor number of specified AP.
  @param  NewState        Desired state of the specified AP.

  @retval EFI_SUCCESS     AP's state successfully changed.

**/
EFI_STATUS
ChangeCpuState (
  IN     UINTN                      ProcessorNumber,
  IN     BOOLEAN                    NewState
  )
{
  CPU_DATA_BLOCK  *CpuData;

  ASSERT (ProcessorNumber < mNumberOfProcessors);
  ASSERT (ProcessorNumber < MAX_CPU_NUMBER);

  CpuData = &mMPSystemData.CpuData[ProcessorNumber];

  if (!NewState) {
    AcquireSpinLock (&CpuData->CpuDataLock);
    CpuData->State = CpuStateDisabled;
    ReleaseSpinLock (&CpuData->CpuDataLock);
  } else {
    AcquireSpinLock (&CpuData->CpuDataLock);
    CpuData->State = CpuStateIdle;
    ReleaseSpinLock (&CpuData->CpuDataLock);
  }

  return EFI_SUCCESS;
}

/**
  Test memory region of EfiGcdMemoryTypeReserved.

  @param  Length           The length of memory region to test.

  @retval EFI_SUCCESS      The memory region passes test.
  @retval EFI_NOT_FOUND    The memory region is not reserved memory.
  @retval EFI_DEVICE_ERROR The memory fails on test.

**/
EFI_STATUS
TestReservedMemory (
  UINTN  Length
  )
{
  EFI_STATUS                       Status;
  EFI_GCD_MEMORY_SPACE_DESCRIPTOR  Descriptor;
  EFI_PHYSICAL_ADDRESS             Address;
  UINTN                            LengthCovered;
  UINTN                            RemainingLength;

  //
  // Walk through the memory descriptors covering the memory range.
  //
  Address         = mStartupVector;
  RemainingLength = Length;
  while (Address < mStartupVector + Length) {
    Status = gDS->GetMemorySpaceDescriptor(
                    Address,
                    &Descriptor
                    );
    if (EFI_ERROR (Status)) {
      return EFI_NOT_FOUND;
    }

    if (Descriptor.GcdMemoryType != EfiGcdMemoryTypeReserved) {
      return EFI_NOT_FOUND;
    }
    //
    // Calculated the length of the intersected range.
    //
    LengthCovered = (UINTN) (Descriptor.BaseAddress + Descriptor.Length - Address);
    if (LengthCovered > RemainingLength) {
      LengthCovered = RemainingLength;
    }

    Status = mGenMemoryTest->CompatibleRangeTest (
                               mGenMemoryTest,
                               Address,
                               LengthCovered
                               );
    if (EFI_ERROR (Status)) {
      return EFI_DEVICE_ERROR;
    }

    Address         += LengthCovered;
    RemainingLength -= LengthCovered;
  }

  return EFI_SUCCESS;
}

/**
  Allocates startup vector for APs.

  This function allocates Startup vector for APs.

  @param  Size  The size of startup vector.

**/
VOID
AllocateStartupVector (
  UINTN   Size
  )
{
  EFI_STATUS                            Status;

  Status = gBS->LocateProtocol (
                  &gEfiGenericMemTestProtocolGuid,
                  NULL,
                  (VOID **) &mGenMemoryTest
                  );
  if (EFI_ERROR (Status)) {
    mGenMemoryTest = NULL;
  }

  for (mStartupVector = 0x7F000; mStartupVector >= 0x2000; mStartupVector -= EFI_PAGE_SIZE) {
    if (mGenMemoryTest != NULL) {
      //
      // Test memory if it is EfiGcdMemoryTypeReserved.
      //
      Status = TestReservedMemory (EFI_SIZE_TO_PAGES (Size) * EFI_PAGE_SIZE);
      if (Status == EFI_DEVICE_ERROR) {
        continue;
      }
    }

    Status = gBS->AllocatePages (
                    AllocateAddress,
                    EfiBootServicesCode,
                    EFI_SIZE_TO_PAGES (Size),
                    &mStartupVector
                    );

    if (!EFI_ERROR (Status)) {
      break;
    }
  }

  ASSERT_EFI_ERROR (Status);
}

/**
  Prepares Startup Vector for APs.

  This function prepares Startup Vector for APs.

**/
VOID
PrepareAPStartupVector (
  VOID
  )
{
  MP_ASSEMBLY_ADDRESS_MAP   AddressMap;
  IA32_DESCRIPTOR           GdtrForBSP;
  IA32_DESCRIPTOR           IdtrForBSP;
  EFI_PHYSICAL_ADDRESS      GdtForAP;
  EFI_PHYSICAL_ADDRESS      IdtForAP;
  EFI_STATUS                Status;

  //
  // Get the address map of startup code for AP,
  // including code size, and offset of long jump instructions to redirect.
  //
  AsmGetAddressMap (&AddressMap);

  //
  // Allocate a 4K-aligned region under 1M for startup vector for AP.
  // The region contains AP startup code and exchange data between BSP and AP.
  //
  AllocateStartupVector (AddressMap.Size + sizeof (MP_CPU_EXCHANGE_INFO));

  //
  // Copy AP startup code to startup vector, and then redirect the long jump
  // instructions for mode switching.
  //
  CopyMem ((VOID *) (UINTN) mStartupVector, AddressMap.RendezvousFunnelAddress, AddressMap.Size);
  *(UINT32 *) (UINTN) (mStartupVector + AddressMap.FlatJumpOffset + 3) = (UINT32) (mStartupVector + AddressMap.PModeEntryOffset);
  //
  // For IA32 mode, LongJumpOffset is filled with zero. If non-zero, then we are in X64 mode, so further redirect for long mode switch.
  //
  if (AddressMap.LongJumpOffset != 0) {
    *(UINT32 *) (UINTN) (mStartupVector + AddressMap.LongJumpOffset + 2) = (UINT32) (mStartupVector + AddressMap.LModeEntryOffset);
  }

  //
  // Get the start address of exchange data between BSP and AP.
  //
  mExchangeInfo = (MP_CPU_EXCHANGE_INFO *) (UINTN) (mStartupVector + AddressMap.Size);

  ZeroMem ((VOID *) mExchangeInfo, sizeof (MP_CPU_EXCHANGE_INFO));

  mStackStartAddress = AllocatePages (EFI_SIZE_TO_PAGES (MAX_CPU_NUMBER * AP_STACK_SIZE));
  mExchangeInfo->StackSize  = AP_STACK_SIZE;

  AsmReadGdtr (&GdtrForBSP);
  AsmReadIdtr (&IdtrForBSP);

  //
  // Allocate memory under 4G to hold GDT for APs
  //
  GdtForAP = 0xffffffff;
  Status   = gBS->AllocatePages (
                    AllocateMaxAddress,
                    EfiBootServicesData,
                    EFI_SIZE_TO_PAGES ((GdtrForBSP.Limit + 1) + (IdtrForBSP.Limit + 1)),
                    &GdtForAP
                    );
  ASSERT_EFI_ERROR (Status);

  IdtForAP = (UINTN) GdtForAP + GdtrForBSP.Limit + 1;

  CopyMem ((VOID *) (UINTN) GdtForAP, (VOID *) GdtrForBSP.Base, GdtrForBSP.Limit + 1);
  CopyMem ((VOID *) (UINTN) IdtForAP, (VOID *) IdtrForBSP.Base, IdtrForBSP.Limit + 1);

  mExchangeInfo->GdtrProfile.Base  = (UINTN) GdtForAP;
  mExchangeInfo->GdtrProfile.Limit = GdtrForBSP.Limit;
  mExchangeInfo->IdtrProfile.Base  = (UINTN) IdtForAP;
  mExchangeInfo->IdtrProfile.Limit = IdtrForBSP.Limit;

  mExchangeInfo->BufferStart = (UINT32) mStartupVector;
  mExchangeInfo->Cr3         = (UINT32) (AsmReadCr3 ());
}

/**
  Prepares memory region for processor configuration.

  This function prepares memory region for processor configuration.

**/
VOID
PrepareMemoryForConfiguration (
  VOID
  )
{
  UINTN                Index;

  //
  // Initialize Spin Locks for system
  //
  InitializeSpinLock (&mMPSystemData.APSerializeLock);
  for (Index = 0; Index < MAX_CPU_NUMBER; Index++) {
    InitializeSpinLock (&mMPSystemData.CpuData[Index].CpuDataLock);
  }

  PrepareAPStartupVector ();
}

/**
  Gets the processor number of BSP.

  @return  The processor number of BSP.

**/
UINTN
GetBspNumber (
  VOID
  )
{
  UINTN                      ProcessorNumber;
  EFI_MP_PROC_CONTEXT        ProcessorContextBuffer;
  EFI_STATUS                 Status;
  UINTN                      BufferSize;

  BufferSize = sizeof (EFI_MP_PROC_CONTEXT);

  for (ProcessorNumber = 0; ProcessorNumber < mNumberOfProcessors; ProcessorNumber++) {
    Status = mFrameworkMpService->GetProcessorContext (
                                    mFrameworkMpService,
                                    ProcessorNumber,
                                    &BufferSize,
                                    &ProcessorContextBuffer
                                    );
    ASSERT_EFI_ERROR (Status);

    if (ProcessorContextBuffer.Designation == EfiCpuBSP) {
      break;
    }
  }
  ASSERT (ProcessorNumber < mNumberOfProcessors);

  return ProcessorNumber;
}

/**
  Entrypoint of MP Services Protocol thunk driver.

  @param[in] ImageHandle    The firmware allocated handle for the EFI image.
  @param[in] SystemTable    A pointer to the EFI System Table.

  @retval EFI_SUCCESS       The entry point is executed successfully.

**/
EFI_STATUS
EFIAPI
InitializeMpServicesProtocol (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS Status;

  PrepareMemoryForConfiguration ();

  //
  // Locates Framework version MP Services Protocol
  //
  Status = gBS->LocateProtocol (
                  &gFrameworkEfiMpServiceProtocolGuid,
                  NULL,
                  (VOID **) &mFrameworkMpService
                  );
  ASSERT_EFI_ERROR (Status);

  Status = mFrameworkMpService->GetGeneralMPInfo (
                                  mFrameworkMpService,
                                  &mNumberOfProcessors,
                                  NULL,
                                  NULL,
                                  NULL,
                                  NULL
                                  );
  ASSERT_EFI_ERROR (Status);
  ASSERT (mNumberOfProcessors < MAX_CPU_NUMBER);

  //
  // Create timer event to check AP state for non-blocking execution.
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER | EVT_NOTIFY_SIGNAL,
                  TPL_CALLBACK,
                  CheckAPsStatus,
                  NULL,
                  &mMPSystemData.CheckAPsEvent
                  );
  ASSERT_EFI_ERROR (Status);

  //
  // Now install the MP services protocol.
  //
  Status = gBS->InstallProtocolInterface (
                  &mHandle,
                  &gEfiMpServiceProtocolGuid,
                  EFI_NATIVE_INTERFACE,
                  &mMpService
                  );
  ASSERT_EFI_ERROR (Status);

  //
  // Launch the timer event to check AP state.
  //
  Status = gBS->SetTimer (
                  mMPSystemData.CheckAPsEvent,
                  TimerPeriodic,
                  100000
                  );
  ASSERT_EFI_ERROR (Status);

  return EFI_SUCCESS;
}