summaryrefslogtreecommitdiffstats
path: root/src/usr/secureboot/trusted/trustedboot.C
blob: 75f7208a5843cbe4ac66f8fc14a905be7d1adcb4 (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
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/secureboot/trusted/trustedboot.C $                    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2018                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 * @file trustedboot.C
 *
 * @brief Trusted boot interfaces
 */

// ----------------------------------------------
// Includes
// ----------------------------------------------
#include <string.h>
#include <sys/time.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errl/errludtarget.H>
#include <errl/errludstring.H>
#include <targeting/targplatutil.H>
#include <targeting/common/targetservice.H>
#include <secureboot/service.H>
#include <secureboot/trustedbootif.H>
#include <secureboot/trustedboot_reasoncodes.H>
#include <sys/mmio.h>
#include <sys/task.h>
#include <sys/sync.h>
#include <initservice/initserviceif.H>
#ifdef CONFIG_BMC_IPMI
#include <ipmi/ipmisensor.H>
#endif
#include <config.h>
#include <devicefw/driverif.H>
#include <i2c/tpmddif.H>
#include "trustedboot.H"
#include "trustedTypes.H"
#include "trustedbootCmds.H"
#include "trustedbootUtils.H"
#include "tpmLogMgr.H"
#include "base/trustedbootMsg.H"
#include <secureboot/settings.H>
#ifdef CONFIG_DRTM
#include <secureboot/drtm.H>
#endif
#include <fapi2.H>
#include <plat_hwp_invoker.H>
#include <p9_update_security_ctrl.H>
#include <targeting/common/commontargeting.H>
#include <algorithm>
#include <util/misc.H>
#include <hwas/common/hwasCommon.H>

namespace TRUSTEDBOOT
{

extern SystemData systemData;

errlHndl_t getTpmLogDevtreeInfo(
    const TpmTarget* const i_pTpm,
          uint64_t &       io_logAddr,
          size_t &         o_allocationSize,
          uint64_t &       o_xscomAddr,
          uint32_t &       o_i2cMasterOffset)
{
    assert(i_pTpm != nullptr,"getTpmLogDevtreeInfo: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "getTpmLogDevtreeInfo: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;
    auto * const pTpmLogMgr = getTpmLogMgr(i_pTpm);
    TRACUCOMP( g_trac_trustedboot,
               ENTER_MRK"getTpmLogDevtreeInfo() tgt=0x%08X Addr:0x%016lX "
               "0x%016lX",
               TARGETING::get_huid(i_pTpm),
               io_logAddr ,reinterpret_cast<uint64_t>(pTpmLogMgr));

    o_allocationSize = 0;

    auto hwasState = i_pTpm->getAttr<TARGETING::ATTR_HWAS_STATE>();

    if (nullptr != pTpmLogMgr &&
        hwasState.present)
    {
        err = TpmLogMgr_getDevtreeInfo(pTpmLogMgr,
                                       io_logAddr,
                                       o_allocationSize,
                                       o_xscomAddr,
                                       o_i2cMasterOffset);
    }
    TRACUCOMP( g_trac_trustedboot,
               EXIT_MRK"getTpmLogDevtreeInfo() Addr:0x%016lX",io_logAddr);
    return err;
}

void setTpmDevtreeInfo(
    const TpmTarget* const i_pTpm,
    const uint64_t         i_xscomAddr,
    const uint32_t         i_i2cMasterOffset)
{
    assert(i_pTpm != nullptr,"setTpmLogDevtreeInfo: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "setTpmLogDevtreeInfo: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    TRACUCOMP( g_trac_trustedboot,
               ENTER_MRK"setTpmLogDevtreeOffset() tgt=0x%08X "
               "Xscom:0x%016lX Master:0x%08X",
               TARGETING::get_huid(i_pTpm),
               i_xscomAddr, i_i2cMasterOffset);

    auto * const pTpmLogMgr = getTpmLogMgr(i_pTpm);
    if (nullptr != pTpmLogMgr)
    {
        TpmLogMgr_setTpmDevtreeInfo(pTpmLogMgr,
                                    i_xscomAddr, i_i2cMasterOffset);
    }
}

void getTpmWithRoleOf(
    TARGETING::TPM_ROLE const i_tpmRole,
    TARGETING::Target*&       o_pTpm)
{
    o_pTpm = nullptr;
    TARGETING::TargetHandleList tpmList;
    getTPMs(tpmList,TPM_FILTER::ALL_IN_BLUEPRINT);

    TARGETING::PredicateAttrVal<TARGETING::ATTR_TPM_ROLE>
        hasMatchingTpmRole(i_tpmRole);
    auto itr = std::find_if(tpmList.begin(),tpmList.end(),
        [&hasMatchingTpmRole](const TARGETING::Target* const i_pTpm)
        {
            return hasMatchingTpmRole(i_pTpm);
        });
    if(itr!=tpmList.end())
    {
        o_pTpm=*itr;
    }
}

void getPrimaryTpm(TARGETING::Target*& o_pPrimaryTpm)
{
    getTpmWithRoleOf(TARGETING::TPM_ROLE_TPM_PRIMARY,
        o_pPrimaryTpm);
}

void getBackupTpm(TARGETING::Target*& o_pBackupTpm)
{
    getTpmWithRoleOf(TARGETING::TPM_ROLE_TPM_BACKUP,
        o_pBackupTpm);
}

bool enabled()
{
    bool enabled = false;
#ifdef CONFIG_TPMDD
    TARGETING::TargetHandleList tpmList;
    getTPMs(tpmList,TPM_FILTER::ALL_IN_BLUEPRINT);

    TARGETING::PredicateHwas presentAndFunctional;
    presentAndFunctional.present(true);
    presentAndFunctional.functional(true);

    TARGETING::PredicateAttrVal<TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>
        initialized(true);

    auto itr = std::find_if(tpmList.begin(),tpmList.end(),
        [&presentAndFunctional,&initialized](
            const TARGETING::Target* const i_pTpm)
        {
            return (   presentAndFunctional(i_pTpm)
                    || !initialized(i_pTpm));
        });

    enabled = (itr!=tpmList.end()) ? true : false;
#endif
    return enabled;
}

void* host_update_master_tpm( void *io_pArgs )
{
    errlHndl_t err = nullptr;
    bool unlock = false;

    TRACDCOMP( g_trac_trustedboot,
               ENTER_MRK"host_update_master_tpm()" );
    TRACUCOMP( g_trac_trustedboot,
               ENTER_MRK"host_update_master_tpm()");

    // Get all TPMs to setup our array
    TARGETING::TargetHandleList tpmList;
    getTPMs(tpmList,TPM_FILTER::ALL_IN_BLUEPRINT);

    // Currently we only support a MAX of two TPMS per node
    assert(tpmList.size() <= MAX_TPMS_PER_NODE, "Too many TPMs found");

    do
    {
        if (tpmList.empty())
        {
            TRACFCOMP( g_trac_trustedboot,
                       "No TPM Targets found");
            break;
        }

        TARGETING::TargetService& tS = TARGETING::targetService();

        TARGETING::Target* procTarget = nullptr;
        err = tS.queryMasterProcChipTargetHandle( procTarget );
        if (nullptr != err)
        {
            break;
        }

        for(auto tpm : tpmList)
        {
            mutex_lock(tpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>());
        }
        unlock = true;

        // Loop through the TPMs and figure out if they are attached
        //  to the master or alternate master processor
        TPMDD::tpm_info_t tpmData;
        for (auto tpm : tpmList)
        {
            memset(&tpmData, 0, sizeof(tpmData));
            errlHndl_t readErr = tpmReadAttributes(tpm,
                                                   tpmData,
                                                   TPM_LOCALITY_0);
            if (nullptr != readErr)
            {
                // We are just looking for configured TPMs here
                //  so we ignore any errors
                delete readErr;
                readErr = nullptr;
            }
            else
            {
                // If TPM connected to acting master processor, it is
                // primary; otherwise it is backup
                TARGETING::TPM_ROLE tpmRole =
                    (tpmData.i2cTarget == procTarget) ?
                          TARGETING::TPM_ROLE_TPM_PRIMARY
                        : TARGETING::TPM_ROLE_TPM_BACKUP;
                tpm->setAttr<TARGETING::ATTR_TPM_ROLE>(tpmRole);
            }
        }

        // Initialize primary TPM
        TARGETING::Target* pPrimaryTpm = nullptr;
        (void)getPrimaryTpm(pPrimaryTpm);
        if(pPrimaryTpm)
        {
            auto hwasState = pPrimaryTpm->getAttr<TARGETING::ATTR_HWAS_STATE>();
            if(   hwasState.present
               && hwasState.functional)
            {
                // API call will set TPM init attempted appropriately
                tpmInitialize(pPrimaryTpm);
            }
            else
            {
                pPrimaryTpm->setAttr<
                    TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>(true);
            }

            // Allocate TPM log if it hasn't been already
            auto pTpmLogMgr = getTpmLogMgr(pPrimaryTpm);
            // Need to grab state again, as it could have changed
            hwasState = pPrimaryTpm->getAttr<
                TARGETING::ATTR_HWAS_STATE>();
            if(   hwasState.present
               && hwasState.functional
               && nullptr == pTpmLogMgr)
            {
                // @todo RTC:145689 For DRTM we locate the previous SRTM log
                // and reuse.  We must also allocate a DRTM log to be used
                pTpmLogMgr = new TpmLogMgr;
                setTpmLogMgr(pPrimaryTpm,pTpmLogMgr);
                err = TpmLogMgr_initialize(pTpmLogMgr);
                if (nullptr != err)
                {
                    hwasState = pPrimaryTpm->getAttr<
                        TARGETING::ATTR_HWAS_STATE>();
                    hwasState.functional = false;
                    pPrimaryTpm->setAttr<TARGETING::ATTR_HWAS_STATE>(
                        hwasState);
                    break;
                }
            }
        }

        bool primaryTpmAvail = (pPrimaryTpm != nullptr);
        if(primaryTpmAvail)
        {
            auto primaryHwasState = pPrimaryTpm->getAttr<
                TARGETING::ATTR_HWAS_STATE>();
            if (!primaryHwasState.functional ||
                !primaryHwasState.present)
            {
                primaryTpmAvail = false;
            }
        }

        if(!primaryTpmAvail)
        {
            // Primary TPM not available
            TRACFCOMP( g_trac_trustedboot,
                       "Primary TPM Existence Fail");
        }

        TARGETING::Target* pBackupTpm = nullptr;
        getBackupTpm(pBackupTpm);
        if(pBackupTpm == nullptr)
        {
            TRACFCOMP( g_trac_trustedboot,
                       "host_update_master_tpm() "
                       "Backup TPM unavailable "
                       "since it's not in the system blueprint.");
        }
        else
        {
            auto l_backupHwasState = pBackupTpm->getAttr<
                                                  TARGETING::ATTR_HWAS_STATE>();
            TPMDD::tpm_info_t tpmInfo;
            memset(&tpmInfo, 0, sizeof(tpmInfo));
            errlHndl_t tmpErr = TPMDD::tpmReadAttributes(
                                 pBackupTpm,
                                 tpmInfo,
                                 TPM_LOCALITY_0);
            if (nullptr != tmpErr || !tpmInfo.tpmEnabled ||
                (l_backupHwasState.functional && l_backupHwasState.present))
            // If the backup state is functional and present then we are
            // in MPIPL scenario and we need to reset the states
            {
                TRACUCOMP( g_trac_trustedboot,
                           "host_update_master_tpm() "
                           "Marking backup TPM unavailable");

                l_backupHwasState.present = false;
                l_backupHwasState.functional = false;
                pBackupTpm->setAttr<
                    TARGETING::ATTR_HWAS_STATE>(l_backupHwasState);

                if (nullptr != tmpErr)
                {
                    // Ignore attribute read failure
                    delete tmpErr;
                    tmpErr = nullptr;
                }
            }
        }

    } while ( 0 );

    if( unlock )
    {
        for(auto tpm : tpmList)
        {
            mutex_unlock(tpm->getHbMutexAttr<
                TARGETING::ATTR_HB_TPM_MUTEX>());
        }
        unlock = false;
    }

    // Make sure we are in a state
    //  where we have a functional TPM
    TRUSTEDBOOT::tpmVerifyFunctionalTpmExists();

    if (nullptr == err)
    {
        // Start the task to start to handle the message queue/extends
        task_create(&TRUSTEDBOOT::tpmDaemon, nullptr);
    }

    TARGETING::Target* pPrimaryTpm = nullptr;
    (void)getPrimaryTpm(pPrimaryTpm);

    if (nullptr == err)
    {
        // Log config entries to TPM - needs to be after mutex_unlock
        if(pPrimaryTpm)
        {
            err = tpmLogConfigEntries(pPrimaryTpm);
        }
    }

    if(pPrimaryTpm)
    {
        TRACUCOMP( g_trac_trustedboot,
                   "host_update_master_tpm() - "
                   "Primary TPM Present:%d Functional:%d Init Attempted:%d",
                   pPrimaryTpm->getAttr<TARGETING::ATTR_HWAS_STATE>().
                       present,
                   pPrimaryTpm->getAttr<TARGETING::ATTR_HWAS_STATE>().
                       functional,
                   pPrimaryTpm->getAttr<
                       TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>());
    }

    TARGETING::Target* pBackupTpm = nullptr;
    (void)getBackupTpm(pBackupTpm);
    if(pBackupTpm)
    {
        TRACUCOMP( g_trac_trustedboot,
                   "host_update_master_tpm() - "
                   "Backup TPM Present:%d Functional:%d Init Attempted:%d. "
                   "Backup TPM initialization is deferred to istep 10.14.",
                   pBackupTpm->getAttr<TARGETING::ATTR_HWAS_STATE>().
                       present,
                   pBackupTpm->getAttr<TARGETING::ATTR_HWAS_STATE>().
                       functional,
                   pBackupTpm->getAttr<
                       TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>());
    }

    TRACDCOMP( g_trac_trustedboot,
               EXIT_MRK"host_update_master_tpm() - %s",
               ((nullptr == err) ? "No Error" : "With Error") );
    return err;
}

void tpmInitialize(TRUSTEDBOOT::TpmTarget* const i_pTpm)
{
    assert(i_pTpm != nullptr,"tpmInitialize: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmInitialize: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;

    TRACDCOMP( g_trac_trustedboot,
               ENTER_MRK"tpmInitialize()" );
    TRACUCOMP( g_trac_trustedboot,
               ENTER_MRK"tpmInitialize() tgt=0x%08X",
               TARGETING::get_huid(i_pTpm));

    do
    {
        // TPM Initialization sequence
        i_pTpm->setAttr<TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>(true);
        auto hwasState = i_pTpm->getAttr<
            TARGETING::ATTR_HWAS_STATE>();
        hwasState.functional = true;
        i_pTpm->setAttr<
            TARGETING::ATTR_HWAS_STATE>(hwasState);

        // read + write
        bool sendStartup = true;

#ifdef CONFIG_DRTM
        bool drtmMpipl = false;
        (void)SECUREBOOT::DRTM::isDrtmMpipl(drtmMpipl);
        if(drtmMpipl)
        {
            sendStartup = false;
        }
#endif
        // Don't run STARTUP during DRTM
        if (sendStartup)
        {
            // TPM_STARTUP
            err = tpmCmdStartup(i_pTpm);
            if (nullptr != err)
            {
                break;
            }
        }

        // TPM_GETCAPABILITY to read FW Version
        err = tpmCmdGetCapFwVersion(i_pTpm);
        if (nullptr != err)
        {
            break;
        }

#ifdef CONFIG_TPM_NVIDX_VALIDATE
        // Find out if in manufacturing mode
        TARGETING::Target* pTopLevel = nullptr;
        TARGETING::targetService().getTopLevelTarget(pTopLevel);
        assert(pTopLevel != nullptr,"Top level target was nullptr");

        auto mnfgFlags =
            pTopLevel->getAttr<TARGETING::ATTR_MNFG_FLAGS>();

        // Only validate during MFG IPL
        if (mnfgFlags & TARGETING::MNFG_FLAG_SRC_TERM &&
            !Util::isSimicsRunning()) {
            // TPM_GETCAPABILITY to validate NV Indexes
            err = tpmCmdGetCapNvIndexValidate(i_pTpm);
            if (nullptr != err)
            {
                break;
            }
        }
#endif

#ifdef CONFIG_DRTM
        // For a DRTM we need to reset PCRs 17-22
        if (drtmMpipl)
        {
            err = tpmDrtmReset(i_pTpm);
            if (nullptr != err)
            {
                break;
            }
        }
#endif

    } while ( 0 );


    // If the TPM failed we will mark it not functional and commit err
    if (nullptr != err)
    {
        // err will be committed and set to nullptr
        tpmMarkFailed(i_pTpm, err);
    }

    TRACDCOMP( g_trac_trustedboot,
               EXIT_MRK"tpmInitialize()");
}

void tpmReplayLog(TRUSTEDBOOT::TpmTarget* const i_primaryTpm,
                  TRUSTEDBOOT::TpmTarget* const i_backupTpm)
{
    assert(i_primaryTpm != nullptr,
                                 "tpmReplayLog: BUG! i_primaryTpm was nullptr");
    assert(i_backupTpm != nullptr,
                               "tpmReplayLog: BUG! i_backupTpm was nullptr");
    assert(i_primaryTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmReplayLog: BUG! Expected primary target to be of TPM type, but "
           "it was of type 0x%08X",
                                 i_primaryTpm->getAttr<TARGETING::ATTR_TYPE>());
    assert(i_backupTpm->getAttr<TARGETING::ATTR_TYPE>()
                                                         == TARGETING::TYPE_TPM,
           "tpmReplayLog: BUG! Expected secondary target to be of TPM type, but"
           " it was of type 0x%08X",
                               i_backupTpm->getAttr<TARGETING::ATTR_TYPE>());
    TRACUCOMP(g_trac_trustedboot, ENTER_MRK"tpmReplayLog()");

    errlHndl_t err = nullptr;
    bool unMarshalError = false;


    // Create EVENT2 structure to be populated by getNextEvent()
    TCG_PCR_EVENT2 l_eventLog = {0};
    // Move past header event to get a pointer to the first event
    // If there are no events besides the header, l_eventHndl = nullptr
    auto * const pTpmLogMgr = getTpmLogMgr(i_primaryTpm);
    auto * const bTpmLogMgr = getTpmLogMgr(i_backupTpm);
    assert(pTpmLogMgr != nullptr, "tpmReplayLog: BUG! Primary TPM's log manager"
           " is nullptr!");
    assert(bTpmLogMgr != nullptr, "tpmReplayLog: BUG! Backup TPM's log manager"
           " is nullptr!");
    const uint8_t* l_eventHndl = TpmLogMgr_getFirstEvent(pTpmLogMgr);
    while ( l_eventHndl != nullptr )
    {
        // Get next event
        l_eventHndl = TpmLogMgr_getNextEvent(pTpmLogMgr,
                                             l_eventHndl, &l_eventLog,
                                             &unMarshalError);
        if (unMarshalError)
        {
            /*@
             * @errortype
             * @reasoncode     RC_TPM_UNMARSHALING_FAIL
             * @severity       ERRL_SEV_UNRECOVERABLE
             * @moduleid       MOD_TPM_REPLAY_LOG
             * @userdata1      Starting address of event that caused error
             * @userdata2      0
             * @devdesc        Unmarshal error while replaying tpm log.
             */
            err = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                        MOD_TPM_REPLAY_LOG,
                                        RC_TPM_UNMARSHALING_FAIL,
                                        reinterpret_cast<uint64_t>(l_eventHndl),
                                        0,
                                        true /*Add HB SW Callout*/ );

            err->collectTrace( SECURE_COMP_NAME );
            err->collectTrace(TRBOOT_COMP_NAME);
            tpmMarkFailed(i_primaryTpm, err);
            break;
        }

        err = TpmLogMgr_addEvent(bTpmLogMgr, &l_eventLog);
        if(err)
        {
            tpmMarkFailed(i_backupTpm, err);
            break;
        }

        TRACUBIN(g_trac_trustedboot, "tpmReplayLog: Extending event:",
                 &l_eventLog, sizeof(TCG_PCR_EVENT2));
        for (size_t i = 0; i < l_eventLog.digests.count; i++)
        {
            TPM_Alg_Id l_algId = (TPM_Alg_Id)l_eventLog.digests.digests[i]
                                                                   .algorithmId;
            err = tpmCmdPcrExtend(i_backupTpm,
                                  (TPM_Pcr)l_eventLog.pcrIndex,
                                  l_algId,
                                  reinterpret_cast<uint8_t*>
                                      (&(l_eventLog.digests.digests[i].digest)),
                                  getDigestSize(l_algId));
            if (err)
            {
                tpmMarkFailed(i_backupTpm, err);
                break;
            }
        }
        if (err)
        {
            break;
        }
    }

    TRACUCOMP(g_trac_trustedboot, EXIT_MRK"tpmReplayLog()");
}

errlHndl_t tpmLogConfigEntries(TRUSTEDBOOT::TpmTarget* const i_pTpm)
{
    assert(i_pTpm != nullptr,"tpmLogConfigEntries: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmLogConfigEntries: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    TRACUCOMP(g_trac_trustedboot, ENTER_MRK"tpmLogConfigEntries()");

    errlHndl_t l_err = nullptr;

    do
    {
        // Create digest buffer and set to largest config entry size.
        uint8_t l_digest[sizeof(uint64_t)];
        memset(l_digest, 0, sizeof(uint64_t));

        // Security switches
        uint64_t l_securitySwitchValue = 0;
        l_err = SECUREBOOT::getSecuritySwitch(l_securitySwitchValue,
                            TARGETING::MASTER_PROCESSOR_CHIP_TARGET_SENTINEL);
        if (l_err)
        {
            break;
        }
        TRACFCOMP(g_trac_trustedboot, "security switch value = 0x%016lX",
                                l_securitySwitchValue);
        // Extend to TPM - PCR_1
        memcpy(l_digest, &l_securitySwitchValue, sizeof(l_securitySwitchValue));
        l_err = pcrExtend(PCR_1, EV_PLATFORM_CONFIG_FLAGS,
                          l_digest, sizeof(l_securitySwitchValue),
                          "Security Switches");
        if (l_err)
        {
            break;
        }
        memset(l_digest, 0, sizeof(uint64_t));

        // Chip type and EC
        // Fill in the actual PVR of chip
        // Layout of the PVR is (32-bit): (see cpuid.C for latest format)
        //     2 nibbles reserved.
        //     2 nibbles chip type.
        //     1 nibble technology.
        //     1 nibble major DD.
        //     1 nibble reserved.
        //     1 nibble minor D
        uint32_t l_pvr = mmio_pvr_read() & 0xFFFFFFFF;
        TRACDCOMP(g_trac_trustedboot, "PVR of chip = 0x%08X", l_pvr);
        // Extend to TPM - PCR_1
        memcpy(l_digest, &l_pvr, sizeof(l_pvr));
        l_err = pcrExtend(PCR_1, EV_PLATFORM_CONFIG_FLAGS,
                          l_digest, sizeof(l_pvr),"PVR of Chip");
        if (l_err)
        {
            break;
        }
        memset(l_digest, 0, sizeof(uint64_t));

        // Figure out which node we are running on
        TARGETING::Target* l_masterProc = nullptr;
        TARGETING::targetService().masterProcChipTargetHandle(l_masterProc);

        TARGETING::EntityPath l_entityPath =
                        l_masterProc->getAttr<TARGETING::ATTR_PHYS_PATH>();
        const TARGETING::EntityPath::PathElement l_pathElement =
                        l_entityPath.pathElementOfType(TARGETING::TYPE_NODE);
        uint64_t l_nodeid = l_pathElement.instance;
        // Extend to TPM - PCR_1,4,5,6
        memcpy(l_digest, &l_nodeid, sizeof(l_nodeid));
        const TPM_Pcr l_pcrs[] = {PCR_1,PCR_4,PCR_5,PCR_6};
        for (size_t i = 0; i < (sizeof(l_pcrs)/sizeof(TPM_Pcr)) ; ++i)
        {
            l_err = pcrExtend(l_pcrs[i],
                              (l_pcrs[i] == PCR_1 ?
                               EV_PLATFORM_CONFIG_FLAGS : EV_COMPACT_HASH),
                              l_digest, sizeof(l_nodeid),"Node id");
            if (l_err)
            {
                break;
            }
        }
        if (l_err)
        {
            break;
        }

        // TPM Required
        memset(l_digest, 0, sizeof(uint64_t));
        bool l_tpmRequired = isTpmRequired();
        l_digest[0] = static_cast<uint8_t>(l_tpmRequired);
        l_err = pcrExtend(PCR_1, EV_PLATFORM_CONFIG_FLAGS,
                          l_digest, sizeof(l_tpmRequired),
                          "Tpm Required");
        if (l_err)
        {
            break;
        }

        // HW Key Hash
        SHA512_t l_hw_key_hash;
        SECUREBOOT::getHwKeyHash(l_hw_key_hash);
        l_err = pcrExtend(PCR_1, EV_PLATFORM_CONFIG_FLAGS,
                          l_hw_key_hash,
                          sizeof(SHA512_t),"HW KEY HASH");
        if (l_err)
        {
            break;
        }

    } while(0);

    return l_err;
}

void pcrExtendSingleTpm(TpmTarget* const i_pTpm,
                        const TPM_Pcr i_pcr,
                        const EventTypes i_eventType,
                        TPM_Alg_Id i_algId,
                        const uint8_t* i_digest,
                        size_t  i_digestSize,
                        const char* i_logMsg)
{
    assert(i_pTpm != nullptr,"pcrExtendSingleTpm: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "pcrExtendSingleTpm: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;
    TCG_PCR_EVENT2 eventLog;
    bool unlock = false;

    TPM_Pcr pcr = i_pcr;
    bool useStaticLog = true;

#ifdef CONFIG_DRTM
    // In a DRTM flow, all extensions must be re-rerouted to PCR 17
    // (which will end up using locality 2).
    bool drtmMpipl = false;
    (void)SECUREBOOT::DRTM::isDrtmMpipl(drtmMpipl);
    if(drtmMpipl)
    {
        TRACFCOMP(g_trac_trustedboot,
            INFO_MRK " pcrExtendSingleTpm(): DRTM active; re-routing PCR %d "
            "extend to PCR 17",
            i_pcr);

        pcr = PCR_DRTM_17;
        useStaticLog = false;
    }
#endif

    memset(&eventLog, 0, sizeof(eventLog));
    do
    {
        mutex_lock( i_pTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>() ) ;
        unlock = true;

        auto hwasState = i_pTpm->getAttr<TARGETING::ATTR_HWAS_STATE>();

        // Log the event
        if (hwasState.present &&
             hwasState.functional)
        {
            // Fill in TCG_PCR_EVENT2 and add to log
            eventLog = TpmLogMgr_genLogEventPcrExtend(pcr, i_eventType,
                                                      i_algId, i_digest,
                                                      i_digestSize,
                                                      TPM_ALG_SHA1, i_digest,
                                                      i_digestSize,
                                                      i_logMsg);
            if(useStaticLog)
            {
                auto * const pTpmLogMgr = getTpmLogMgr(i_pTpm);
                err = TpmLogMgr_addEvent(pTpmLogMgr,&eventLog);
                if (nullptr != err)
                {
                    break;
                }
            }

            // TODO: RTC 145689: Add DRTM support for using dynamic
            // log instead of static log; until then, inhibit DRTM logging
            // entirely

            // Perform the requested extension and also force into the
            // SHA1 bank
            err = tpmCmdPcrExtend2Hash(i_pTpm,
                                       pcr,
                                       i_algId,
                                       i_digest,
                                       i_digestSize,
                                       TPM_ALG_SHA1,
                                       i_digest,
                                       i_digestSize);
        }
    } while ( 0 );

    if (nullptr != err)
    {
        // We failed to extend to this TPM we can no longer use it
        // Mark TPM as not functional, commit err and set it to nullptr
        tpmMarkFailed(i_pTpm, err);
    }

    if (unlock)
    {
        mutex_unlock( i_pTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>() ) ;
    }
    return;
}

void pcrExtendSeparator(TpmTarget* const i_pTpm)
{
    assert(i_pTpm != nullptr,"pcrExtendSeparator: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "pcrExtendSeparator: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;
    TCG_PCR_EVENT2 eventLog = {0};
    bool unlock = false;

    // Separators are always the same values
    // The digest is a sha1 hash of 0xFFFFFFFF
    const uint8_t sha1_digest[] = {
        0xd9, 0xbe, 0x65, 0x24, 0xa5, 0xf5, 0x04, 0x7d,
        0xb5, 0x86, 0x68, 0x13, 0xac, 0xf3, 0x27, 0x78,
        0x92, 0xa7, 0xa3, 0x0a};
    // The digest is a sha256 hash of 0xFFFFFFFF
    const uint8_t sha256_digest[] = {
        0xAD, 0x95, 0x13, 0x1B, 0xC0, 0xB7, 0x99, 0xC0,
        0xB1, 0xAF, 0x47, 0x7F, 0xB1, 0x4F, 0xCF, 0x26,
        0xA6, 0xA9, 0xF7, 0x60, 0x79, 0xE4, 0x8B, 0xF0,
        0x90, 0xAC, 0xB7, 0xE8, 0x36, 0x7B, 0xFD, 0x0E};
    // The event message is 0xFFFFFFFF
    const char logMsg[] = { 0xFF, 0xFF, 0xFF, 0xFF, '\0'};

    memset(&eventLog, 0, sizeof(eventLog));
    do
    {
        mutex_lock( i_pTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>() ) ;
        unlock = true;

        std::vector<TPM_Pcr> pcrs =
            {PCR_0,PCR_1,PCR_2,PCR_3,PCR_4,PCR_5,PCR_6,PCR_7};
        bool useStaticLog = true;

#ifdef CONFIG_DRTM
        // In a DRTM flow, all extensions must be re-rerouted to PCR 17
        // (which will end up using locality 2).
        bool drtmMpipl = false;
        (void)SECUREBOOT::DRTM::isDrtmMpipl(drtmMpipl);
        if(drtmMpipl)
        {
            TRACFCOMP(g_trac_trustedboot,
                INFO_MRK " pcrExtendSeparator(): DRTM active; extending "
                "separator to PCR 17 instead of PCR 0..7.");

            pcrs = { PCR_DRTM_17 };
            useStaticLog = false;
        }
#endif

        for (const auto &pcr : pcrs)
        {
            auto hwasState = i_pTpm->getAttr<
                TARGETING::ATTR_HWAS_STATE>();

            // Log the separator
            if (hwasState.present &&
                hwasState.functional)
            {
                // Fill in TCG_PCR_EVENT2 and add to log
                eventLog = TpmLogMgr_genLogEventPcrExtend(pcr,
                                                          EV_SEPARATOR,
                                                          TPM_ALG_SHA1,
                                                          sha1_digest,
                                                          sizeof(sha1_digest),
                                                          TPM_ALG_SHA256,
                                                          sha256_digest,
                                                          sizeof(sha256_digest),
                                                          logMsg);

                if(useStaticLog)
                {
                    auto * const pTpmLogMgr = getTpmLogMgr(i_pTpm);
                    err = TpmLogMgr_addEvent(pTpmLogMgr,&eventLog);
                    if (nullptr != err)
                    {
                        break;
                    }
                }

                // TODO: RTC 145689: Add DRTM support for using dynamic
                // log (which will happen any time useStaticLog is false).
                // Until then, we cannot log DRTM events, since they are only
                // allowed to go to the dynamic log

                // Perform the requested extension
                err = tpmCmdPcrExtend2Hash(i_pTpm,
                                           pcr,
                                           TPM_ALG_SHA1,
                                           sha1_digest,
                                           sizeof(sha1_digest),
                                           TPM_ALG_SHA256,
                                           sha256_digest,
                                           sizeof(sha256_digest));
                if (nullptr != err)
                {
                    break;
                }

            }
        }

    } while ( 0 );

    if (nullptr != err)
    {
        // We failed to extend to this TPM we can no longer use it
        // Mark TPM as not functional, commit err and set it to nullptr
        tpmMarkFailed(i_pTpm, err);

        // Log this failure
        errlCommit(err, TRBOOT_COMP_ID);
    }

    if (unlock)
    {
        mutex_unlock( i_pTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>() ) ;
    }
    return;
}

void tpmMarkFailed(TpmTarget* const i_pTpm,
                   errlHndl_t& io_err)
{
    assert(i_pTpm != nullptr,"tpmMarkFailed: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmMarkFailed: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    TRACFCOMP( g_trac_trustedboot,
               ENTER_MRK"tpmMarkFailed() Marking TPM as failed : "
               "tgt=0x%08X; io_err rc=0x%04X, plid=0x%08X",
               TARGETING::get_huid(i_pTpm), ERRL_GETRC_SAFE(io_err),
               ERRL_GETPLID_SAFE(io_err));

    auto hwasState = i_pTpm->getAttr<
        TARGETING::ATTR_HWAS_STATE>();
    hwasState.functional = false;
    i_pTpm->setAttr<
        TARGETING::ATTR_HWAS_STATE>(hwasState);

    #ifdef CONFIG_SECUREBOOT
    TARGETING::Target* l_tpm = i_pTpm;

    errlHndl_t l_err = nullptr;
    TARGETING::Target* l_proc = nullptr;

    do {

    if (!SECUREBOOT::enabled())
    {
        break;
    }

    // for the given tpm target, find the processor target
    TARGETING::TargetHandleList l_procList;
    getAllChips(l_procList,TARGETING::TYPE_PROC,false);

    auto l_tpmInfo = l_tpm->getAttr<TARGETING::ATTR_TPM_INFO>();

    for(auto it : l_procList)
    {
        auto l_physPath = it->getAttr<TARGETING::ATTR_PHYS_PATH>();
        if (l_tpmInfo.i2cMasterPath == l_physPath)
        {
            // found processor to deconfigure
            l_proc = it;
            break;
        }
    }
    if (l_proc == nullptr)
    {
        assert(false,"tpmMarkFailed - TPM with non-existent processor indicates"
            " a bad MRW. TPM tgt=0x%08X", TARGETING::get_huid(l_tpm));
    }

    // set ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM for the processor
    uint8_t l_protectTpm = 1;
    l_proc->setAttr<TARGETING::ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM>(
        l_protectTpm);

    // do not deconfigure the processor if it already deconfigured
    TARGETING::PredicateHwas isNonFunctional;
    isNonFunctional.functional(false);
    if (isNonFunctional(l_proc))
    {
        // Note: at this point l_err is nullptr so
        // no error log is created on break
        break;
    }

    uint64_t l_regValue = 0;
    l_err = SECUREBOOT::getSecuritySwitch(l_regValue, l_proc);
    if (l_err)
    {
        TRACFCOMP(g_trac_trustedboot,
            ERR_MRK"tpmMarkFailed - call to getSecuritySwitch failed");
        break;
    }
    // if the SBE lock bit is not set, it means that istep 10.3 hasn't executed
    // yet, so we will let istep 10.3 call p9_update_security_control HWP
    // if the SBE lock bit is set, then we will call the HWP here
    if (!(l_regValue & static_cast<uint64_t>(SECUREBOOT::ProcSecurity::SULBit)))
    {
        break;
    }

    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapiTarg(l_proc);

    FAPI_INVOKE_HWP(l_err, p9_update_security_ctrl, l_fapiTarg);

    if (l_err)
    {
        TRACFCOMP(g_trac_trustedboot,
            ERR_MRK"tpmMarkFailed - call to p9_update_security_ctrl failed ");
    }

    } while(0);

    // If we got a local error log, link it to input error log and then
    // commit it
    if (l_err)
    {
        // commit this error log first before creating the new one
        auto plid = l_err->plid();

        // If we have an input error log then link these all together
        if (io_err)
        {
           TRACFCOMP(g_trac_trustedboot,
                ERR_MRK "tpmMarkFailed(): Processor tgt=0x%08X TPM tgt=0x%08X. "
                "Deconfiguring proc because future security cannot be "
                "guaranteed. Linking new l_err rc=0x%04X eid=0x%08X to "
                "io_err rc=0x%04X, plid=0x%08X",
                TARGETING::get_huid(l_proc),
                TARGETING::get_huid(l_tpm),
                l_err->reasonCode(), l_err->eid(),
                io_err->reasonCode(), io_err->plid());

            // Use io_err's plid to link all errors together
            plid = io_err->plid();
            l_err->plid(plid);
        }
        else
        {
            TRACFCOMP(g_trac_trustedboot,
                ERR_MRK "tpmMarkFailed(): Processor tgt=0x%08X TPM tgt=0x%08X: "
                "Deconfiguring proc because future security cannot be "
                "guaranteed due to new l_err rc=0x%04X plid=0x%08X",
                TARGETING::get_huid(l_proc),
                TARGETING::get_huid(l_tpm),
                l_err->reasonCode(), l_err->plid());
        }

        ERRORLOG::ErrlUserDetailsTarget(l_proc).addToLog(l_err);
        l_err->collectTrace(SECURE_COMP_NAME);
        l_err->collectTrace(TRBOOT_COMP_NAME);

        // commit this error log first before creating the new one
        errlCommit(l_err, TRBOOT_COMP_ID);

       /*@
        * @errortype
        * @reasoncode       TRUSTEDBOOT::RC_UPDATE_SECURITY_CTRL_HWP_FAIL
        * @moduleid         TRUSTEDBOOT::MOD_TPM_MARK_FAILED
        * @severity         ERRL_SEV_UNRECOVERABLE
        * @userdata1        Processor Target
        * @userdata2        TPM Target
        * @devdesc          Failed to set SEEPROM lock and/or TPM deconfig
        *                   protection for this processor, so we cannot
        *                   guarrantee platform secuirty for this processor
        * @custdesc         Platform security problem detected
        */
        l_err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
            TRUSTEDBOOT::MOD_TPM_MARK_FAILED,
            TRUSTEDBOOT::RC_UPDATE_SECURITY_CTRL_HWP_FAIL,
            TARGETING::get_huid(l_proc),
            TARGETING::get_huid(l_tpm));

        // Pass on the plid to connect all previous error(s)
        l_err->plid(plid);

       TRACFCOMP(g_trac_trustedboot,
            ERR_MRK "tpmMarkFailed(): Processor tgt=0x%08X TPM tgt=0x%08X. "
            "Deconfiguring proc errorlog is rc=0x%04X plid=0x%08X, eid=0x%08X",
            TARGETING::get_huid(l_proc),
            TARGETING::get_huid(l_tpm),
            l_err->reasonCode(), l_err->plid(), l_err->eid());

        l_err->addHwCallout(l_proc,
                            HWAS::SRCI_PRIORITY_LOW,
                            HWAS::DELAYED_DECONFIG,
                            HWAS::GARD_NULL);

        l_err->collectTrace(SECURE_COMP_NAME);
        l_err->collectTrace(TRBOOT_COMP_NAME);

        ERRORLOG::ErrlUserDetailsTarget(l_proc).addToLog(l_err);

        ERRORLOG::errlCommit(l_err, TRBOOT_COMP_ID);
    }
    #endif

    // Commit input error log
    if (io_err)
    {
       TRACFCOMP(g_trac_trustedboot,
            ERR_MRK "Committing io_err rc=0x%04X plid=0x%08X, eid=0x%08X",
            io_err->reasonCode(), io_err->plid(), io_err->eid());

        io_err->collectTrace(SECURE_COMP_NAME);
        io_err->collectTrace(TRBOOT_COMP_NAME);

        ERRORLOG::errlCommit(io_err, TRBOOT_COMP_ID);
    }

}

void tpmVerifyFunctionalTpmExists(
    const NoTpmShutdownPolicy i_noTpmShutdownPolicy)
{
    errlHndl_t err = nullptr;
    bool foundFunctional = enabled();
    const bool isBackgroundShutdown =
        (i_noTpmShutdownPolicy == NoTpmShutdownPolicy::BACKGROUND_SHUTDOWN);

    if (!foundFunctional && !systemData.failedTpmsPosted)
    {
        systemData.failedTpmsPosted = true;
        TRACFCOMP( g_trac_trustedboot,
                   "NO FUNCTIONAL TPM FOUND");

        // Check to ensure jumper indicates we are running secure
        SECUREBOOT::SecureJumperState l_state
                          = SECUREBOOT::SecureJumperState::SECURITY_DEASSERTED;
        err = SECUREBOOT::getJumperState(l_state);
        if (err)
        {
            auto errPlid = err->plid();
            errlCommit(err, TRBOOT_COMP_ID);

            // we should not continue if we could not read the jumper state
            INITSERVICE::doShutdown(errPlid,isBackgroundShutdown);
        }
        else if (l_state == SECUREBOOT::SecureJumperState::SECURITY_ASSERTED)
        {
            if (isTpmRequired())
            {
                /*@
                 * @errortype
                 * @reasoncode     RC_TPM_NOFUNCTIONALTPM_FAIL
                 * @severity       ERRL_SEV_UNRECOVERABLE
                 * @moduleid       MOD_TPM_VERIFYFUNCTIONAL
                 * @userdata1      0
                 * @userdata2      0
                 * @devdesc        The system is configured in the hardware
                 *                 (via processor secure jumpers) to enable
                 *                 Secure Boot, and the system's "TPM required"
                 *                 policy is configured to require at least one
                 *                 functional TPM in order to boot with Secure
                 *                 Boot enabled. Therefore, the system will
                 *                 terminate due to lack of functional TPMs.
                 * @custdesc       The system is configured for Secure Boot and
                 *                 trusted platform module required mode; at
                 *                 least one functional trusted platform module
                 *                 is required to boot the system, but none are
                 *                 available.  Therefore, the system will
                 *                 terminate.
                 *                 Trusted platform module required mode may be
                 *                 disabled via the appropriate systems
                 *                 management interface to allow platform boot
                 *                 without the remote trusted attestation
                 *                 capability. Look for other errors which call
                 *                 out the trusted platform module and follow
                 *                 the repair actions for these errors.
                 */
                err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                              MOD_TPM_VERIFYFUNCTIONAL,
                                              RC_TPM_NOFUNCTIONALTPM_FAIL);

                // Add low priority HB SW callout
                err->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE,
                                         HWAS::SRCI_PRIORITY_LOW);
                err->collectTrace( SECURE_COMP_NAME );
                err->collectTrace(TRBOOT_COMP_NAME);
                err->collectTrace( I2C_COMP_NAME );
                err->collectTrace( TPMDD_COMP_NAME );
                uint32_t errPlid = err->plid();

                // Add Security Registers to the error log
                SECUREBOOT::addSecurityRegistersToErrlog(err);

                // HW callout TPMs
                TARGETING::TargetHandleList l_tpmList;
                TRUSTEDBOOT::getTPMs(l_tpmList, TPM_FILTER::ALL_IN_BLUEPRINT);
                for(const auto &tpm : l_tpmList)
                {
                    err->addHwCallout(tpm,
                                      HWAS::SRCI_PRIORITY_HIGH,
                                      HWAS::NO_DECONFIG,
                                      HWAS::GARD_NULL);
                }
                errlCommit(err, TRBOOT_COMP_ID);
                // terminating the IPL with this fail
                // Terminate IPL immediately
                INITSERVICE::doShutdown(errPlid,isBackgroundShutdown);
            }
            else
            {
                TRACUCOMP( g_trac_trustedboot,
                           "No functional TPM's found but TPM not Required");
            }
        }
        else
        {
            TRACUCOMP( g_trac_trustedboot,
                       "No functional TPM's found but not running secure");
        }

    }

    return;
}

void doInitBackupTpm()
{
    TARGETING::Target* l_backupTpm = nullptr;
    errlHndl_t l_errl = nullptr;
    TRUSTEDBOOT::getBackupTpm(l_backupTpm);

    do {
    if(l_backupTpm)
    {
        auto l_backupHwasState = l_backupTpm->getAttr<
                                                  TARGETING::ATTR_HWAS_STATE>();
        // Presence-detect the secondary TPM
        TARGETING::TargetHandleList l_targetList;
        l_targetList.push_back(l_backupTpm);
        l_errl = HWAS::platPresenceDetect(l_targetList);
        if(l_errl)
        {
            errlCommit(l_errl, SECURE_COMP_ID);
            break;
        }

        // The TPM target would have been deleted from the list if it's
        // not present.
        if(l_targetList.size())
        {
            l_backupHwasState.present = true;
            l_backupTpm->setAttr<TARGETING::ATTR_HWAS_STATE>(l_backupHwasState);
        }
        else
        {
            l_backupHwasState.present = false;
            l_backupTpm->setAttr<TARGETING::ATTR_HWAS_STATE>(l_backupHwasState);
            break;
        }

        mutex_lock(l_backupTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>());
        tpmInitialize(l_backupTpm);
        TpmLogMgr* l_tpmLogMgr = getTpmLogMgr(l_backupTpm);
        if(!l_tpmLogMgr)
        {
            l_tpmLogMgr = new TpmLogMgr;
            setTpmLogMgr(l_backupTpm, l_tpmLogMgr);
            l_errl = TpmLogMgr_initialize(l_tpmLogMgr);
            if(l_errl)
            {
                l_backupHwasState.functional = false;
                l_backupTpm->setAttr<TARGETING::ATTR_HWAS_STATE>
                                                            (l_backupHwasState);
                errlCommit(l_errl, SECURE_COMP_ID);
                mutex_unlock(l_backupTpm->
                                getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>());
                break;
            }
        }
        mutex_unlock(l_backupTpm->
                                getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>());

        TARGETING::Target* l_primaryTpm = nullptr;
        getPrimaryTpm(l_primaryTpm);
        if(l_primaryTpm)
        {
            auto l_primaryHwasState = l_primaryTpm->getAttr<
                                                  TARGETING::ATTR_HWAS_STATE>();
            if(l_primaryHwasState.functional && l_primaryHwasState.present)
            {
                tpmReplayLog(l_primaryTpm, l_backupTpm);
            }
        }

        l_errl = TRUSTEDBOOT::testCmpPrimaryAndBackupTpm();
        if(l_errl)
        {
            errlCommit(l_errl, SECURE_COMP_ID);
            break;
        }
    }
    else
    {
        TRACFCOMP(g_trac_trustedboot, "tpmDaemon: Backup TPM init message was"
                  " received but the backup TPM cannot be found.");
    }

    } while(0);

    // Init was attempted even if it didn't succeed
    if(l_backupTpm)
    {
        l_backupTpm->setAttr<TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>(true);
    }
}

void* tpmDaemon(void* unused)
{
    bool shutdownPending = false;
    errlHndl_t err = nullptr;

    // Mark as an independent daemon so if it crashes we terminate
    task_detach();

    TRACUCOMP( g_trac_trustedboot, ENTER_MRK "TpmDaemon Thread Start");

    // Register shutdown events with init service.
    //      Done at the "end" of shutdown processing.
    // This will flush any other messages (PCR extends) and terminate task
    INITSERVICE::registerShutdownEvent(systemData.msgQ,
                                       TRUSTEDBOOT::MSG_TYPE_SHUTDOWN);

    Message* tb_msg = nullptr;
    while (true)
    {
        msg_t* msg = msg_wait(systemData.msgQ);

        const MessageType type =
            static_cast<MessageType>(msg->type);
        tb_msg = nullptr;

        TRACUCOMP( g_trac_trustedboot, "TpmDaemon Handle CmdType %d",
                   type);

        switch (type)
        {
          case TRUSTEDBOOT::MSG_TYPE_SHUTDOWN:
              {
                  shutdownPending = true;

                  // Un-register message queue from the shutdown
                  INITSERVICE::unregisterShutdownEvent(systemData.msgQ);

              }
              break;
          case TRUSTEDBOOT::MSG_TYPE_PCREXTEND:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);

                  TRUSTEDBOOT::PcrExtendMsgData* msgData =
                      reinterpret_cast<TRUSTEDBOOT::PcrExtendMsgData*>
                      (tb_msg->iv_data);

                  assert(tb_msg->iv_len == sizeof(TRUSTEDBOOT::PcrExtendMsgData)
                         && msgData != nullptr, "Invalid PCRExtend Message");

                  TARGETING::TargetHandleList tpmList;
                  getTPMs(tpmList);
                  for (auto tpm : tpmList)
                  {
                      // Add the event to this TPM,
                      // if an error occurs the TPM will
                      //  be marked as failed and the error log committed
                      TRUSTEDBOOT::pcrExtendSingleTpm(
                                   tpm,
                                   msgData->mPcrIndex,
                                   msgData->mEventType,
                                   msgData->mAlgId,
                                   msgData->mDigest,
                                   msgData->mDigestSize,
                                   msgData->mLogMsg);
                  }

                  // Lastly make sure we are in a state
                  //  where we have a functional TPM
                  TRUSTEDBOOT::tpmVerifyFunctionalTpmExists(
                      NoTpmShutdownPolicy::BACKGROUND_SHUTDOWN);
              }
              break;
          case TRUSTEDBOOT::MSG_TYPE_SEPARATOR:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);

                  TARGETING::TargetHandleList tpmList;
                  getTPMs(tpmList);
                  for (auto tpm : tpmList)
                  {
                      // Add the separator to this TPM,
                      // if an error occurs the TPM will
                      //  be marked as failed and the error log committed
                      TRUSTEDBOOT::pcrExtendSeparator(
                                   tpm);
                  }

                  // Lastly make sure we are in a state
                  //  where we have a functional TPM
                  TRUSTEDBOOT::tpmVerifyFunctionalTpmExists(
                      NoTpmShutdownPolicy::BACKGROUND_SHUTDOWN);
              }
              break;
            case TRUSTEDBOOT::MSG_TYPE_INIT_BACKUP_TPM:
                {
                    doInitBackupTpm();
                }
                break;
          default:
            assert(false, "Invalid msg command");
            break;
        };

        // Reply back, if we have a tb_msg do that way
        if (nullptr != tb_msg)
        {
            tb_msg->response(systemData.msgQ);
        }
        else
        {
            // use the HB message type to respond
            int rc = msg_respond(systemData.msgQ, msg);
            if (rc)
            {
                TRACFCOMP( g_trac_trustedboot,
                           ERR_MRK "TpmDaemon: response msg_respond failure %d",
                           rc);
                /*@
                 * @errortype       ERRL_SEV_UNRECOVERABLE
                 * @moduleid        MOD_TPM_TPMDAEMON
                 * @reasoncode      RC_MSGRESPOND_FAIL
                 * @userdata1       rc from msq_respond()
                 * @devdesc         msg_respond() failed
                 * @custdesc        Firmware error during system boot
                 */
                err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                              MOD_TPM_TPMDAEMON,
                                              RC_MSGRESPOND_FAIL,
                                              rc,
                                              0,
                                              true);
                err->collectTrace(SECURE_COMP_NAME);
                err->collectTrace(TRBOOT_COMP_NAME);

                // Log this failure here since we can't reply to caller
                errlCommit(err, TRBOOT_COMP_ID);

            }
        }

        if (shutdownPending)
        {
            // Exit loop and terminate task
            break;
        }
    }

    TRACUCOMP( g_trac_trustedboot, EXIT_MRK "TpmDaemon Thread Terminate");
    return nullptr;
}

bool isTpmRequired()
{
    bool retVal = false;

    do
    {
        // First check if sensor is available
        if ( getTpmRequiredSensorValue(retVal) )
        {
            // Sensor is available so use its setting of retVal
            TRACUCOMP( g_trac_trustedboot, "isTpmRequired: Sensor is "
                       "available: using retVal=%d",
                       retVal );
            break;
        }
        else
        {
            // Sensor not available; reset retVal to be safe
            retVal = false;
        }


        // Since sensor isn't available, use ATTR_TPM_REQUIRED
        TARGETING::Target* pTopLevel = nullptr;
        (void)TARGETING::targetService().getTopLevelTarget(pTopLevel);
        assert(pTopLevel != nullptr, "Unable to get top level target");

        retVal = pTopLevel->getAttr<TARGETING::ATTR_TPM_REQUIRED>();

        TRACUCOMP( g_trac_trustedboot, "isTpmRequired: Using ATTR_TPM_REQUIRED:"
                   " retVal=%d",
                   retVal );

    } while(0);

    TRACFCOMP( g_trac_trustedboot,
               "Tpm Required: %s",(retVal ? "Yes" : "No") );

    return retVal;
}

bool getTpmRequiredSensorValue(bool& o_isTpmRequired)
{
    bool retVal = false;
    o_isTpmRequired = false;

    // Get TPM Required Sensor
#ifdef CONFIG_BMC_IPMI

    TARGETING::Target* pTopLevel = nullptr;
    (void)TARGETING::targetService().getTopLevelTarget(pTopLevel);
    assert(pTopLevel != nullptr, "Unable to get top level target");

    uint32_t sensorNum = TARGETING::UTIL::getSensorNumber(pTopLevel,
                                        TARGETING::SENSOR_NAME_TPM_REQUIRED);

    TRACUCOMP( g_trac_trustedboot,"getTpmRequiredSensorValue: sensorNum=0x%X, "
               "enum=0x%X",
               sensorNum, TARGETING::SENSOR_NAME_TPM_REQUIRED);

    // VALID IPMI sensors are 0-0xFE
    if (TARGETING::UTIL::INVALID_IPMI_SENSOR != sensorNum)
    {
        // Check if TPM is required by BMC
        SENSOR::getSensorReadingData tpmRequiredData;
        SENSOR::SensorBase tpmRequired(TARGETING::SENSOR_NAME_TPM_REQUIRED,
                                       pTopLevel);

        errlHndl_t err = tpmRequired.readSensorData(tpmRequiredData);
        if (nullptr == err)
        {
            // Sensor is available and found without error
            retVal = true;

            // 0x02 == Asserted bit (TPM is required)
            if ((tpmRequiredData.event_status &
                 (1 << SENSOR::ASSERTED)) ==
                (1 << SENSOR::ASSERTED))
            {
                o_isTpmRequired = true;
            }
        }
        else
        {
            // error reading sensor, so consider sensor not available
            TRACFCOMP( g_trac_trustedboot,ERR_MRK"getTpmRequiredSensorValue: "
                       "Unable to read Tpm Required Sensor: rc = 0x%04X "
                       "(sensorNum=0x%X, enum=0x%X) Deleting Error plid=0x%04X."
                       " Considering Sensor NOT required",
                       err->reasonCode(), sensorNum,
                       TARGETING::SENSOR_NAME_TPM_REQUIRED,
                       err->plid());
            delete err;
            err = nullptr;
            retVal = false;
        }
    }
    else
    {
        // Sensor not available
        retVal = false;
        TRACUCOMP( g_trac_trustedboot, "getTpmRequiredSensorValue: Sensor "
                   "not available: retVal=%d (sensorNum=0x%X)",
                   retVal, sensorNum );
    }
#else
    // IPMI support not there, so consider sensor not available
    retVal = false;
    TRACUCOMP( g_trac_trustedboot, "getTpmRequiredSensorValue: IPMI Support "
               "not found; retVal=%d",
               retVal );
#endif


    TRACFCOMP( g_trac_trustedboot,
               "getTpmRequiredSensorValue: isAvail=%s, o_isTpmRequired=%s",
               (retVal ? "Yes" : "No"),
               (o_isTpmRequired ? "Yes" : "No") );

    return retVal;
}


#ifdef CONFIG_DRTM
errlHndl_t tpmDrtmReset(TpmTarget* const i_pTpm)
{
    assert(i_pTpm != nullptr,"tpmDrtmReset: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmDrtmReset: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;

    // Send to the TPM
    size_t len = 0;
    err = deviceRead(i_pTpm,
                     nullptr,
                     len,
                     DEVICE_TPM_ADDRESS(TPMDD::TPM_OP_DRTMRESET,
                                        0,
                                        TPM_LOCALITY_4));

    if (nullptr == err)
    {
        /// @todo RTC: 145689 reset the dynamic tpm log
    }

    return err;
}
#endif

} // end TRUSTEDBOOT
OpenPOWER on IntegriCloud