Default.JLinkScript 49.2 KB
Newer Older
时昊's avatar
时昊 committed
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
/******************************************************************************
 * $Revision: 8885 $
 * $Date: 2015-10-21 08:54:33 +0200 (Wed, 21 Oct 2015) $
 *****************************************************************************/
/* __DISCLAIMER_START__                                                      */
/******************************************************************************
* Copyright (C) 2014 Spansion LLC. All Rights Reserved. 
*
* This software is owned and published by: 
* Spansion LLC, 915 DeGuigne Dr. Sunnyvale, CA  94088-3453 ("Spansion").
*
* BY DOWNLOADING, INSTALLING OR USING THIS SOFTWARE, YOU AGREE TO BE BOUND 
* BY ALL THE TERMS AND CONDITIONS OF THIS AGREEMENT.
*
* This software contains source code for use with Spansion 
* components. This software is licensed by Spansion to be adapted only 
* for use in systems utilizing Spansion components. Spansion shall not be 
* responsible for misuse or illegal use of this software for devices not 
* supported herein.  Spansion is providing this software "AS IS" and will 
* not be responsible for issues arising from incorrect user implementation 
* of the software.  
*
* SPANSION MAKES NO WARRANTY, EXPRESS OR IMPLIED, ARISING BY LAW OR OTHERWISE,
* REGARDING THE SOFTWARE (INCLUDING ANY ACOOMPANYING WRITTEN MATERIALS), 
* ITS PERFORMANCE OR SUITABILITY FOR YOUR INTENDED USE, INCLUDING, 
* WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, THE IMPLIED 
* WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE, AND THE IMPLIED 
* WARRANTY OF NONINFRINGEMENT.  
* SPANSION SHALL HAVE NO LIABILITY (WHETHER IN CONTRACT, WARRANTY, TORT, 
* NEGLIGENCE OR OTHERWISE) FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT 
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, 
* LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM USE OR 
* INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY DIRECT, 
* INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS OF DATA, 
* SAVINGS OR PROFITS, 
* EVEN IF SPANSION HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 
* YOU ASSUME ALL RESPONSIBILITIES FOR SELECTION OF THE SOFTWARE TO ACHIEVE YOUR
* INTENDED RESULTS, AND FOR THE INSTALLATION OF, USE OF, AND RESULTS OBTAINED 
* FROM, THE SOFTWARE.  
*
* This software may be replicated in part or whole for the licensed use, 
* with the restriction that this Disclaimer and Copyright notice must be 
* included with each copy of this software, whether used in part or whole, 
* at all times.
******************************************************************************/
/* __DISCLAIMER_END__                                                        */
/*****************************************************************************/
/** \file Default.JLinkScript
 **
 **
 ** History:
 **   - 2014-09-11    0.01    CEy    Initial version for Traveo
 **                                  (tested with JLinkARM.dll 4.90d)
 **   - 2014-10-24    0.02    CEy    Added device S6J326CL
 **   - 2014-11-21    0.03    CEy    Added device S6J326CK
 **   - 2015-01-20    0.04    CEy    Added device S6J32DAL
 **   - 2015-03-12    0.05    CEy    Added further device IDs
 **   - 2015-10-21    0.06    CEy    Added further device IDs and port function,
 **                                  rename Spansion to Cypress in script output
 *****************************************************************************/

/*****************************************************************************
*  For further information refer to the following documents:
*
*  - "ARM Debug Interface v5 Architecture Specification"
*    ARM: IHI0031A_ARM_debug_interface_v5.pdf
*  - "Cortex-R5 and Cortex-R5F (Revision r1p3) Technical Reference Manual"
*    ARM: DDI0460D_cortexr5_r1p3_trm.pdf
*  - "J-Link / J-Trace User Guide"
*    SEGGER: UM08001_JLinkARM.pdf


*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*  In case script shall be enhanced/adapted to other Traveo family members
*  search for the following marker to find the places which are device specific
*  <<<_DEVICE_SPECIFIC_>>>
*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*  Search for following marker to find the places which are user configurable
*  <<<_USER_CONFIGURATION_>>>
*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
*****************************************************************************/


// ###################################################################
//  H E L P E R   F U N C T I O N S
// ###################################################################

/*********************************************************************
*
*  _SelDP
*
*  Selects the Debug Port register set as the DR scan chain
*/
void _SelDP(void)
{
    JTAG_StoreIR(0xa);   // Updates Instruction Register scan chain
    JTAG_StoreClocks(1); // Transition from "Update-IR" to "Run-Test/Idle" state of Debug TAP
}

/*********************************************************************
*
*  _SelAP
*
*  Selects the Access Port register set as the DR scan chain
*/
void _SelAP(void)
{
    JTAG_StoreIR(0xb);   // Updates Instruction Register scan chain
    JTAG_StoreClocks(1); // Transition from "Update-IR" to "Run-Test/Idle" state of Debug TAP
}

/*********************************************************************
*
*  _TriggerReadAPDPReg
*
*  Triggers a read of an AP or DP register.
*  Depends on the previous command (_SelAP / _SelDP)
*
*  Parameter:
*  - u32RegIndex: 0-3 (selects which of the 4 registers shall be read)
*/
unsigned int _TriggerReadAPDPReg(unsigned int u32RegIndex)
{
    unsigned __int64 u64Value;        // We need 35 bits: 32 data, 2 bit addr, 1 bit RnW
    unsigned int u32BitPosData;

    // Write 35 bits (32 bits data, 2 bits addr, 1 bit RnW)
    u64Value = 0;
    u64Value |= 1;                    // Bit0 == 1 indicates read access
    u64Value |= (u32RegIndex << 1);
    u32BitPosData = JTAG_StoreDR(u64Value, 35); // Updates Data Register scan chain
    JTAG_WriteClocks(1); // Transition from "Update-DR" to "Run-Test/Idle" state of Debug TAP
    return u32BitPosData;
}

/*********************************************************************
*
*  _WriteAPDPReg
*
*  Writes an AP or DP register.
*  Depends on the previous command (_SelAP / _SelDP)
*
*  Parameter:
*  - u32RegIndex: 0-3 (selects which of the 4 registers shall be written)
*  - u32Data:     Data that shall be written
*
*  Return value:
*  - u32BitPosData:     Bit position of read data
*/
unsigned int _WriteAPDPReg(unsigned int u32RegIndex, unsigned int u32Data)
{
    unsigned __int64 u64Value;        // We need 35 bits: 32 data, 2 bit addr, 1 bit RnW
    unsigned int u32BitPosData;

    // Write 35 bits (32 bits data, 2 bits addr, 1 bit RnW)
    u64Value = 0; // Bit0 == 0 indicates write access
    u64Value |= (u32RegIndex << 1);
    u64Value |= (u32Data << 3);
    u32BitPosData = JTAG_StoreDR(u64Value, 35); // Updates Data Register scan chain
    JTAG_WriteClocks(1); // Transition from "Update-DR" to "Run-Test/Idle" state of Debug TAP
    return u32BitPosData;
}

/*********************************************************************
*
*  _StoreAPDPReg
*
*  Writes an AP or DP register.
*  Depends on the previous command (_SelAP / _SelDP)
*
*  Parameter:
*  - u32RegIndex: 0-3 (selects which of the 4 registers shall be written)
*  - u32Data:     Data that shall be written
*
*  Return value:
*  - u32BitPosData:     Bit position of read data
*/
unsigned int _StoreAPDPReg(unsigned int u32RegIndex, unsigned int u32Data)
{
    unsigned __int64 u64Value;        // We need 35 bits: 32 data, 2 bit addr, 1 bit RnW
    unsigned int u32BitPosData;

    // Write 35 bits (32 bits data, 2 bits addr, 1 bit RnW)
    u64Value = 0; // Bit0 == 0 indicates write access
    u64Value |= (u32RegIndex << 1);
    u64Value |= (u32Data << 3);
    u32BitPosData = JTAG_StoreDR(u64Value, 35); // Updates Data Register scan chain
    JTAG_StoreClocks(1); // Transition from "Update-DR" to "Run-Test/Idle" state of Debug TAP
    return u32BitPosData;
}

/*********************************************************************
*
*  _GetReadData
*
*  Returns the actual 32-bit read data from the specified register.
*  In order to get the wanted read data, a further action must be done
*  after the actual read access to shift the read data out of the scan
*  chain. This is done by reading the RDBUFF register in the DP which
*  is intended for this use case (a read to this register returns 0 and
*  has no side effects on the system)
*
*  Parameter:
*  - u32RegIndex:        0-3 (selects which of the 4 registers shall be read)
*  - cSelectApOnReturn:  If 0, DP is selected when function returns
*                        otherwise AP will be selected. Since no
*                        global variables are supported by JLinkScript
*                        the state cannot be restored in another way...
*
*  Return value:
*  - u32Data:            Read data
*/
unsigned int _GetReadData(unsigned int u32RegIndex, char cSelectApOnReturn)
{
    unsigned int u32Data;
    unsigned int u32BitPosData;

    // Trigger read to move wanted data in the DR scan chain
    _TriggerReadAPDPReg(u32RegIndex); 
    // Trigger read from RDBUFF register to shift out the wanted read data
    _SelDP();
    u32BitPosData = _TriggerReadAPDPReg(3);
    u32Data = JTAG_GetU32(u32BitPosData + 3);
    
    if (cSelectApOnReturn != 0)
    {
        _SelAP();
    }
    
    return u32Data;
}


/*********************************************************************
*
*  _WriteViaAhb
*
*  Writes to the MCU via the AHB-AP
*
*  Parameter:
*  - u32Address: Address for write action (as required by AHB master)
*  - u32Data:    Data that shall be written
*/
void _WriteViaAhb(unsigned int u32Address, unsigned int u32Data)
{
    _SelDP();
    _WriteAPDPReg(2, 0x00000000);  // Bank 0x0 of AHB-AP (0x00) selected
    
    _SelAP();
    _WriteAPDPReg(1, u32Address);  // Set TAR register of AP
    _WriteAPDPReg(3, u32Data);     // Write via DRW register of AP
}

/*********************************************************************
*
*  _ReadViaAhb
*
*  Reads from the MCU via the AHB-AP
*
*  Parameter:
*  - u32Address: Address for read action (as required by AHB master)
*
*  Return value:
*  - u32Data:    Data that has been read
*/
unsigned int _ReadViaAhb(unsigned int u32Address)
{
    unsigned int u32Data;

    _SelDP();
    _WriteAPDPReg(2, 0x00000000); // Bank 0x0 of AHB-AP (0x00) selected
    _SelAP();

    _WriteAPDPReg(1, u32Address); // Set TAR register of AP
    u32Data = _GetReadData(3, 0); // Read via DRW register of AP
    return u32Data;
}

/*********************************************************************
*
*  _WriteViaApb
*
*  Writes to the MCU via the APB-AP
*
*  Parameter:
*  - u32Address: Address for write action (as required by APB master)
*  - u32Data:    Data that shall be written
*/
void _WriteViaApb(unsigned int u32Address, unsigned int u32Data)
{
    _SelDP();
    _WriteAPDPReg(2, 0x01000000);  // Bank 0x0 of APB-AP (0x01) selected
    
    _SelAP();
    _WriteAPDPReg(1, u32Address);  // Set TAR register of AP
    _WriteAPDPReg(3, u32Data);     // Write via DRW register of AP
}

/*********************************************************************
*
*  _ReadViaApb
*
*  Reads from the MCU via the APB-AP
*
*  Parameter:
*  - u32Address: Address for read action (as required by APB master)
*
*  Return value:
*  - u32Data:    Data that has been read
*/
unsigned int _ReadViaApb(unsigned int u32Address)
{
    unsigned int u32Data;

    _SelDP();
    _WriteAPDPReg(2, 0x01000000); // Bank 0x0 of APB-AP (0x01) selected
    
    _SelAP();

    _WriteAPDPReg(1, u32Address); // Set TAR register of AP
    u32Data = _GetReadData(3, 0); // Read via DRW register of AP
    return u32Data;
}

/*********************************************************************
*
*  _GetAndClearStickyError
*
*  Checks if an error occurred after the last invocation of this function
*  This means the function can be called after several read/write actions
*  to check if this group of actions has been processed successfully
*
*  Return value:
*  - cStickyErrorFlag:    0 if no sticky error has occurred otherwise 1
*/
char _GetAndClearStickyError(void)
{
    unsigned int u32Data;
    char cStickyErrorFlag;

    _SelDP();
    u32Data = _GetReadData(1, 0);

    // Clear only Sticky Error Flag ('1' clears sticky flags)
    _WriteAPDPReg(1, ((u32Data & 0xffffffcd) | 0x20));
    if((u32Data & 0x20) == 0)
    {
        cStickyErrorFlag = 0;
    }
    else
    {
        cStickyErrorFlag = 1;
    }
    return cStickyErrorFlag;
}



// ###################################################################
//  U S E R   F U N C T I O N S
// ###################################################################

/*********************************************************************
*
*  PrintRead
*
*  Reads a value from an address and prints it to the log window
*
*  Parameter:
*  - bUseAhbPort:   0: APB port is used, else AHB
*  - u32Address:   address to be read from
*/
void PrintRead(char bUseAhbPort, unsigned int u32Address)
{
    unsigned int u32Data;
    
    if (bUseAhbPort == 0)
    {
        Report1("--- Cypress script --- Read address (APB): ", u32Address );
        u32Data = _ReadViaApb(u32Address);
    }
    else
    {
        Report1("--- Cypress script --- Read address (AHB): ", u32Address );
        u32Data = _ReadViaAhb(u32Address);
    }
    
    Report1("--- Cypress script ---         Read value: ", u32Data);
}


/*********************************************************************
*
*  ResetJtag
*
*  Resets the JTAG (and hence debug logic) for the specified time (ms)
*  by asserting nTRST pin
*
*  Parameter:
*  - u32ResetDuration:   Time in [ms] the reset signal is asserted
*/
void ResetJtag(unsigned int u32ResetDuration)
{
    Report("--- Cypress script --- JTAG reset");
    JTAG_TRSTPin = 0;
    SYS_Sleep(u32ResetDuration);
    JTAG_TRSTPin = 1;
}


/*********************************************************************
*
*  ResetMcu
*
*  Resets the MCU for the specified time (ms) via JTAG connector pin 15
*
*  Parameter:
*  - u32ResetDuration:   Time in [ms] the reset signal is asserted
*/
void ResetMcu(unsigned int u32ResetDuration)
{
    Report("--- Cypress script --- ============== MCU reset ==============");
    JTAG_ResetPin = 0;
    SYS_Sleep(u32ResetDuration);
    JTAG_ResetPin = 1;
}


/*********************************************************************
*
*  GetId
*
*  Checks the CoreSight JTAG IDCODE register
*/
void GetId(void)
{
    unsigned int u32Value;

    // Device Index parameter is counted from TDO
    u32Value = JTAG_GetDeviceId(0);
    
    if(u32Value == 0x4ba00477)
    {
        Report("--- Cypress script --- OK: ARM JTAG-DP detected (JTAG IDCODE: 0x4ba00477)");
    }
    else
    {
        Report1("--- Cypress script --- ERROR: JTAG IDCODE unknown -> ", u32Value);
    }
}


/*********************************************************************
*
*  PowerUpDebugPort
*
*  Sets the "power request bits" (CSYSPWRUPREQ, CDBGPWRUPREQ) in the
*  DP CTRL/STAT register and waits for their acknowledgement.
*
*  Return value:
*  - cError:    0 if power-up was successful otherwise 1
*/
char PowerUpDebugPort(void)
{
    unsigned int u32ReadData;
    unsigned int u32TimeOut;

    // Set CxxxPWRUPREQ bits and also clear sticky error flags, enable overrun detection
    _SelDP();
    _WriteAPDPReg(1, 0x50000033);
    
    u32TimeOut = 10;
    while(1)
    {
        u32TimeOut -= 1;
        
        u32ReadData = _GetReadData(1, 0);
        
        // Check if CxxxPWRUPREQ and CxxxPWRUPACK bits are set
        if ((u32ReadData >> 28) == 0xf)
        {
            // Report("--- Cypress script --- OK: Debug port powered up");
            return 0;
        }
        else if (u32TimeOut == 0)
        {
            Report("--- Cypress script --- ERROR: Could not power up debug port (time-out reached)!");
            return 1;
        }
    }
}


/*********************************************************************
*
*  InitAccessPorts
*
*  Initializes APB and AHB Access Port registers to their default value.
*  These registers may be in an unknown state because they are not
*  reset by an MCU hard reset. But the functions in here may rely on a 
*  defined state...
*/
void InitAccessPorts(void)
{
    // AHB Access Port
    // ---------------
    _SelDP();
    // Write DP APSEL register: Bank 0x0 of AHB-AP (AP-ID: 0x00) selected
    _WriteAPDPReg(2, 0x00000000);
    _SelAP();
    
    _WriteAPDPReg(0, 0x43000002); // Write CSW register of AHB-AP
    
    // APB Access Port
    // ---------------
    _SelDP();
    // Write DP APSEL register: Bank 0x0 of APB-AP (AP-ID: 0x01) selected
    _WriteAPDPReg(2, 0x01000000);
    _SelAP();
    
    _WriteAPDPReg(0, 0x80000002); // Write CSW register of APB-AP
}


/*********************************************************************
*
*  GetStat2RegVal
*
*  Returns the value of SCCFG_STAT2 register after DBGRDY bit has been set
*  because only then the content reflects the actual security configuration
*
*  Return value:
*  - u32SccfgStat2Value: Value of SCCFG_STAT2 or 0xFFFFFFFF on error/timeout
*/
unsigned int GetStat2RegVal(void)
{
    unsigned int u32TimeOut;
    unsigned int u32SccfgStat2AddressApb;
    unsigned int u32SccfgStat2Value;

    // Addresses as required for access via APB-AP
    u32SccfgStat2AddressApb = 0x000c0180;
    
    u32TimeOut = 10;
    while(1)
    {
        u32TimeOut -= 1;
        
        u32SccfgStat2Value = _ReadViaApb(u32SccfgStat2AddressApb);
        // Report1("--- Cypress script --- SCCFG_STAT2 = ", u32SccfgStat2Value);
        if(_GetAndClearStickyError() == 1)
        {
            Report("--- Cypress script --- ERROR: GetStat2RegVal() caused the StickyError flag to be set!");
            return 0xFFFFFFFF;
        }
        else if ((u32SccfgStat2Value & 0x100) != 0) // Check for SCCFG_STAT2_DBGRDY
        {
            // Report1("--- Cypress script --- OK: SCCFG_STAT2_DBGRDY is set, whole MCU can now be accessed (if unsecured))");
            return u32SccfgStat2Value;
        }
        else if (u32TimeOut == 0)
        {
            Report("--- Cypress script --- ERROR: SCCFG_STAT2_DBGRDY is not set (time-out reached)!");
            return 0xFFFFFFFF;
        }
    }
}


/*********************************************************************
*
*  UnlockDevice
*
*  If the MCU is secured, the passed security key will be entered
*  in the Security Checker module to unlock the MCU.
*  Otherwise this step is skipped
*
*  Note: Security key can be entered at any time, the result of key
*        entering will be available after SCCFG_STAT2_DBGRDY is set.
*
*  Parameter:
*  - u32KeyBytes0_3:   Part of the key for register SCCFG_SECKEY0
*  - u32KeyBytes4_7:   Part of the key for register SCCFG_SECKEY1
*  - u32KeyBytes8_11:  Part of the key for register SCCFG_SECKEY2
*  - u32KeyBytes12_15: Part of the key for register SCCFG_SECKEY3
*
*  Return value:
*  - cError: 0 if MCU unsecured or unlocking successful otherwise 1
*/
char UnlockDevice(unsigned int u32KeyBytes0_3, unsigned int u32KeyBytes4_7, unsigned int u32KeyBytes8_11, unsigned int u32KeyBytes12_15)
{
    unsigned int u32SccfgStat2Value;
    unsigned int u32SccfgUnlckAddressApb;
    unsigned int u32SccfgSeckey0AddressApb;
    unsigned int u32RegisterUnlockKey;
    unsigned int u32RegisterLockKey;
    unsigned int u32SccfgGpreg1AddressApb;
    unsigned int u32SccfgGpreg1Value;    
    
    // Check if security is enabled at all
    u32SccfgStat2Value = GetStat2RegVal();
    
    if((u32SccfgStat2Value & 0x1) == 0)
    {
        Report("--- Cypress script --- OK: MCU is unsecured");
        return 0;
    }
    else
    {
        // If MCU had been unlocked by a prior call to this function
        // or by SW in the MCU, there is nothing to do
        if(u32SccfgStat2Value == 0x101)
        {
            Report("--- Cypress script --- OK: MCU still unlocked");
            return 0;
        }
        
        // Addresses as required for access via APB-AP
        u32SccfgSeckey0AddressApb = 0x000c0190;
        u32SccfgUnlckAddressApb   = 0x000c01a4;

        // Security Checker Register Unlock/Lock Keys
        u32RegisterUnlockKey = 0x5ecacce5;
        u32RegisterLockKey   = 0xa135331a;    
        
        _GetAndClearStickyError();
        
        // Unlock SCCFG registers
        _WriteViaApb(u32SccfgUnlckAddressApb, u32RegisterUnlockKey);

        // Enter security key
        _WriteViaApb(u32SccfgSeckey0AddressApb      , u32KeyBytes0_3);
        _WriteViaApb(u32SccfgSeckey0AddressApb + 0x4, u32KeyBytes4_7);
        _WriteViaApb(u32SccfgSeckey0AddressApb + 0x8, u32KeyBytes8_11);
        _WriteViaApb(u32SccfgSeckey0AddressApb + 0xc, u32KeyBytes12_15);

        // Lock SCCFG registers again
        _WriteViaApb(u32SccfgUnlckAddressApb, u32RegisterLockKey);
        
        if(_GetAndClearStickyError() != 0)
        {
           Report("--- Cypress script --- ERROR: UnlockDevice() caused the StickyError flag to be set!");
           return 1;
        }
        else
        {
            // Read SCCFG_STAT2 to check for success
            u32SccfgStat2Value  = GetStat2RegVal();

            if((u32SccfgStat2Value & 0x7) == 0x03)
            {
                Report("--- Cypress script --- ERROR: Invalid security key entered!");
                return 1;
            }
            else if((u32SccfgStat2Value & 0x7) == 0x01)
            {
                Report("--- Cypress script --- OK: Correct security key entered, MCU unlocked");
                return 0;
            }
            else // is probably never reached
            {
                Report("--- Cypress script --- ERROR: Device still secured");
                return 1;
            }
        }
    }
    return 1;
}


/*********************************************************************
*
*  WaitForInstructionComplete
*
*  Waits for DBGDSCR.InstrCompl_1 to be set which indicates that the
*  current instruction that has been fed via ITR has finished
*
*  Return value:
*  - cError:    0 if waiting was successful otherwise 1
*/
char WaitForInstructionComplete(void)
{
    unsigned int u32TimeOut;
    unsigned int u32ReadData;
    unsigned int u32DebugStatusControlRegisterAddressApb;
    
    // Addresses as required for access via APB-AP
    u32DebugStatusControlRegisterAddressApb = 0x80090088;
    
    _GetAndClearStickyError();
    
    u32TimeOut = 10;
    while(1)
    {
        u32TimeOut -= 1;
    
        u32ReadData = _ReadViaApb(u32DebugStatusControlRegisterAddressApb);
        
        if(_GetAndClearStickyError() != 0)
        {
            Report("--- Cypress script --- ERROR: WaitForInstructionComplete() caused the StickyError flag to be set!");
            return 1;
        }
        if((u32ReadData & (1 << 24)) != 0)
        {
            return 0;
        }
        else if (u32TimeOut == 0)
        {
            Report("--- Cypress script --- ERROR: Debug instruction was not completed (time-out reached)!");
            return 1;
        }
    }
}

/*********************************************************************
*
*  GetCurrentPc
*
*  Returns the current value of the program counter
*  
*  Note: Core must be halted before calling this function!
*
*  Return value:
*  - u32CurrentPc:    Value of PC or 0xFFFFFFFF on error
*/
char GetCurrentPc(void)
{
    unsigned int u32CurrentPc;
    unsigned int u32TempData;
    unsigned int u32Reg0Save;
    unsigned int u32InstructionMovePcToR0;
    unsigned int u32InstructionReadR0;
    unsigned int u32InstructionWriteR0;
    unsigned int u32DebugStatusControlRegisterAddressApb;
    unsigned int u32InstructionTransferRegisterAddressApb;
    unsigned int u32DataTransferRegisterAddressApb;
        
    // Addresses as required for access via APB-AP
    u32InstructionTransferRegisterAddressApb = 0x80090084;
    u32DebugStatusControlRegisterAddressApb  = 0x80090088;
    u32DataTransferRegisterAddressApb        = 0x8009008c;
    
    // ARM instructions
    u32InstructionMovePcToR0 = 0xE1A0000F; // Instruction MOV r0, pc
    u32InstructionReadR0     = 0xEE000E15; // Instruction MCR p14, 0, Rd, c0, c5, 0  ; Rd is register 0
    u32InstructionWriteR0    = 0xEE100E15; // Instruction MRC p14, 0, Rd, c0, c5, 0  ; Rd is register 0

    _GetAndClearStickyError();
    
    // Set DBGDSCR.ITRen bit to enable transfer of instructions by debugger
    u32TempData = _ReadViaApb(u32DebugStatusControlRegisterAddressApb);
    // Report1("--- Cypress script --- DBGDSCR = ", u32TempData);
    _WriteViaApb(u32DebugStatusControlRegisterAddressApb, (u32TempData | (1 << 13)));
    
    // Save R0 because it must be temporarily used
    _WriteViaApb(u32InstructionTransferRegisterAddressApb, u32InstructionReadR0);
    WaitForInstructionComplete();        
    u32Reg0Save = _ReadViaApb(u32DataTransferRegisterAddressApb);
    
    // Copy PC to R0 and then read out R0 via debug register
    _WriteViaApb(u32InstructionTransferRegisterAddressApb, u32InstructionMovePcToR0);
    WaitForInstructionComplete();
    _WriteViaApb(u32InstructionTransferRegisterAddressApb, u32InstructionReadR0);
    WaitForInstructionComplete();
    u32CurrentPc = _ReadViaApb(u32DataTransferRegisterAddressApb);
    
    // Restore R0
    _WriteViaApb(u32DataTransferRegisterAddressApb, u32Reg0Save);
    _WriteViaApb(u32InstructionTransferRegisterAddressApb, u32InstructionWriteR0);
    WaitForInstructionComplete();    
        
    // Clear DBGDSCR.ITRen bit again because CPU behaviour would be unpredictable if set in non-debug state
    u32TempData = _ReadViaApb(u32DebugStatusControlRegisterAddressApb);
    _WriteViaApb(u32DebugStatusControlRegisterAddressApb, (u32TempData & 0xffffdfff));
    // u32TempData = _ReadViaApb(u32DebugStatusControlRegisterAddressApb);
    // Report1("--- Cypress script --- DBGDSCR = ", u32TempData);
    
    if(_GetAndClearStickyError() != 0)
    {
        Report("--- Cypress script --- ERROR: GetCurrentPc() caused the StickyError flag to be set!");
        return 0xffffffff;
    }
    
    // Report1("--- Cypress script --- OK: PC = ", u32CurrentPc);
    
    // In ARM architecture the actual PC is "current instruction + 8",
    // so this is "corrected" because usually the address of the current instruction is of interest
    return (u32CurrentPc - 8);
}


/*********************************************************************
*
*  HaltCore
*
*  Sets a request to halt the core (enter debug state) by setting
*  core debug register DRCR bit 0 and checks if halted by reading
*  the corresponding status register
*
*  Return value:
*  - cError:    0 if Core Halt Request was successful otherwise 1
*/
char HaltCore(void)
{
    char cIsHalted;
    unsigned int u32TimeOut;
    unsigned int u32DebugRunControlRegisterAddressApb;
    
    // Addresses as required for access via APB-AP
    u32DebugRunControlRegisterAddressApb    = 0x80090090;

    _GetAndClearStickyError();
    
    // Set Halt Request
    _WriteViaApb(u32DebugRunControlRegisterAddressApb, 0x00000001);
    
    if(_GetAndClearStickyError() != 0)
    {
        Report("--- Cypress script --- ERROR: HaltCore() caused the StickyError flag to be set!");
        return 1;
    }

    // Wait until Core halted
        
    u32TimeOut = 10;
    while(1)
    {
        u32TimeOut -= 1;
        
        cIsHalted = IsCoreHalted();
        
        if (cIsHalted != 0) // Check if core is halted
        {
            return 0;
        }
        else if (u32TimeOut == 0)
        {
            Report("--- Cypress script --- ERROR: Core could not be halted (time-out reached)!");
            return 1;
        }
    }
}


/*********************************************************************
*
*  IsCoreHalted
*
*  Returns whether the core is halted
*
*  Return value:
*  - cIsHalted:    0 if core is not halted otherwise 1
*/
char IsCoreHalted(void)
{
    unsigned int u32ReadData;
    unsigned int u32DebugStatusControlRegisterAddressApb;
    
    // Addresses as required for access via APB-AP
    u32DebugStatusControlRegisterAddressApb = 0x80090088;

    _GetAndClearStickyError();
    
    u32ReadData = _ReadViaApb(u32DebugStatusControlRegisterAddressApb);
            
    if(_GetAndClearStickyError() == 1)
    {
        Report("--- Cypress script --- ERROR: IsCoreHalted() caused the StickyError flag to be set!");
        return 0;
    }
    else if ((u32ReadData & 0x1) != 0) // Check if core is halted
    {
        // Report("--- Cypress script --- OK: Core is halted");
        return 1;
    }
    
    return 0;
}

/*********************************************************************
*
*  GetBreakpointControlReg
*
*  Returns the value of the breakpoint control register for the
*  specified breakpoint number
*  Parameter:
*  - BreakpointNumber:      Breakpoint number
*
*  Return value:
*  - cRegValue:    Register value if read was successful otherwise 0
*/
char GetBreakpointControlReg(char cBreakpointNumber)
{
    unsigned int u32BreakpointControlRegisterAddressApb;
    unsigned int u32RegValue;
    
    // Address as required for access via APB-AP
    u32BreakpointControlRegisterAddressApb = 0x80090140 + (4 * cBreakpointNumber);

    _GetAndClearStickyError();
    
    // Read breakpoint control register
    u32RegValue = _ReadViaApb(u32BreakpointControlRegisterAddressApb);
    
    if(_GetAndClearStickyError() != 0)
    {
        Report("--- Cypress script --- ERROR: GetBreakpointControlReg() caused the StickyError flag to be set!");
        return 0;
    }

    return u32RegValue;
}


/*********************************************************************
*
*  SetBreakpointControlReg
*
*  Writes the breakpoint control register for the specified
*  breakpoint number
*  Parameter:
*  - cBreakpointNumber:      Breakpoint number
*  - u32RegValue:            Value to be written
*
*  Return value:
*  - cError:    0 if register was written successful otherwise 1
*/
char SetBreakpointControlReg(char cBreakpointNumber, unsigned int u32RegValue)
{
    unsigned int u32BreakpointControlRegisterAddressApb;
    unsigned int u32RegValue;
    
    // Address as required for access via APB-AP
    u32BreakpointControlRegisterAddressApb = 0x80090140 + (4 * cBreakpointNumber);

    _GetAndClearStickyError();
    
    // Write breakpoint control register
    _WriteViaApb(u32BreakpointControlRegisterAddressApb, u32RegValue);
    
    if(_GetAndClearStickyError() != 0)
    {
        Report("--- Cypress script --- ERROR: SetBreakpointControlReg() caused the StickyError flag to be set!");
        return 1;
    }

    return 0;
}


/*********************************************************************
*
*  GetBreakpointValueReg
*
*  Returns the value of the breakpoint value register for the
*  specified breakpoint number
*  Parameter:
*  - cBreakpointNumber:      Breakpoint number
*
*  Return value:
*  - cRegValue:    Register value if read was successful otherwise 0
*/
char GetBreakpointValueReg(char cBreakpointNumber)
{
    unsigned int u32BreakpointValueRegisterAddressApb;
    unsigned int u32RegValue;
    
    // Address as required for access via APB-AP
    u32BreakpointValueRegisterAddressApb = 0x80090100 + (4 * cBreakpointNumber);

    _GetAndClearStickyError();
    
    // Read breakpoint control register
    u32RegValue = _ReadViaApb(u32BreakpointValueRegisterAddressApb);
    
    if(_GetAndClearStickyError() != 0)
    {
        Report("--- Cypress script --- ERROR: GetBreakpointValueReg() caused the StickyError flag to be set!");
        return 0;
    }

    return u32RegValue;
}


/*********************************************************************
*
*  SetBreakpointValueReg
*
*  Writes the breakpoint value register for the specified
*  breakpoint number
*  Parameter:
*  - cBreakpointNumber:      Breakpoint number
*  - u32RegValue:            Value to be written
*
*  Return value:
*  - cError:    0 if register was written successful otherwise 1
*/
char SetBreakpointValueReg(char cBreakpointNumber, unsigned int u32RegValue)
{
    unsigned int u32BreakpointValueRegisterAddressApb;
    unsigned int u32RegValue;
    
    // Address as required for access via APB-AP
    u32BreakpointValueRegisterAddressApb = 0x80090100 + (4 * cBreakpointNumber);

    _GetAndClearStickyError();
    
    // Write breakpoint control register
    _WriteViaApb(u32BreakpointValueRegisterAddressApb, u32RegValue);
    
    if(_GetAndClearStickyError() != 0)
    {
        Report("--- Cypress script --- ERROR: SetBreakpointValueReg() caused the StickyError flag to be set!");
        return 1;
    }

    return 0;
}



/*********************************************************************
*
*  SetBreakpoint
*
*  Sets the specified breakpoint to the specified address
*  Parameter:
*  - cBreakpointNumber:     Breakpoint number
*  - u32InstructionAddress: Instruction address
*
*  Return value:
*  - none
*/
void SetBreakpoint(char cBreakpointNumber, unsigned int u32InstructionAddress)
{
    // Set breakpoint instruction address
    SetBreakpointValueReg(cBreakpointNumber, u32InstructionAddress);
    // Enable breakpoint (instruction address match of any byte in any CPU mode)
    SetBreakpointControlReg(cBreakpointNumber, 0x000001e7);

    // Report1("--- Cypress script --- OK: Breakpoint has been set to address: ", u32InstructionAddress);
}


/*********************************************************************
*
*  DeleteBreakpoint
*
*  Deletes the specified breakpoint
*  Parameter:
*  - cBreakpointNumber:      Breakpoint number
*
*  Return value:
*  - none
*/
void DeleteBreakpoint(char cBreakpointNumber)
{
    // Disable breakpoint
    SetBreakpointControlReg(cBreakpointNumber, 0x00000000);
}



/*********************************************************************
*
*  SetSpecialDebugFeatures
*
*  Sets SCSCU_CNTL.JTAGCON, .WDG_RST_MASK, .FAKE_PDON and .FAKE_CLKON

*  Parameter:
*  - cMaskWdgReset:      if != 0 SW and HW watchdog resets are masked
*  - cEnableFakePowerOn: if != 0 Fake Power On mode is enabled
*  - cEnableFakeClockOn: if != 0 Fake Clock On mode is enabled
*
*  Return value:
*  - cError:   0 if special features were set successfully otherwise 1
*/
char SetSpecialDebugFeatures(char cMaskWdgReset, char cEnableFakePowerOn, char cEnableFakeClockOn)
{
    unsigned int u32ScscuCntlValue;
    unsigned int u32ScscuCntlAddressApb;
    unsigned int u32SccfgUnlckAddressApb;
    unsigned int u32RegisterUnlockKey;
    unsigned int u32RegisterLockKey;
    unsigned int u32RegValue;
    
    // Addresses as required for access via APB-AP or AHB-AP
    u32ScscuCntlAddressApb       = 0x000c01b4;
    u32SccfgUnlckAddressApb      = 0x000c01a4;    

    // Security Checker Register Unlock/Lock Keys
    u32RegisterUnlockKey = 0x5ecacce5;
    u32RegisterLockKey   = 0xa135331a;
    
     
    _GetAndClearStickyError();

    // Unlock SCCFG registers
    _WriteViaApb(u32SccfgUnlckAddressApb, u32RegisterUnlockKey);

    // Sets SCSCU_CNTL.JTAGCON and depending on parameters: .WDG_RST_MASK, .FAKE_PDON and .FAKE_CLKON
    u32RegValue = 0x00010000;
    Report("--- Cypress script --- OK: Setting special debug features: ");
    if(cMaskWdgReset != 0)
    {
        u32RegValue |= 0x00000100;
        Report("--- Cypress script ---     -> HW/SW Watchdog Reset Mask");
    }
    if(cEnableFakePowerOn != 0)
    {
        u32RegValue |= 0x00000010;
        Report("--- Cypress script ---     -> Fake Power On Mode");
    }
    if(cEnableFakeClockOn != 0)
    {
        u32RegValue |= 0x00000003;
        Report("--- Cypress script ---     -> Fake Clock On Mode");
    }
    if (u32RegValue == 0x00010000)
    {
        Report("--- Cypress script ---     -> none");
    }

    _WriteViaApb(u32ScscuCntlAddressApb, u32RegValue);

    // Lock SCCFG registers again
    _WriteViaApb(u32SccfgUnlckAddressApb, u32RegisterLockKey);


    if(_GetAndClearStickyError() != 0)
    {
       Report("--- Cypress script --- ERROR: SetSpecialDebugFeatures() caused the StickyError flag to be set!");
       return 1;
    }
    
    return 0;
}


/*********************************************************************
*
*  SetHaltingDebugMode
*
*  Sets DBGDSCR.HDBGen bit to ensure that CPU enters halting debug state
*  on debug event like a hit of the breakpoint we have configured.
*
*  Return value:
*  - cError:    0 if halting mode was set successfully otherwise 1
*/
void SetHaltingDebugMode(void)
{
    unsigned int u32ReadData;
    unsigned int u32DebugStatusControlRegisterAddressApb;
    
    // Addresses as required for access via APB-AP
    u32DebugStatusControlRegisterAddressApb = 0x80090088;
    
    _GetAndClearStickyError();
    
    // Sets DBGDSCR.HDBGen
    u32ReadData = _ReadViaApb(u32DebugStatusControlRegisterAddressApb);
    u32ReadData = u32ReadData | (1 << 14);
    _WriteViaApb(u32DebugStatusControlRegisterAddressApb, u32ReadData);
    
    if(_GetAndClearStickyError() != 0)
    {
       Report("--- Cypress script --- ERROR: SetHaltingDebugMode() caused the StickyError flag to be set!");
       return 1;
    }
    
    return 0;
}


/*********************************************************************
*
*  GetMcuSeriesArrayIndex
*
*  Reads SYSC0_SYSIDR to determine the current device in an array and
*  returns the index of the array match
*
*  Return value:
*  - cIndex:    Index of the device ID defined in the device ID array in
*               in this function. Can be sued to index other device
*               specific arrays, like BootROM end addresses. 
*               Returns 0xff if no device match is found
*/
char GetMcuSeriesArrayIndex(void)
{
    unsigned int u32ChipId;
    unsigned int u32Sysc0SysidrRegisterAddressAhb;
    unsigned int au32DeviceIds[6];
    unsigned int u32ChipIdMask;
    char cNrOfDeviceIds;
    char cIndex;
    
    // Addresses as required for access via AHB-AP
    u32Sysc0SysidrRegisterAddressAhb = 0xb0600280;
    
    // Currently Chip-ID is only required to retrieve BootROM end address of current MCU derivate
    // which usually should not differ for a family or over revisions
    u32ChipIdMask = 0xffff0000;
    
    // <<<_DEVICE_SPECIFIC_>>>
    au32DeviceIds[0] = 0x100a0100 & u32ChipIdMask; // S6J311EJ
    au32DeviceIds[1] = 0x10061000 & u32ChipIdMask; // S6J320CQX
    au32DeviceIds[2] = 0x10100000 & u32ChipIdMask; // S6J32-3/4/5/6/7/8
    au32DeviceIds[3] = 0x10110000 & u32ChipIdMask; // S6J32-A/B/C/D  
    //au32DeviceIds[4] = 0x10120000 & u32ChipIdMask; // S6J33?
    au32DeviceIds[4] = 0x10168100 & u32ChipIdMask; // S6J3360
    cNrOfDeviceIds = 5;
    
    
    _GetAndClearStickyError();
    
    // Read Chip ID
    u32ChipId = _ReadViaAhb(u32Sysc0SysidrRegisterAddressAhb);
    
    if(_GetAndClearStickyError() != 0)
    {
       Report("--- Cypress script --- ERROR: GetMcuSeriesArrayIndex() caused the StickyError flag to be set!");
       return 0xff;
    }
    Report1("--- Cypress script --- OK: Chip-ID is ", u32ChipId);
    
    u32ChipId = u32ChipId & u32ChipIdMask;
    
    cIndex = 0;
    while(cIndex < cNrOfDeviceIds)
    {
        if(au32DeviceIds[cIndex] == u32ChipId)
        {
            return cIndex;
        }
        cIndex += 1;
    }
    
    return 0xff;
}


/*********************************************************************
*
*  GetBootRomEndAddress
*
*  Returns the address of the "BX LR" instruction in the BootROM which
*  would branch to the actual user code. This address is device-specific
*
*  Return value:
*  - u32BootRomEndAddress:  The BootROM end address of the current device        
*/
unsigned int GetBootRomEndAddress(void)
{
    unsigned int au32BootRomEndAddress[5];
    char cIndex;
    
    // <<<_DEVICE_SPECIFIC_>>>
    au32BootRomEndAddress[0] = 0xffff12f8; // S6J311EJ
    au32BootRomEndAddress[1] = 0xffff1334; // S6J320CQX
    au32BootRomEndAddress[2] = 0xffff12f8; // S6J32-3/4/5/6/7/8
    au32BootRomEndAddress[3] = 0xffff12f8; // S6J32-A/B/C/D  
    au32BootRomEndAddress[4] = 0xffff12f8; // S6J33?  
    
    // Get array index (no out of bounds check will be made!)
    cIndex = GetMcuSeriesArrayIndex();
    
    if(cIndex != 0xff)
    {
        return au32BootRomEndAddress[cIndex];
    }
    else
    {
        return 0;
    }    
}


/*********************************************************************
*
*  ChangePortPin
*
*  Configures a port pin as GPIO output and sets the requested
*  output level (Function assumes that corresponding PPC_PCFGR register
*  has default reset value!)
*
*  Parameter:
*  - cPort:   Port number
*  - cPin:    Pin number (0..31)
*  - cLevel:  Logic level: 0 -> low, 1 -> high
*
*  Return value:
*  - cError:   0 if port pin was changed successfully otherwise 1
*/
char ChangePortPin(char cPort, char cPin, char cLevel)
{
    unsigned int u32Sysc0ProtkeyrAddressAhb;
    unsigned int u32SyscSpecfgrAddressAhb;
    unsigned int u32Value;
    unsigned int u32GpioKeycodeAddressAhb;
    unsigned int u32GpioRegsBaseAddressAhb;
    unsigned int u32GpioRegsIncrement;
    unsigned int u32GpioPosrOffset;
    unsigned int u32GpioPocrOffset;
    unsigned int u32GpioDdsrOffset;
    unsigned int u32Keycode1;
    unsigned int u32Keycode2;
    unsigned int u32Keycode3;
    unsigned int u32Keycode4;
    unsigned int u32TempAddressAhb;
    unsigned int u32TargetBit;
        
    // Addresses as required for access via AHB-AP
    u32Sysc0ProtkeyrAddressAhb = 0xb0600000;
    u32SyscSpecfgrAddressAhb   = 0xb0600680;
    u32GpioKeycodeAddressAhb   = 0xb4738404;
    u32GpioRegsBaseAddressAhb  = 0xb4738000;
    u32GpioRegsIncrement       = 0x10;
    u32GpioPosrOffset          = 0x0;
    u32GpioPocrOffset          = 0x4;
    u32GpioDdsrOffset          = 0x8;
    u32Keycode1                = 0x20000000;
    u32Keycode2                = 0x60000000;
    u32Keycode3                = 0xa0000000;
    u32Keycode4                = 0xe0000000;
    
    u32TargetBit = (1 << cPin);
     
    _GetAndClearStickyError();
    
    // First set port output data before switching to output mode
    if(cLevel == 0)
    {
        u32TempAddressAhb = u32GpioRegsBaseAddressAhb + (cPort * u32GpioRegsIncrement) + u32GpioPocrOffset;       
    }
    else
    {
        u32TempAddressAhb = u32GpioRegsBaseAddressAhb + (cPort * u32GpioRegsIncrement) + u32GpioPosrOffset;               
    }

    // Set output level
    _WriteViaAhb(u32GpioKeycodeAddressAhb, u32Keycode1 + (u32TempAddressAhb & 0x7fff));
    _WriteViaAhb(u32GpioKeycodeAddressAhb, u32Keycode2 + (u32TempAddressAhb & 0x7fff));
    _WriteViaAhb(u32GpioKeycodeAddressAhb, u32Keycode3 + (u32TempAddressAhb & 0x7fff));
    _WriteViaAhb(u32GpioKeycodeAddressAhb, u32Keycode4 + (u32TempAddressAhb & 0x7fff));
    _WriteViaAhb(u32TempAddressAhb, u32TargetBit);
    
    // Switch to output direction
    u32TempAddressAhb = u32GpioRegsBaseAddressAhb + (cPort * u32GpioRegsIncrement) + u32GpioDdsrOffset; 
    _WriteViaAhb(u32GpioKeycodeAddressAhb, u32Keycode1 + (u32TempAddressAhb & 0x7fff));
    _WriteViaAhb(u32GpioKeycodeAddressAhb, u32Keycode2 + (u32TempAddressAhb & 0x7fff));
    _WriteViaAhb(u32GpioKeycodeAddressAhb, u32Keycode3 + (u32TempAddressAhb & 0x7fff));
    _WriteViaAhb(u32GpioKeycodeAddressAhb, u32Keycode4 + (u32TempAddressAhb & 0x7fff));
    _WriteViaAhb(u32TempAddressAhb, u32TargetBit);    
    
    // Clear IO3RSTC and IO35RSTC bits
    u32Value = _ReadViaAhb(u32SyscSpecfgrAddressAhb);
    u32Value = u32Value & 0xff9fffff;
    _WriteViaAhb(u32Sysc0ProtkeyrAddressAhb, 0x5cacce55);
    _WriteViaAhb(u32SyscSpecfgrAddressAhb, u32Value);

    if(_GetAndClearStickyError() != 0)
    {
       Report("--- Cypress script --- ERROR: ChangePortPin() caused the StickyError flag to be set!");
       return 1;
    }
    else
    {
       Report("--- Cypress script --- OK: Port pin changed successfully!");
    }
    
    return 0;
}


/*********************************************************************
*
*  PrepareMcuBeforeReset
*
*  Halts the CPU and sets a breakpoint at the BootROM end address so
*  that CPU will stop there when the reset is triggered.
*/
void PrepareMcuBeforeReset(void)
{
    unsigned int u32BootRomEndAddress;
    
    HaltCore();
    u32BootRomEndAddress = GetBootRomEndAddress();    
    SetBreakpoint(0, u32BootRomEndAddress);        
    SetHaltingDebugMode();
}



/*********************************************************************
*
*  PrepareMcuAfterReset
*
*  Checks whether the CPU has really stopped at the BootROM end address
*  after reset and continues the preparation of the target MCU for
*  debugging.
*/
void PrepareMcuAfterReset(void)
{
    char cIsCoreHalted;
    unsigned int u32CurrentPc;
    unsigned int u32BootRomEndAddress;    
    u32BootRomEndAddress = GetBootRomEndAddress();
    
    InitAccessPorts();
    
    // <<<_USER_CONFIGURATION_>>>
    // Specify the security key that shall be used to unlock the MCU
    UnlockDevice(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff);
    
    cIsCoreHalted = IsCoreHalted();
    
    if (cIsCoreHalted == 0)
    {
        Report("--- Cypress script --- ERROR: Core has not halted after setting breakpoint to BootROM end address and reset");
    }
    else
    {
        u32CurrentPc = GetCurrentPc();
        
        if(u32CurrentPc != u32BootRomEndAddress)
        {
            Report1("--- Cypress script --- ERROR: Core has halted but not at BootROM end address. PC = ", u32CurrentPc);
        }
        else
        {
            // Breakpoint is no longer required
            DeleteBreakpoint(0);
            
            // <<<_USER_CONFIGURATION_>>>
            // Specify the special debug features (0 means FALSE, otherwise TRUE)
            // 1st parameter: Mask HW/SW watchdog reset
            // 2nd parameter: Enable Fake Power On mode
            // 3rd parameter: Enable Fake Clock On mode
            SetSpecialDebugFeatures(0, 0, 0);
        }    
    }
}

/*********************************************************************
*
*  ExecuteInitSequence
*
*  Executes the functions in the correct order that are required after
*  every initial connection or for resetting MCU. 
*/
void ExecuteInitSequence(void)
{
    unsigned int u32BreakpointControl;
    unsigned int u32BreakpointValue;
    char cBreakpointIsInUse;
    
    // Get breakpoint #0 control reg and also save value reg if breakpoint
    // is currently in use, so that both can be restored later
    u32BreakpointControl = GetBreakpointControlReg(0);
    cBreakpointIsInUse = (u32BreakpointControl & 0x1);
    if(cBreakpointIsInUse != 0)
    {
        u32BreakpointValue = GetBreakpointValueReg(0);
    }
    

    PrepareMcuBeforeReset();
    ResetMcu(1);   
    PrepareMcuAfterReset();
    
    
    // Now that the breakpoint for stopping at BootROM end address is no
    // longer required, we can restore the user breakpoint
    if(cBreakpointIsInUse != 0)
    {
        SetBreakpointValueReg(0, u32BreakpointValue);
        SetBreakpointControlReg(0, u32BreakpointControl);        
    }
}



// ###################################################################
//  S E G G E R   C A L L B A C K   F U N C T I O N S
// ###################################################################

/*********************************************************************
*
*  ResetTarget
*
*  Standard/Pre-defined SEGGER function that replaces
*  the reset functionality of the DLL/J-Link.
*/
void ResetTarget(void)
{
    Report("--- Cypress script --- ResetTarget() from JLinkScript is executed");  
    
    ExecuteInitSequence();
}


/*********************************************************************
*
*  InitTarget
*
*  Standard/Pre-defined SEGGER function that replaces the auto-detection
*  capability of J-Link and allows to setup custom initialisation commands
*/
void InitTarget(void)
{
    // There are two devices on the JTAG scan chain:
    //                  _____________              _____________       
    //                 | Bound. Scan |            |  CoreSight  |      
    //  Debugger       |             |            |             |       Debugger
    //  TDI_out  ----->|TDI       TDO|------>-----|TDI       TDO|-----> TDO_in
    //                 |   IR: 5     |            |    IR: 4    |      
    //                 |_____________|            |_____________|      
    // 
    //--------------------------------------------------------------------------------------------------
    JTAG_Speed         = 8000;
    JTAG_DRPre         = 0;         // Number of devices closer to TDO than the device J-Link talks to
    JTAG_DRPost        = 1;         // Number of devices closer to TDI than the device J-Link talks to
    JTAG_IRPre         = 0;         // Total IRLen of all devices which are closer to TDO than the device J-Link talks to
    JTAG_IRPost        = 5;         // Total IRLen of all devices which are closer to TDI than the device J-Link talks to
    JTAG_IRLen         = 4;         // IRLen of Cortex-R5
    CPU                = CORTEX_R5; // It is a Cortex-R5 core
    JTAG_AllowTAPReset = 1;         // En-/Disables auto-JTAG-detection of J-Link. Has to be disabled for 
                                    // devices which need some special init which is lost at a TAP reset.
                                    // Allowed values
                                    // - 0: Auto-detection is enabled.
                                    // - 1: Auto-detection is disabled.
    //--------------------------------------------------------------------------------------------------

    Report("--- Cypress script --- InitTarget() from JLinkScript is executed");

    //==================
    JTAG_ResetPin = 0;  // MCU reset assert
    //------------------
    // Reset Debug TAP and provide clock to enter Run-Test/Idle state
    ResetJtag(1);
    JTAG_WriteClocks(1);
    //------------------
    JTAG_ResetPin = 1;  // MCU reset de-assert  
    //==================
    
    PowerUpDebugPort();
    InitAccessPorts();
    
    // <<<_USER_CONFIGURATION_>>>
    // Specify the security key that shall be used to unlock the MCU
    UnlockDevice(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff);
    
    ExecuteInitSequence();    
}