summaryrefslogtreecommitdiffstats
path: root/src/usr/pnor/pnorrp.C
blob: a887e8a9850ea272782c2f2f4da547d7bf3f2932 (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
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/pnor/pnorrp.C $                                       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2011,2015                        */
/* [+] Google Inc.                                                        */
/* [+] 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                                                     */
#include "pnorrp.H"
#include <pnor/pnor_reasoncodes.H>
#include <initservice/taskargs.H>
#include <sys/msg.h>
#include <trace/interface.H>
#include <errl/errlmanager.H>
#include <targeting/common/targetservice.H>
#include <devicefw/userif.H>
#include <limits.h>
#include <string.h>
#include <sys/mm.h>
#include <errno.h>
#include <initservice/initserviceif.H>
#include "pnordd.H"
#include "ffs.h"   //Common header file with BuildingBlock.
#include "common/ffs_hb.H"//Hostboot definition of user data in ffs_entry struct
#include <pnor/ecc.H>
#include <kernel/console.H>
#include <endian.h>
#include <util/align.H>
#include <config.h>
#include "pnor_common.H"
#include <hwas/common/hwasCallout.H>
#include <console/consoleif.H>

extern trace_desc_t* g_trac_pnor;

// Easy macro replace for unit testing
//#define TRACUCOMP(args...)  TRACFCOMP(args)
#define TRACUCOMP(args...)

using namespace PNOR;

/**
 * Eyecatcher strings for PNOR TOC entries
 */
extern const char* cv_EYECATCHER[];

/**
 * @brief   set up _start() task entry procedure for PNOR daemon
 */
TASK_ENTRY_MACRO( PnorRP::init );


/********************
 Public Methods
 ********************/

/**
 * @brief  Returns information about a given side of PNOR
 */
errlHndl_t PNOR::getSideInfo( PNOR::SideId i_side,
                              PNOR::SideInfo_t& o_info)
{
    return Singleton<PnorRP>::instance().getSideInfo(i_side,o_info);
}

/**
 * @brief  Return the size and address of a given section of PNOR data
 */
errlHndl_t PNOR::getSectionInfo( PNOR::SectionId i_section,
                                 PNOR::SectionInfo_t& o_info )
{
    return Singleton<PnorRP>::instance().getSectionInfo(i_section,o_info);
}

/**
 * @brief  Clear pnor section
 */
errlHndl_t PNOR::clearSection(PNOR::SectionId i_section)
{
    return Singleton<PnorRP>::instance().clearSection(i_section);
}

/**
 * @brief  Write the data for a given sectino into PNOR
 */
errlHndl_t PNOR::flush( PNOR::SectionId i_section)
{
    errlHndl_t l_err = NULL;
    do {
        PNOR::SectionInfo_t l_info;
        l_err = getSectionInfo(i_section, l_info);
        if (l_err)
        {
            TRACFCOMP(g_trac_pnor, "PNOR::flush: getSectionInfo errored,"
                    " secId: %d", (int)i_section);
            break;
        }
        int l_rc = mm_remove_pages (RELEASE,
                reinterpret_cast<void*>(l_info.vaddr), l_info.size);
        if (l_rc)
        {
            TRACFCOMP(g_trac_pnor, "PNOR::flush: mm_remove_pages errored,"
                    " secId: %d, rc: %d", (int)i_section, l_rc);
            /*@
             *  @errortype
             *  @moduleid       PNOR::MOD_PNORRP_FLUSH
             *  @reasoncode     PNOR::RC_MM_REMOVE_PAGES_FAILED
             *  @userdata1      section Id
             *  @userdata2      RC
             *  @devdesc        mm_remove_pages failed
             */
            l_err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                        PNOR::MOD_PNORRP_FLUSH,
                                        PNOR::RC_MM_REMOVE_PAGES_FAILED,
                                        i_section, l_rc, true);
            break;
        }
    } while (0);
    return l_err;
}

/**
 * @brief  check and fix correctable ECC for a given pnor section
 */
errlHndl_t PNOR::fixECC(PNOR::SectionId i_section)
{
    return Singleton<PnorRP>::instance().fixECC(i_section);
}

/**
 * STATIC
 * @brief Static Initializer
 */
void PnorRP::init( errlHndl_t   &io_rtaskRetErrl )
{
    TRACUCOMP(g_trac_pnor, "PnorRP::init> " );
    uint64_t rc = 0;
    errlHndl_t  l_errl  =   NULL;

    if( Singleton<PnorRP>::instance().didStartupFail(rc) )
    {
        /*@
         *  @errortype      ERRL_SEV_CRITICAL_SYS_TERM
         *  @moduleid       PNOR::MOD_PNORRP_DIDSTARTUPFAIL
         *  @reasoncode     PNOR::RC_BAD_STARTUP_RC
         *  @userdata1      return code
         *  @userdata2      0
         *
         *  @devdesc        PNOR startup task returned an error.
         * @custdesc    A problem occurred while accessing the boot flash.
         */
        l_errl = new ERRORLOG::ErrlEntry(
                                ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
                                PNOR::MOD_PNORRP_DIDSTARTUPFAIL,
                                PNOR::RC_BAD_STARTUP_RC,
                                rc,
                                0,
                                true /*Add HB SW Callout*/ );

        l_errl->collectTrace(PNOR_COMP_NAME);
    }

    io_rtaskRetErrl=l_errl;
}


/********************
 Helper Methods
 ********************/

/**
 * @brief  Static function wrapper to pass into task_create
 */
void* wait_for_message( void* unused )
{
    TRACUCOMP(g_trac_pnor, "wait_for_message> " );
    Singleton<PnorRP>::instance().waitForMessage();
    return NULL;
}

/********************
 Private/Protected Methods
 ********************/

/**
 * @brief  Constructor
 */
PnorRP::PnorRP()
:
iv_TOC_used(TOC_0)
,iv_msgQ(NULL)
,iv_startupRC(0)
,iv_shutdown_pending(false)
{
    TRACFCOMP(g_trac_pnor, "PnorRP::PnorRP> " );
    // setup everything in a separate function
    initDaemon();

    TRACFCOMP(g_trac_pnor, "< PnorRP::PnorRP : Startup Errors=%X ", iv_startupRC );
}

/**
 * @brief  Destructor
 */
PnorRP::~PnorRP()
{
    TRACFCOMP(g_trac_pnor, "PnorRP::~PnorRP> " );

    // delete the message queue we created
    if( iv_msgQ )
    {
        msg_q_destroy( iv_msgQ );
    }

    // should kill the task we spawned, but that isn't needed right now

    TRACFCOMP(g_trac_pnor, "< PnorRP::~PnorRP" );
}

/**
 * @brief Initialize the daemon
 */
void PnorRP::initDaemon()
{
    TRACUCOMP(g_trac_pnor, "PnorRP::initDaemon> " );
    errlHndl_t l_errhdl = NULL;

    do
    {
        // create a message queue
        iv_msgQ = msg_q_create();

        INITSERVICE::registerShutdownEvent( iv_msgQ,
                PNOR::MSG_SHUTDOWN,
                INITSERVICE::PNOR_RP_PRIORITY);

        // create a Block, passing in the message queue
        int rc = mm_alloc_block( iv_msgQ, (void*) BASE_VADDR, TOTAL_SIZE );
        if( rc )
        {
            TRACFCOMP( g_trac_pnor, "PnorRP::initDaemon> Error from mm_alloc_block : rc=%d", rc );
            /*@
             * @errortype
             * @moduleid     PNOR::MOD_PNORRP_INITDAEMON
             * @reasoncode   PNOR::RC_EXTERNAL_ERROR
             * @userdata1    Requested Address
             * @userdata2    rc from mm_alloc_block
             * @devdesc      PnorRP::initDaemon> Error from mm_alloc_block
             * @custdesc     A problem occurred while accessing the boot flash.
             */
            l_errhdl = new ERRORLOG::ErrlEntry(
                           ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                           PNOR::MOD_PNORRP_INITDAEMON,
                           PNOR::RC_EXTERNAL_ERROR,
                           TO_UINT64(BASE_VADDR),
                           TO_UINT64(rc),
                           true /*Add HB SW Callout*/);
            l_errhdl->collectTrace(PNOR_COMP_NAME);
            break;
        }

        //Register this memory range to be FLUSHed during a shutdown.
        INITSERVICE::registerBlock(reinterpret_cast<void*>(BASE_VADDR),
                                   TOTAL_SIZE,PNOR_PRIORITY);

        //Find and read the TOC in the PNOR to compute the sections and set
        //their correct permissions
        l_errhdl = findTOC();
        if( l_errhdl )
        {
            TRACFCOMP(g_trac_pnor, ERR_MRK"PnorRP::initDaemon: Failed to findTOC");
            errlCommit(l_errhdl, PNOR_COMP_ID);
            INITSERVICE::doShutdown(PNOR::RC_FINDTOC_FAILED);
        }

        l_errhdl = readTOC();
        if( l_errhdl )
        {
            TRACFCOMP(g_trac_pnor, ERR_MRK"PnorRP::initDaemon: Failed to readTOC");
            break;
        }
        l_errhdl =  PnorRP::setSideInfo ();
        if(l_errhdl)
        {
            TRACFCOMP(g_trac_pnor, "PnorRP::initDaemon> setSideInfo failed");
            break;
        }

        // start task to wait on the queue
        task_create( wait_for_message, NULL );

    } while(0);

    if( l_errhdl )
    {
        iv_startupRC = l_errhdl->reasonCode();
        errlCommit(l_errhdl,PNOR_COMP_ID);
    }

// Not supporting PNOR error in VPO
#ifndef CONFIG_VPO_COMPILE
    // call ErrlManager function - tell him that PNOR is ready!
    ERRORLOG::ErrlManager::errlResourceReady(ERRORLOG::PNOR);
#endif

    TRACUCOMP(g_trac_pnor, "< PnorRP::initDaemon" );
}

errlHndl_t PnorRP::getSideInfo( PNOR::SideId i_side,
                              PNOR::SideInfo_t& o_info)
{
    errlHndl_t l_err = NULL;
    do
    {
        //check to make sure side id is valid
        if (i_side != PNOR::INVALID_SIDE)
        {
            memcpy (&o_info, &iv_side[i_side], sizeof(SideInfo_t));
        }
        else
        {
            TRACFCOMP(g_trac_pnor, "Side:%d is currently not supported",
                    (int)i_side);
            /*@
             * @errortype
             * @moduleid     PNOR::MOD_PNORRP_GETSIDEINFO
             * @reasoncode   PNOR::RC_INVALID_PNOR_SIDE
             * @userdata1    Requested SIDE
             * @userdata2    0
             * @devdesc      PnorRP::getSideInfo> Side not supported
             */
            l_err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                            PNOR::MOD_PNORRP_GETSIDEINFO,
                                            PNOR::RC_INVALID_PNOR_SIDE,
                                            TO_UINT64(i_side),
                                            0,true);
            break;
        }
    } while (0);
    return l_err;
}

/**
 * @brief  Return the size and address of a given section of PNOR data
 */
errlHndl_t PnorRP::getSectionInfo( PNOR::SectionId i_section,
                                   PNOR::SectionInfo_t& o_info )
{
    //TRACDCOMP(g_trac_pnor, "PnorRP::getSectionInfo> i_section=%d", i_section );
    errlHndl_t l_errhdl = NULL;
    PNOR::SectionId id = i_section;

    do
    {
        // Abort this operation if we had a startup failure
        uint64_t rc = 0;
        if( didStartupFail(rc) )
        {
            TRACFCOMP( g_trac_pnor, "PnorRP::getSectionInfo> RP not properly initialized, failing : rc=%X", rc );
            /*@
             * @errortype
             * @moduleid     PNOR::MOD_PNORRP_GETSECTIONINFO
             * @reasoncode   PNOR::RC_STARTUP_FAIL
             * @userdata1    Requested Section
             * @userdata2    Startup RC
             * @devdesc      PnorRP::getSectionInfo> RP not properly initialized
             * @custdesc     A problem occurred while accessing the boot flash.
             */
            l_errhdl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                               PNOR::MOD_PNORRP_GETSECTIONINFO,
                                               PNOR::RC_STARTUP_FAIL,
                                               TO_UINT64(i_section),
                                               rc,
                                               true /*Add HB SW Callout*/);
            l_errhdl->collectTrace(PNOR_COMP_NAME);

            // set the return section to our invalid data
            id = PNOR::INVALID_SECTION;
            break;
        }

        // Zero-length means the section is invalid
        if( 0 == iv_TOC[id].size )
        {
            TRACFCOMP( g_trac_pnor, "PnorRP::getSectionInfo> Invalid Section Requested : i_section=%d", i_section );
            TRACFCOMP(g_trac_pnor, "o_info={ id=%d, size=%d }", iv_TOC[i_section].id, iv_TOC[i_section].size );
            /*@
             * @errortype
             * @moduleid     PNOR::MOD_PNORRP_GETSECTIONINFO
             * @reasoncode   PNOR::RC_INVALID_SECTION
             * @userdata1    Requested Section
             * @userdata2    TOC used
             * @devdesc      PnorRP::getSectionInfo> Invalid Address for read/write
             * @custdesc     A problem occurred while accessing the boot flash.
            */
            l_errhdl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                               PNOR::MOD_PNORRP_GETSECTIONINFO,
                                               PNOR::RC_INVALID_SECTION,
                                               TO_UINT64(i_section),
                                               iv_TOC_used,
                                               true /*Add HB SW Callout*/);
            l_errhdl->collectTrace(PNOR_COMP_NAME);

            // set the return section to our invalid data
            id = PNOR::INVALID_SECTION;
            break;
        }
    } while(0);

    if (PNOR::INVALID_SECTION != id)
    {
        TRACDCOMP( g_trac_pnor, "PnorRP::getSectionInfo: i_section=%d, id=%d", i_section, iv_TOC[i_section].id );

        // copy my data into the external format
        o_info.id = iv_TOC[id].id;
        o_info.name = cv_EYECATCHER[id];
        o_info.vaddr = iv_TOC[id].virtAddr;
        o_info.flashAddr = iv_TOC[id].flashAddr;
        o_info.size = iv_TOC[id].size;
        o_info.eccProtected = ((iv_TOC[id].integrity & FFS_INTEG_ECC_PROTECT)
                                != 0) ? true : false;
        o_info.sha512Version = ((iv_TOC[id].version & FFS_VERS_SHA512)
                                 != 0) ? true : false;
        o_info.sha512perEC = ((iv_TOC[id].version & FFS_VERS_SHA512_PER_EC)
                               != 0) ? true : false;
        o_info.readOnly = ((iv_TOC[id].misc & FFS_MISC_READ_ONLY)
                               != 0) ? true : false;
    }

    return l_errhdl;
}

/*
 * @brief Finds the toc locations based on hostboot base address
 */
errlHndl_t PnorRP::findTOC()
{
    TRACFCOMP(g_trac_pnor, ENTER_MRK"PnorRP::findTOC...");
    errlHndl_t l_err             = NULL;
    do {
        const uint32_t l_shiftAmount = 32;
        uint64_t l_chip         = 0;
        uint64_t l_fatalError   = 0;
        bool l_foundTOC         = false;
        uint64_t l_toc          = PNOR::PNOR_SIZE - 1;
        ffs_hdr* l_ffs_hdr      = 0;
        uint64_t l_hbbAddr      = 0;
        uint8_t l_tocBuffer [PAGESIZE];

        //get the HBB Address we booted from
        l_err =  PNOR::mmioToPhysicalOffset(l_hbbAddr);
        if (l_err)
        {
            TRACFCOMP(g_trac_pnor, "PnorRP::findTOC> mmioToPhysicalOffset failed");
            break;
        }

        //if we booted from a lower address, then we need to increment
        //sides as we find tocs, otherwise decrement.
        bool l_inc = (ALIGN_DOWN_X(l_hbbAddr, l_shiftAmount*MEGABYTE) == 0);
        uint64_t l_tempHBB = l_hbbAddr;

        //while TOC not found and we are within the flash size
        while((!l_foundTOC) && (l_tempHBB > 0) && (l_tempHBB < PNOR_SIZE))
        {
            //Align HBB down -- looking at 0x0 or 0x2000000
            l_toc = ALIGN_DOWN_X(l_tempHBB, l_shiftAmount*MEGABYTE);
            l_err = readFromDevice(l_toc, l_chip, false, l_tocBuffer,
                    l_fatalError);
            if(l_err)
            {
                TRACFCOMP(g_trac_pnor,"findTOC: readFromDevice failed "
                        "searching for primaryTOC");
                break;
            }

            l_ffs_hdr  = (ffs_hdr*)l_tocBuffer;
            l_foundTOC = ((l_ffs_hdr->magic == FFS_MAGIC) &&
                        (PNOR::pnor_ffs_checksum(l_ffs_hdr,FFS_HDR_SIZE) == 0));
            if (!l_foundTOC)
            {
                //If TOC not found at 0x0 or 0x2000000
                //Align HBB down + 8000 -- looking at 0x8000 or 0x2008000
                l_toc += TOC_SIZE;
                l_err = readFromDevice(l_toc, l_chip, false, l_tocBuffer,
                    l_fatalError);
                if(l_err)
                {
                    TRACFCOMP(g_trac_pnor,"findTOC: readFromDevice failed "
                            "searching for backupTOC for A-B-D arrangement");
                    break;
                }

                l_ffs_hdr  = (ffs_hdr*)l_tocBuffer;
                l_foundTOC =
                    ((l_ffs_hdr->magic == FFS_MAGIC) &&
                     (PNOR::pnor_ffs_checksum(l_ffs_hdr, FFS_HDR_SIZE) == 0));
            }

            if (!l_foundTOC)
            {
                //If toc not found at 0x8000 or 0x2008000
                //Align HBB up (l_shiftAmount) - 8000
                // -- looking at 0x1FF8000 or 0x3FF8000
                l_toc = ALIGN_X(l_tempHBB, l_shiftAmount*MEGABYTE);
                l_toc -= TOC_SIZE;
                l_err = readFromDevice(l_toc, l_chip, false, l_tocBuffer,
                    l_fatalError);
                if(l_err)
                {
                    TRACFCOMP(g_trac_pnor,"findTOC: readFromDevice failed"
                            "searching for backupTOC for A-D-B arrangement");
                    break;
                }

                l_ffs_hdr  = (ffs_hdr*)l_tocBuffer;
                l_foundTOC =
                    ((l_ffs_hdr->magic == FFS_MAGIC) &&
                     (PNOR::pnor_ffs_checksum(l_ffs_hdr, FFS_HDR_SIZE) == 0));
            }

            //Setup for next time -- look for the other side
            l_tempHBB = (l_inc) ? (l_tempHBB + l_shiftAmount*MEGABYTE) :
                                  (l_tempHBB - l_shiftAmount*MEGABYTE);
        }

        if(l_err)
        {
            break;
        }

        //found at least one TOC
        if(l_foundTOC)
        {
            TRACFCOMP(g_trac_pnor, "findTOC> found at least one toc at 0x%X", l_toc);

            //look for BACKUP_PART and read it
            uint64_t l_backupTOC = INVALID_OFFSET;
            PNOR::findPhysicalOffset(l_ffs_hdr,"BACKUP_PART",l_backupTOC);

            //figure out if the toc found belongs to the side we booted from
            //or if it belongs to the other side
            uint64_t l_foundHBB;
            PNOR::findPhysicalOffset(l_ffs_hdr, "HBB", l_foundHBB);
            bool l_isActiveTOC = (l_foundHBB == l_hbbAddr);

#ifdef CONFIG_PNOR_TWO_SIDE_SUPPORT
            uint64_t l_otherPrimaryTOC = INVALID_OFFSET;
            uint64_t l_otherBackupTOC  = INVALID_OFFSET;
            uint8_t l_otherPrimaryTOCBuff [PAGESIZE];
            uint8_t l_otherBackupTOCBuff  [PAGESIZE];
            uint8_t l_backupTOCBuffer     [PAGESIZE];

            //look for OTHER_SIDE
            PNOR::findPhysicalOffset(l_ffs_hdr, "OTHER_SIDE",l_otherPrimaryTOC);

            //reading to look for OTHER_SIDE's backup
            bool l_foundOtherBackup  = false;
            bool l_foundOtherPrimary = false;

            if (l_otherPrimaryTOC != INVALID_OFFSET)
            {
                l_err = readFromDevice(l_otherPrimaryTOC,l_chip,
                            false, l_otherPrimaryTOCBuff,l_fatalError);
                l_ffs_hdr = (ffs_hdr*)l_otherPrimaryTOCBuff;
                if(l_err)
                {
                    TRACFCOMP(g_trac_pnor, "findTOC: readFromDevice failed"
                            " while looking for other side's primary TOC");
                    errlCommit(l_err, PNOR_COMP_ID);
                }
                else if ((l_ffs_hdr->magic == FFS_MAGIC) &&
                        (PNOR::pnor_ffs_checksum(l_ffs_hdr, FFS_HDR_SIZE)==0))
                {
                        //if otherPrimaryTOC is valid,
                        //then we can find it's backup
                        PNOR::findPhysicalOffset(l_ffs_hdr, "BACKUP_PART",
                              l_otherBackupTOC);
                        l_foundOtherPrimary = true;
                }
            }
            if ((!l_foundOtherPrimary) && (l_backupTOC != INVALID_OFFSET))
            {
                //if otherPrimaryTOC is not valid, find the other backup
                //through BACKUP_PART's OTHER_SIDE
                l_err = readFromDevice (l_backupTOC, l_chip, false,
                        l_backupTOCBuffer, l_fatalError);
                l_ffs_hdr = (ffs_hdr*)l_backupTOCBuffer;
                if (l_err)
                {
                    TRACFCOMP(g_trac_pnor, "findTOC: readFromDevice failed"
                            " while reading for backup TOC");
                    errlCommit(l_err, PNOR_COMP_ID);
                }
                else if ((l_ffs_hdr->magic == FFS_MAGIC)
                      && (PNOR::pnor_ffs_checksum(l_ffs_hdr,FFS_HDR_SIZE)==0))
                {
                    PNOR::findPhysicalOffset(l_ffs_hdr,"OTHER_SIDE",
                                    l_otherBackupTOC);
                    l_foundOtherBackup = true;
                }
            }

            //figure out if other side's toc belongs to the side we booted from
            if(l_foundOtherPrimary)
            {
                PNOR::findPhysicalOffset((ffs_hdr*)l_otherPrimaryTOCBuff, "HBB",
                    l_foundHBB);
            }
            else if (l_foundOtherBackup)
            {
                l_err = readFromDevice (l_otherBackupTOC, l_chip, false,
                        l_otherBackupTOCBuff, l_fatalError);
                l_ffs_hdr = (ffs_hdr*)l_backupTOCBuffer;
                if (l_err)
                {
                    TRACFCOMP(g_trac_pnor, "findTOC: readFromDevice failed"
                            " while reading other side's backup TOC");
                    errlCommit(l_err, PNOR_COMP_ID);
                }
                else if ((l_ffs_hdr->magic == FFS_MAGIC) &&
                        (PNOR::pnor_ffs_checksum(l_ffs_hdr,FFS_HDR_SIZE)==0))
                {
                    PNOR::findPhysicalOffset(l_ffs_hdr,"HBB",
                                    l_foundHBB);
                }
            }
            bool l_isOtherActiveTOC = (l_foundHBB == l_hbbAddr);

            if (l_isActiveTOC)
            {
                iv_TocOffset[WORKING].first    = l_toc;
                iv_TocOffset[WORKING].second   = l_backupTOC;
                iv_TocOffset[ALTERNATE].first  = l_otherPrimaryTOC;
                iv_TocOffset[ALTERNATE].second = l_otherBackupTOC;
            }
            else if (l_isOtherActiveTOC)
            {
                iv_TocOffset[WORKING].first    = l_otherPrimaryTOC;
                iv_TocOffset[WORKING].second   = l_otherBackupTOC;
                iv_TocOffset[ALTERNATE].first  = l_toc;
                iv_TocOffset[ALTERNATE].second = l_backupTOC;
            }
            else
            {
                TRACFCOMP(g_trac_pnor,"findTOC>No valid TOC found, looked"
                       "at following addresses PrimaryTOC:0x%08X, BackupTOC:"
                       "0x%08X", l_toc, l_backupTOC);
                INITSERVICE::doShutdown(PNOR::RC_PARTITION_TABLE_CORRUPTED);
            }
            TRACFCOMP(g_trac_pnor,"findTOC>activePrimary:0x%X,activeBackup:0x%X"
                  "altPrimary:0x%X, altBackup:0x%X",iv_TocOffset[WORKING].first,
                  iv_TocOffset[WORKING].second, iv_TocOffset[ALTERNATE].first,
                  iv_TocOffset[ALTERNATE].second);
#else
            if (l_isActiveTOC)
            {
                iv_TocOffset[WORKING].first  = l_toc;
                iv_TocOffset[WORKING].second = l_backupTOC;
                TRACFCOMP(g_trac_pnor, "findTOC> activePrimary:0x%X, "
                        "activeBackup:0x%X", iv_TocOffset[WORKING].first,
                        iv_TocOffset[WORKING].second);
            }
            else
            {
                TRACFCOMP(g_trac_pnor,"findTOC>No valid TOC found, looked"
                       "at following addresses PrimaryTOC:0x%08X, BackupTOC:"
                       "0x%08X", l_toc, l_backupTOC);
                INITSERVICE::doShutdown(PNOR::RC_PARTITION_TABLE_CORRUPTED);
            }

#endif
        }
        else
        {
            //no valid TOC found
            TRACFCOMP(g_trac_pnor, "No valid TOC found");
            if (l_err)
            {
                errlCommit(l_err, PNOR_COMP_ID);
            }
            INITSERVICE::doShutdown(PNOR::RC_PARTITION_TABLE_NOT_FOUND);
        }
    } while (0);

    TRACFCOMP(g_trac_pnor, EXIT_MRK"findTOC");
    return l_err;
}

/**
 * @brief Read the TOC and store section information
 */
errlHndl_t PnorRP::readTOC()
{
    TRACUCOMP(g_trac_pnor, "PnorRP::readTOC>" );
    errlHndl_t l_errhdl = NULL;
    uint8_t* toc0Buffer = new uint8_t[PAGESIZE];
    uint8_t* toc1Buffer = new uint8_t[PAGESIZE];
    uint64_t fatal_error = 0;
    do {
        //Initialize toc bufferes to invalid value
        //If these buffers are not read from device,
        //then parseTOC will see invalid data
        memset(toc0Buffer, 0xFF, PAGESIZE);
        memset(toc1Buffer, 0xFF, PAGESIZE);

        if (iv_TocOffset[WORKING].first != INVALID_OFFSET)
        {
            l_errhdl = readFromDevice(iv_TocOffset[WORKING].first, 0, false,
                                    toc0Buffer, fatal_error );
            if (l_errhdl)
            {
                TRACFCOMP(g_trac_pnor,"readTOC:readFromDevice failed for TOC0");
                break;
            }
        }

        if (iv_TocOffset[WORKING].second != INVALID_OFFSET)
        {
            l_errhdl = readFromDevice(iv_TocOffset[WORKING].second, 0, false,
                                       toc1Buffer, fatal_error );
            if (l_errhdl)
            {
                TRACFCOMP(g_trac_pnor,"readTOC:readFromDevice failed for TOC1");
                break;
            }
        }

        l_errhdl = PNOR::parseTOC(toc0Buffer, toc1Buffer, iv_TOC_used, iv_TOC,
                                  BASE_VADDR);
        if (l_errhdl)
        {
            TRACFCOMP(g_trac_pnor, "readTOC: parseTOC failed");
            errlCommit(l_errhdl, PNOR_COMP_ID);
            INITSERVICE::doShutdown(PNOR::RC_PARTITION_TABLE_INVALID);
        }
    } while (0);

    if(toc0Buffer != NULL)
    {
        delete[] toc0Buffer;
    }

    if(toc1Buffer != NULL)
    {
        delete[] toc1Buffer;
    }
    TRACUCOMP(g_trac_pnor, "< PnorRP::readTOC" );
    return l_errhdl;
}

errlHndl_t PnorRP::setSideInfo ()
{
    uint64_t l_chip       = 0;
    uint64_t l_fatalError = 0;
    uint8_t* l_tocBuffer  = new uint8_t [PAGESIZE];
    ffs_hdr* l_ffs_hdr    = 0;
    errlHndl_t l_err      = NULL;
    for (SideId i = FIRST_SIDE; i < NUM_SIDES; i = (SideId)(i+1))
    {
        //id
        iv_side[i].id = (SideId)i;

        //get a valid TOC
        uint64_t l_primaryTOC = iv_TocOffset[i].first;
        uint64_t l_backupTOC  = iv_TocOffset[i].second;

        uint64_t l_validTOC = (l_primaryTOC != INVALID_OFFSET) ? l_primaryTOC :
                              ((l_backupTOC != INVALID_OFFSET) ? l_backupTOC  :
                                INVALID_OFFSET);
        if(l_validTOC == INVALID_OFFSET)
        {
            if (i == WORKING)
            {
                TRACFCOMP(g_trac_pnor, "setSideInfo: No valid TOC found for"
                        "working side");
                INITSERVICE::doShutdown(PNOR::RC_INVALID_WORKING_TOC);
            }
            else
            {
                TRACFCOMP(g_trac_pnor,"setSideInfo: No valid TOC found for"
                        " side: %d", i);
                /*@
                 * @errortype
                 * @moduleid         PNOR::MOD_PNORRP_SETSIDEINFO
                 * @reasoncode       PNOR::RC_INVALID_TOC
                 * @userdata1        Side Id
                 * @userdata2[00:31] primary toc
                 * @userdata2[32:63] backup toc
                 * @devdesc          PnorRP::setSideInfo> No valid TOCs found
                 */
                l_err = new ERRORLOG::ErrlEntry(
                            ERRORLOG::ERRL_SEV_INFORMATIONAL,
                            PNOR::MOD_PNORRP_SETSIDEINFO,
                            PNOR::RC_INVALID_TOC,
                            i,TWO_UINT32_TO_UINT64(l_primaryTOC,l_backupTOC),
                            true);
                l_err->addPartCallout(
                        TARGETING::MASTER_PROCESSOR_CHIP_TARGET_SENTINEL,
                        HWAS::PNOR_PART_TYPE,
                        HWAS::SRCI_PRIORITY_LOW,
                        HWAS::NO_DECONFIG,
                        HWAS::GARD_NULL);
                break;
            }
        }

        iv_side[i].primaryTOC = l_primaryTOC;
        iv_side[i].backupTOC  = l_backupTOC;

        l_err = readFromDevice(l_validTOC,l_chip,
                    false, l_tocBuffer,l_fatalError);
        if(l_err)
        {
            TRACFCOMP(g_trac_pnor, "setSideInfo: readFromDevice failed"
                    " while reading a valid TOC");
            break;
        }
        l_ffs_hdr = (ffs_hdr*)l_tocBuffer;

        //isGolden
        //Entry 0 is the "part" partition
        //Need to read from the ffs hdr instead of the TOC because
        //TOC has no knowledge of other side
        ffs_entry* cur_entry = (&l_ffs_hdr->entries[0]);
        ffs_hb_user_t* ffsUserData = (ffs_hb_user_t*)&(cur_entry->user);
        iv_side[i].isGolden = (ffsUserData->miscFlags & FFS_MISC_GOLDEN);

        //isGuardPresent
        uint64_t l_secOffset = INVALID_OFFSET;
        findPhysicalOffset (l_ffs_hdr, "GUARD", l_secOffset);
        iv_side[i].isGuardPresent = (l_secOffset != INVALID_OFFSET);

        //isOtherSide
        iv_side[i].hasOtherSide = false;
#ifdef CONFIG_PNOR_TWO_SIDE_SUPPORT
        iv_side[i].hasOtherSide =
            ((iv_TocOffset[(i+1)%NUM_SIDES].first != INVALID_OFFSET) ||
            (iv_TocOffset[(i+1)%NUM_SIDES].second != INVALID_OFFSET));
#endif

        //hbbAddress
        l_secOffset = INVALID_OFFSET;
        findPhysicalOffset (l_ffs_hdr, "HBB", l_secOffset);
        iv_side[i].hbbAddress = l_secOffset;

        //mmioOffset
        uint64_t l_mmioOffset;
        physicalToMmioOffset(l_secOffset, l_mmioOffset);
        iv_side[i].hbbMmioOffset = l_mmioOffset;

        //char side
        iv_side[i].side =(ALIGN_DOWN_X(l_secOffset,32*MEGABYTE) == 0) ? 'A':'B';

        TRACFCOMP(g_trac_pnor, "setSideInfo: sideId:%d, isGolden:%d, "
              "isGuardPresent:%d, hasOtherSide:%d, primaryTOC: 0x%x, backupTOC"
              ":0x%X, HBB:0x%X, MMIO:0x%X",i, iv_side[i].isGolden,
              iv_side[i].isGuardPresent,iv_side[i].hasOtherSide,
              iv_side[i].primaryTOC, iv_side[i].backupTOC,
              iv_side[i].hbbAddress, iv_side[i].hbbMmioOffset);
    }
    return l_err;
}
/**
 * @brief  Message receiver
 */
void PnorRP::waitForMessage()
{
    TRACFCOMP(g_trac_pnor, "PnorRP::waitForMessage>" );

    errlHndl_t l_errhdl = NULL;
    msg_t* message = NULL;
    uint8_t* user_addr = NULL;
    uint8_t* eff_addr = NULL;
    uint64_t dev_offset = 0;
    uint64_t chip_select = 0xF;
    bool needs_ecc = false;
    int rc = 0;
    uint64_t status_rc = 0;
    uint64_t fatal_error = 0;

    while(1)
    {
        status_rc = 0;
        TRACUCOMP(g_trac_pnor, "PnorRP::waitForMessage> waiting for message" );
        message = msg_wait( iv_msgQ );
        if( message )
        {
            // if its a shutdown message skip the address calculation
            if( message->type !=  PNOR::MSG_SHUTDOWN )
            {
                /*  data[0] = virtual address requested
                 *  data[1] = address to place contents
                 */
                eff_addr = (uint8_t*)message->data[0];
                user_addr = (uint8_t*)message->data[1];

                //figure out the real pnor offset
                l_errhdl =
                    computeDeviceAddr( eff_addr,
                            dev_offset, chip_select, needs_ecc );
            }

            if( l_errhdl )
            {
                status_rc = -EFAULT; /* Bad address */
            }
            else
            {
                switch(message->type)
                {
                    case( PNOR::MSG_SHUTDOWN ):
                        {
                            // we got a message saying there is a shutdown in
                            // progress, dont accept any new pnor writes
                            iv_shutdown_pending = true;
                            TRACFCOMP(g_trac_pnor,"PnorRP::Shutdown message recieved" );
                        }
                        break;

                    case( MSG_MM_RP_READ ):
                        l_errhdl = readFromDevice( dev_offset,
                                                   chip_select,
                                                   needs_ecc,
                                                   user_addr,
                                                   fatal_error );
                        if( l_errhdl || ( 0 != fatal_error ) )
                        {
                            status_rc = -EIO; /* I/O error */
                        }
                        break;

                    case( MSG_MM_RP_WRITE ):
                        if( !iv_shutdown_pending )
                        {
                            l_errhdl = writeToDevice( dev_offset,
                                                      chip_select,
                                                      needs_ecc,
                                                      user_addr );
                            if( l_errhdl )
                            {
                                status_rc = -EIO; /* I/O error */
                            }
                        }
                        else
                        {
                          TRACFCOMP(g_trac_pnor, "PnorRP::shutdown pending write dropped");
                        }
                        break;

                    default:
                        TRACFCOMP( g_trac_pnor, "PnorRP::waitForMessage> Unrecognized message type : user_addr=%p, eff_addr=%p, msgtype=%d", user_addr, eff_addr, message->type );
                        /*@
                         * @errortype
                         * @moduleid     PNOR::MOD_PNORRP_WAITFORMESSAGE
                         * @reasoncode   PNOR::RC_INVALID_MESSAGE_TYPE
                         * @userdata1    Message type
                         * @userdata2    Requested Virtual Address
                         * @devdesc      PnorRP::waitForMessage> Unrecognized
                         *               message type
                         * @custdesc     A problem occurred while accessing
                         *               the boot flash.
                         */
                        l_errhdl = new ERRORLOG::ErrlEntry(
                                           ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                           PNOR::MOD_PNORRP_WAITFORMESSAGE,
                                           PNOR::RC_INVALID_MESSAGE_TYPE,
                                           TO_UINT64(message->type),
                                           (uint64_t)eff_addr,
                                           true /*Add HB SW Callout*/);
                        l_errhdl->collectTrace(PNOR_COMP_NAME);
                        status_rc = -EINVAL; /* Invalid argument */
                }
            }

            if( !l_errhdl && msg_is_async(message) )
            {
                TRACFCOMP( g_trac_pnor, "PnorRP::waitForMessage> Unsupported Asynchronous Message  : user_addr=%p, eff_addr=%p, msgtype=%d", user_addr, eff_addr, message->type );
                /*@
                 * @errortype
                 * @moduleid     PNOR::MOD_PNORRP_WAITFORMESSAGE
                 * @reasoncode   PNOR::RC_INVALID_ASYNC_MESSAGE
                 * @userdata1    Message type
                 * @userdata2    Requested Virtual Address
                 * @devdesc      PnorRP::waitForMessage> Unrecognized message
                 *               type
                 * @custdesc     A problem occurred while accessing the boot
                 *               flash.
                 */
                l_errhdl = new ERRORLOG::ErrlEntry(
                                         ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                         PNOR::MOD_PNORRP_WAITFORMESSAGE,
                                         PNOR::RC_INVALID_ASYNC_MESSAGE,
                                         TO_UINT64(message->type),
                                         (uint64_t)eff_addr,
                                         true /*Add HB SW Callout*/);
                l_errhdl->collectTrace(PNOR_COMP_NAME);
                status_rc = -EINVAL; /* Invalid argument */
            }

            if( l_errhdl )
            {
                errlCommit(l_errhdl,PNOR_COMP_ID);
            }


            /*  Expected Response:
             *      data[0] = virtual address requested
             *      data[1] = rc (0 or negative errno value)
             *      extra_data = Specific reason code.
             */
            message->data[1] = status_rc;
            message->extra_data = reinterpret_cast<void*>(fatal_error);
            rc = msg_respond( iv_msgQ, message );
            if( rc )
            {
                TRACFCOMP(g_trac_pnor, "PnorRP::waitForMessage> Error from msg_respond, giving up : rc=%d", rc );
                break;
            }
        }
    }


    TRACFCOMP(g_trac_pnor, "< PnorRP::waitForMessage" );
}


/**
 * @brief  Retrieve 1 page of data from the PNOR device
 */
errlHndl_t PnorRP::readFromDevice( uint64_t i_offset,
                                   uint64_t i_chip,
                                   bool i_ecc,
                                   void* o_dest,
                                   uint64_t& o_fatalError )
{
    TRACUCOMP(g_trac_pnor, "PnorRP::readFromDevice> i_offset=0x%X, i_chip=%d", i_offset, i_chip );
    errlHndl_t l_errhdl = NULL;
    uint8_t* ecc_buffer = NULL;
    o_fatalError = 0;

    do
    {
        TARGETING::Target* pnor_target = TARGETING::MASTER_PROCESSOR_CHIP_TARGET_SENTINEL;

        // assume a single page
        void* data_to_read = o_dest;
        size_t read_size = PAGESIZE;

        // if we need to handle ECC we need to read more than 1 page
        if( i_ecc )
        {
            ecc_buffer = new uint8_t[PAGESIZE_PLUS_ECC]();
            data_to_read = ecc_buffer;
            read_size = PAGESIZE_PLUS_ECC;
        }

        // get the data from the PNOR DD
        l_errhdl = DeviceFW::deviceRead(pnor_target,
                                        data_to_read,
                                        read_size,
                                        DEVICE_PNOR_ADDRESS(i_chip,i_offset) );
        if( l_errhdl )
        {
            TRACFCOMP(g_trac_pnor, "PnorRP::readFromDevice> Error from device : RC=%X", l_errhdl->reasonCode() );
            break;
        }

        // remove the ECC data
        if( i_ecc )
        {
            // remove the ECC and fix the original data if it is broken
            PNOR::ECC::eccStatus ecc_stat =
              PNOR::ECC::removeECC( reinterpret_cast<uint8_t*>(data_to_read),
                                    reinterpret_cast<uint8_t*>(o_dest),
                                    PAGESIZE );

            // create an error if we couldn't correct things
            if( ecc_stat == PNOR::ECC::UNCORRECTABLE )
            {
                TRACFCOMP( g_trac_pnor, "PnorRP::readFromDevice> Uncorrectable ECC error : chip=%d,offset=0x%.X", i_chip, i_offset );
                CONSOLE::displayf( NULL, "ECC error in PNOR flash in section offset 0x%.8X\n", i_offset );

                // Need to shutdown here instead of creating an error log
                //  because the bad page could be critical to the regular
                //  error handling path and cause an infinite loop.
                // Also need to spawn a separate task to do the shutdown
                //  so that the regular PNOR task can service the writes
                //  that happen during shutdown.
                o_fatalError = PNOR::RC_ECC_UE;
                INITSERVICE::doShutdown( PNOR::RC_ECC_UE, true );
            }
            // found an error so we need to fix something
            else if( ecc_stat != PNOR::ECC::CLEAN )
            {
                TRACFCOMP( g_trac_pnor, "PnorRP::readFromDevice> Correctable ECC error : chip=%d, offset=0x%.X", i_chip, i_offset );

                // need to write good data back to PNOR
                l_errhdl = DeviceFW::deviceWrite(pnor_target,
                                       data_to_read,//corrected data
                                       read_size,
                                       DEVICE_PNOR_ADDRESS(i_chip,i_offset) );
                if( l_errhdl )
                {
                    TRACFCOMP(g_trac_pnor, "PnorRP::readFromDevice> Error writing corrected data back to device : RC=%X", l_errhdl->reasonCode() );
                    // we don't need to fail here since we can correct
                    //  it the next time we read it again, instead just
                    //  commit the log here
                    errlCommit(l_errhdl,PNOR_COMP_ID);
                }

                // keep some stats here in case we want them someday
                //no need for mutex since only ever 1 thread accessing this
                iv_stats[i_offset/PAGESIZE].numCEs++;
            }
        }
    } while(0);

    if( ecc_buffer )
    {
        delete[] ecc_buffer;
    }

    TRACUCOMP(g_trac_pnor, "< PnorRP::readFromDevice" );
    return l_errhdl;
}

/**
 * @brief  Write 1 page of data to the PNOR device
 */
errlHndl_t PnorRP::writeToDevice( uint64_t i_offset,
                                  uint64_t i_chip,
                                  bool i_ecc,
                                  void* i_src )
{
    TRACUCOMP(g_trac_pnor, "PnorRP::writeToDevice> i_offset=%X, i_chip=%d", i_offset, i_chip );
    errlHndl_t l_errhdl = NULL;
    uint8_t* ecc_buffer = NULL;

    do
    {
        TARGETING::Target* pnor_target = TARGETING::MASTER_PROCESSOR_CHIP_TARGET_SENTINEL;

        // assume a single page to write
        void* data_to_write = i_src;
        size_t write_size = PAGESIZE;

        // apply ECC to data if needed
        if( i_ecc )
        {
            ecc_buffer = new uint8_t[PAGESIZE_PLUS_ECC];
            PNOR::ECC::injectECC( reinterpret_cast<uint8_t*>(i_src),
                                  PAGESIZE,
                                  reinterpret_cast<uint8_t*>(ecc_buffer) );
            data_to_write = reinterpret_cast<void*>(ecc_buffer);
            write_size = PAGESIZE_PLUS_ECC;
        }

        //no need for mutex since only ever a singleton object
        iv_stats[i_offset/PAGESIZE].numWrites++;

        // write the data out to the PNOR DD
        errlHndl_t l_errhdl = DeviceFW::deviceWrite( pnor_target,
                                       data_to_write,
                                       write_size,
                                       DEVICE_PNOR_ADDRESS(i_chip,i_offset) );
        if( l_errhdl )
        {
            TRACFCOMP(g_trac_pnor, "PnorRP::writeToDevice> Error from device : RC=%X", l_errhdl->reasonCode() );
            break;
        }
    } while(0);

    if( ecc_buffer )
    {
        delete[] ecc_buffer;
    }

    TRACUCOMP(g_trac_pnor, "< PnorRP::writeToDevice" );
    return l_errhdl;
}

/**
 * @brief  Convert a virtual address into the PNOR device address
 */
errlHndl_t PnorRP::computeDeviceAddr( void* i_vaddr,
                                      uint64_t& o_offset,
                                      uint64_t& o_chip,
                                      bool& o_ecc )
{
    errlHndl_t l_errhdl = NULL;
    o_offset = 0;
    o_chip = 99;
    uint64_t l_vaddr = (uint64_t)i_vaddr;

    do
    {
        // make sure this is one of our addresses
        if( !((l_vaddr >= BASE_VADDR)
              && (l_vaddr < LAST_VADDR)) )
        {
            TRACFCOMP( g_trac_pnor, "PnorRP::computeDeviceAddr> Virtual Address outside known PNOR range : i_vaddr=%p", i_vaddr );
            /*@
             * @errortype
             * @moduleid     PNOR::MOD_PNORRP_WAITFORMESSAGE
             * @reasoncode   PNOR::RC_INVALID_ADDRESS
             * @userdata1    Virtual Address
             * @userdata2    Base PNOR Address
             * @devdesc      PnorRP::computeDeviceAddr> Virtual Address outside
             *               known PNOR range
             * @custdesc    A problem occurred while accessing the boot flash.
             */
            l_errhdl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                            PNOR::MOD_PNORRP_COMPUTEDEVICEADDR,
                                            PNOR::RC_INVALID_ADDRESS,
                                            l_vaddr,
                                            BASE_VADDR,
                                            true /*Add HB SW Callout*/);
            l_errhdl->collectTrace(PNOR_COMP_NAME);
            break;
        }

        // find the matching section
        PNOR::SectionId id = PNOR::INVALID_SECTION;
        l_errhdl = computeSection( l_vaddr, id );
        if( l_errhdl )
        {
            TRACFCOMP( g_trac_pnor, "PnorRP::computeDeviceAddr> Virtual address does not match any pnor sections : i_vaddr=%p", i_vaddr );
            break;
        }

        // pull out the information we need to return from our global copy
        o_chip = iv_TOC[id].chip;
        o_ecc = (bool)(iv_TOC[id].integrity & FFS_INTEG_ECC_PROTECT);
        o_offset = l_vaddr - iv_TOC[id].virtAddr; //offset into section

        // for ECC we need to figure out where the ECC-enhanced offset is
        //  before tacking on the offset to the section
        if( o_ecc )
        {
            o_offset = (o_offset * 9) / 8;
        }
        // add on the offset of the section itself
        o_offset += iv_TOC[id].flashAddr;
    } while(0);

    TRACUCOMP( g_trac_pnor, "< PnorRP::computeDeviceAddr: i_vaddr=%X, o_offset=0x%X, o_chip=%d", l_vaddr, o_offset, o_chip );
    return l_errhdl;
}

/**
 * @brief Static instance function
 */
PnorRP& PnorRP::getInstance()
{
    return Singleton<PnorRP>::instance();
}

/**
 * @brief  Figure out which section a VA belongs to
 */
errlHndl_t PnorRP::computeSection( uint64_t i_vaddr,
                                   PNOR::SectionId& o_id )
{
    errlHndl_t errhdl = NULL;

    o_id = PNOR::INVALID_SECTION;

    do {
        // loop through all sections to find a matching id
        for( PNOR::SectionId id = PNOR::FIRST_SECTION;
             id < PNOR::NUM_SECTIONS;
             id = (PNOR::SectionId) (id + 1) )
        {
            if( (i_vaddr >= iv_TOC[id].virtAddr)
                && (i_vaddr < (iv_TOC[id].virtAddr + iv_TOC[id].size)) )
            {
                o_id = iv_TOC[id].id;
                break;
            }
        }

    }while(0);

    if(o_id == PNOR::INVALID_SECTION)
    {
        TRACFCOMP( g_trac_pnor, "PnorRP::computeSection> Invalid virtual address : i_vaddr=%X", i_vaddr );
        /*@
         * @errortype
         * @moduleid     PNOR::MOD_PNORRP_COMPUTESECTION
         * @reasoncode   PNOR::RC_INVALID_ADDRESS
         * @userdata1    Requested Virtual Address
         * @userdata2    <unused>
         * @devdesc      PnorRP::computeSection> Invalid Address
         * @custdesc    A problem occurred while accessing the boot flash.
         */
        errhdl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                         PNOR::MOD_PNORRP_COMPUTESECTION,
                                         PNOR::RC_INVALID_ADDRESS,
                                         i_vaddr,
                                         0,
                                         true /*Add HB SW Callout*/);
        errhdl->collectTrace(PNOR_COMP_NAME);
        return errhdl;
    }

    return errhdl;
}

errlHndl_t PnorRP::clearSection(PNOR::SectionId i_section)
{
    TRACFCOMP(g_trac_pnor, "PnorRP::clearSection Section id = %d", i_section);
    errlHndl_t l_errl = NULL;
    const uint64_t CLEAR_BYTE = 0xFF;
    uint8_t* l_buf = new uint8_t[PAGESIZE];
    uint8_t* l_eccBuf = NULL;

    do
    {
        // Flush pages of pnor section we are trying to clear
        l_errl = flush(i_section);
        if (l_errl)
        {
            TRACFCOMP( g_trac_pnor, ERR_MRK"PnorRP::clearSection: flush() failed on section",
                        i_section);
            break;
        }

        // Get PNOR section info
        uint64_t l_address = iv_TOC[i_section].flashAddr;
        uint64_t l_chipSelect = iv_TOC[i_section].chip;
        uint32_t l_size = iv_TOC[i_section].size;
        bool l_ecc = iv_TOC[i_section].integrity & FFS_INTEG_ECC_PROTECT;

        // Number of pages needed to cycle proper ECC
        // Meaning every 9th page will copy the l_eccBuf at offset 0
        const uint64_t l_eccCycleNum = 9;

        // Boundaries for properly splitting up an ECC page for 4K writes.
        // Subtract 1 from l_eccCycleNum because we start writing with offset 0
        // and add this value 8 times to complete a cycle.
        const uint64_t l_sizeOfOverlapSection = (PAGESIZE_PLUS_ECC - PAGESIZE) /
                                                (l_eccCycleNum - 1);

        // Create clear section buffer
        memset(l_buf, CLEAR_BYTE, PAGESIZE);

        // apply ECC to data if needed
        if(l_ecc)
        {
            l_eccBuf = new uint8_t[PAGESIZE_PLUS_ECC];
            PNOR::ECC::injectECC( reinterpret_cast<uint8_t*>(l_buf),
                                  PAGESIZE,
                                  reinterpret_cast<uint8_t*>(l_eccBuf) );
            l_size = (l_size*9)/8;
        }

        // Write clear section page to PNOR
        for (uint64_t i = 0; i < l_size; i+=PAGESIZE)
        {
            if(l_ecc)
            {
                // Take (current page) mod (l_eccCycleNum) to get cycle position
                uint8_t l_bufPos = ( (i/PAGESIZE) % l_eccCycleNum );
                uint64_t l_bufOffset = l_sizeOfOverlapSection * l_bufPos;
                memcpy(l_buf, (l_eccBuf + l_bufOffset), PAGESIZE);
            }

            // Set ecc parameter to false to avoid double writes will only write
            // 4k at a time, even if the section is ecc protected.
            l_errl = writeToDevice((l_address + i), l_chipSelect,
                                   false, l_buf);
            if (l_errl)
            {
                TRACFCOMP( g_trac_pnor, ERR_MRK"PnorRP::clearSection: writeToDevice fail: eid=0x%X, rc=0x%X",
                           l_errl->eid(), l_errl->reasonCode());
                break;
            }
        }
        if (l_errl)
        {
            break;
        }
    } while(0);

    // Free allocated memory
    if(l_eccBuf)
    {
        delete[] l_eccBuf;
    }
    delete [] l_buf;

    return l_errl;
}

/**
 * @brief check and fix correctable ECC errors for a given section
 */
errlHndl_t PnorRP::fixECC (PNOR::SectionId i_section)
{
    errlHndl_t l_err  = NULL;
    uint8_t* l_buffer = new uint8_t [PAGESIZE] ();
    do {
        TRACFCOMP(g_trac_pnor, ENTER_MRK"PnorRP::fixECC");

        //get info from the TOC
        uint8_t* l_virtAddr = reinterpret_cast<uint8_t*>
                                (iv_TOC[i_section].virtAddr);
        uint32_t l_size    = iv_TOC[i_section].size;
        bool l_ecc         = iv_TOC[i_section].integrity&FFS_INTEG_ECC_PROTECT;

        if (!l_ecc)
        {
            TRACFCOMP(g_trac_pnor, "PnorRP::fixECC: section is not"
                    " ecc protected");
            /*@
             *  @errortype      ERRL_SEV_INFORMATIONAL
             *  @moduleid       PNOR::MOD_PNORRP_FIXECC
             *  @reasoncode     PNOR::RC_NON_ECC_PROTECTED_SECTION
             *  @userdata1      Section ID
             *  @userdata2      0
             *
             *  @devdesc        Non ECC protected section is passed to fixECC
             */
            l_err = new ERRORLOG::ErrlEntry(
                                    ERRORLOG::ERRL_SEV_INFORMATIONAL,
                                    PNOR::MOD_PNORRP_FIXECC,
                                    PNOR::RC_NON_ECC_PROTECTED_SECTION,
                                    i_section,
                                    0,true);
            break;
        }

        uint32_t l_numOfPages = (l_size)/PAGESIZE;

        //loop over number of pages in a section
        for (uint32_t i = 0; i < l_numOfPages; i++)
        {
            TRACDCOMP(g_trac_pnor, "PnorRP::fixECC: memcpy virtAddr:0x%X",
                      l_virtAddr);
            memcpy(l_buffer, l_virtAddr, PAGESIZE);
            l_virtAddr += PAGESIZE;
        }
    } while (0);

    delete [] l_buffer;
    TRACFCOMP(g_trac_pnor, EXIT_MRK"PnorRP::fixECC");
    return l_err;
}

uint64_t PnorRP::getTocOffset(TOCS i_toc) const
{
    // Can use a ternary operator because there are only 2 TOCs per side
    return (i_toc == TOC_0) ? iv_TocOffset[WORKING].first :
                              iv_TocOffset[WORKING].second;
}
OpenPOWER on IntegriCloud