-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathFlashProgrammer_ARM.cpp
3040 lines (2810 loc) · 115 KB
/
FlashProgrammer_ARM.cpp
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
/*! \file
\brief Utility Routines for programming ARM (Kinetis) Flash
FlashProgramming.cpp
\verbatim
Copyright (C) 2008 Peter O'Donoghue
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
\verbatim
+============================================================================================
| Revision History
+============================================================================================
| 14 Apr 17 | Fixed loadTargetProgram() for OpWriteRam - pgo 4.12.1.170
| 4 Mar 16 | Fixed saving/restoring security regions - pgo 4.12.1.90
| 29 Mar 15 | Refactored - pgo 4.11.1.10
+-----------+--------------------------------------------------------------------------------
| 20 Jan 15 | Cleanup of programming and readback code - pgo V4.10.6.250
| 18 Jan 15 | Addition of DSC mass erase using TCL code - pgo V4.10.6.250
| 18 Dec 14 | TCL interface changes - pgo V4.10.6.240
| 1 Dec 14 | Corrected logging printfs() - pgo V4.10.6.240
| 15 Sep 14 | Changed error check order in VerifyFlash() - pgo V4.10.6.190
| 17 Aug 14 | Changed SDID structure to support multiple masks - pgo V4.10.6.180
| 12 Jul 14 | Added getCommonFlashProgram(), changed getFlashProgram() etc - pgo V4.10.6.170
| 6 Nov 13 | 4.10.6.60 Changes to support PAxx small programmer - pgo
| 4 Jun 13 | 4.10.5.20 Set controller address in partitionFlexNVM() - pgo
| 28 Dec 12 | 4.10.4 Changed handling of security area (& erasing) - pgo
| 28 Dec 12 | 4.10.4 Changed TCL interface error handling - pgo
| 16 Dec 12 | 4.10.4 Moved Check of SDID to before Mass erase (HCS08) - pgo
| 14 Dec 12 | 4.10.4 Added custom security - pgo
| 30 Nov 12 | 4.10.4 Changed logging - pgo
| 30 Oct 12 | 4.10.4 Added MS_FAST option for HCS12/HCS12 - pgo
| 30 Sep 12 | 4.10.2 RAM write added - pgo
| 26 Aug 12 | 4.10.0 JTAG/SWD combined code - pgo
| 1 Jun 12 | 4.9.5 Now handles arbitrary number of memory regions - pgo
| 30 May 12 | 4.9.5 Re-write of DSC programming - pgo
| 12 Apr 12 | 4.9.4 Changed handling of empty images - pgo
| 30 Mar 12 | 4.9.4 Added Intelligent security option - pgo
| 25 Feb 12 | 4.9.1 Fixed alignment rounding problem on partial phrases - pgo
| 10 Feb 12 | 4.9.0 Major changes for HCS12 (Generalised code) - pgo
| 20 Nov 11 | 4.8.0 Major changes for Coldfire+ (Generalised code) - pgo
| 4 Oct 11 | 4.7.0 Added progress dialogues - pgo
| 23 Apr 11 | 4.6.0 Major changes for CFVx programming - pgo
| 6 Apr 11 | 4.6.0 Major changes for ARM programming - pgo
| 3 Jan 11 | 4.4.0 Major changes for XML device files etc - pgo
| 17 Sep 10 | 4.0.0 Fixed minor bug in isTrimLocation() - pgo
| 30 Jan 10 | 2.0.0 Changed to C++ - pgo
| | Added paged memory support - pgo
| 15 Dec 09 | 1.1.1 setFlashSecurity() was modifying image unnecessarily - pgo
| 14 Dec 09 | 1.1.0 Changed Trim to use linear curve fitting - pgo
| | FTRIM now combined with image value - pgo
| 7 Dec 09 | 1.0.3 Changed SOPT value to disable RESET pin - pgo
| 29 Nov 09 | 1.0.2 Bug fixes after trim testing - pgo
| 17 Nov 09 | 1.0.0 Created - pgo
+============================================================================================
\endverbatim
*/
#define _WIN32_IE 0x0500 //!< Required for common controls?
#define TARGET ARM
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string>
#include <ctype.h>
#include <memory.h>
#include "Common.h"
#include "UsbdmSystem.h"
#include "USBDM_API.h"
#include "TargetDefines.h"
#include "Utils.h"
#include "Names.h"
#include "ProgressTimer.h"
#include "SimpleSRecords.h"
#if (TARGET == ARM)
#include "STM32F100xx.h"
#include "ArmDefinitions.h"
#elif TARGET == MC56F80xx
#include "USBDM_DSC_API.h"
#endif
#include "UsbdmTclInterpreterFactory.h"
#include "WxPlugin.h"
#ifdef GDI
#include "GDI.h"
#include "MetrowerksInterface.h"
#endif
#include "Names.h"
#include "PluginHelper.h"
#include "FlashProgrammer_ARM.h"
static const TargetType_t targetType = T_ARM;
ModuleInfo FlashProgrammer_ARM::moduleInfo;
#pragma pack(1)
//! Header at the start of flash programming code (describes flash code)
struct LargeTargetImageHeader {
uint32_t loadAddress; //!< Address where to load this image
uint32_t entry; //!< Pointer to entry routine (for currently loaded routine)
uint32_t capabilities; //!< Capabilities of routine
uint32_t reserved1;
uint32_t reserved2;
uint32_t flashData; //!< Pointer to information about operation
};
//! Header at the start of timing data (controls program action & holds result)
struct LargeTargetTimingDataHeader {
uint32_t flags; //!< Controls actions of routine
uint32_t errorCode; //!< Error code from action
uint32_t controller; //!< Ptr to flash controller (unused)
uint32_t timingCount; //!< Timing count
};
//! Header at the start of flash programming buffer (controls program action)
struct LargeTargetFlashDataHeader {
uint32_t flags; //!< Controls actions of routine
uint32_t controller; //!< Ptr to flash controller
uint32_t frequency; //!< Target frequency (kHz)
uint16_t errorCode; //!< Error code from action
uint16_t sectorSize; //!< Size of Flash memory sectors (smallest erasable block)
uint32_t address; //!< Memory address being accessed (reserved/page/address)
uint32_t dataSize; //!< Size of memory range being accessed
uint32_t dataAddress; //!< Ptr to data to program
};
//! Holds program execution result
struct ResultStruct {
uint32_t flags; //!< Incomplete actions of routine
uint32_t reserved1;
uint32_t reserved2;
uint16_t errorCode; //!< Error code from action
uint16_t padding;
};
#pragma pack()
/* ======================================================================
* Notes on BDM clock source (for default CLKSW):
*
* CPU BDM clock
* ----------------------
* RS08 bus clock
* HCS08 bus clock
* HC12 bus clock
* CFV1 bus clock
*
*/
//=======================================================================================
inline uint16_t swap16(uint16_t data) {
return ((data<<8)&0xFF00) + ((data>>8)&0xFF);
}
inline uint32_t swap32(uint32_t data) {
return ((data<<24)&0xFF000000) + ((data<<8)&0xFF0000) + ((data>>8)&0xFF00) + ((data>>24)&0xFF);
}
inline uint32_t getData32Be(uint8_t *data) {
return (data[0]<<24)+(data[1]<<16)+(data[2]<<8)+data[3];
}
inline uint32_t getData32Le(uint8_t *data) {
return (data[3]<<24)+(data[2]<<16)+(data[1]<<8)+data[0];
}
inline uint32_t getData16Be(uint8_t *data) {
return (data[0]<<8)+data[1];
}
inline uint32_t getData16Le(uint8_t *data) {
return (data[1]<<8)+data[0];
}
inline uint32_t getData32Be(uint16_t *data) {
return (data[0]<<16)+data[1];
}
inline uint32_t getData32Le(uint16_t *data) {
return (data[1]<<16)+data[0];
}
inline const uint8_t *getData4x8Le(uint32_t data) {
static uint8_t data8[4];
data8[0]= data;
data8[1]= data>>8;
data8[2]= data>>16;
data8[3]= data>>24;
return data8;
}
inline const uint8_t *getData4x8Be(uint32_t data) {
static uint8_t data8[4];
data8[0]= data>>24;
data8[1]= data>>16;
data8[2]= data>>8;
data8[3]= data;
return data8;
}
inline const uint8_t *getData2x8Le(uint32_t data) {
static uint8_t data8[2];
data8[0]= data;
data8[1]= data>>8;
return data8;
}
inline const uint8_t *getData2x8Be(uint32_t data) {
static uint8_t data8[2];
data8[0]= data>>8;
data8[1]= data;
return data8;
}
#if (TARGET == ARM) || (TARGET == MC56F80xx)
#define targetToNative16(x) (x)
#define targetToNative32(x) (x)
#define nativeToTarget16(x) (x)
#define nativeToTarget32(x) (x)
inline uint32_t getData32Target(uint8_t *data) {
return getData32Le(data);
}
inline uint32_t getData16Target(uint8_t *data) {
return *data;
}
inline uint32_t getData32Target(uint16_t *data) {
return getData32Le(data);
}
inline uint32_t getData16Target(uint16_t *data) {
return *data;
}
#else
#define targetToNative16(x) swap16(x)
#define targetToNative32(x) swap32(x)
#define nativeToTarget16(x) swap16(x)
#define nativeToTarget32(x) swap32(x)
/**
* Get 32-bit target value from buffer i.e. converts from target to native format
*
* @param data Pointer to 1st byte of data in target format
*
* @return Data value in native format
*/
inline uint32_t getData32Target(uint8_t *data) {
return getData32Be(data);
}
/**
* Get 16-bit target value from buffer i.e. converts from target to native format
*
* @param data Pointer to 1st byte of data in target format
*
* @return Data value in native format
*/
inline uint32_t getData16Target(uint8_t *data) {
return getData16Be(data);
}
#endif
//=======================================================================
//
FlashProgrammer_ARM::FlashProgrammer_ARM() :
FlashProgrammerCommon(DeviceData::eraseMass, DeviceData::resetHardware),
initTargetDone(false),
currentFlashOperation(OpNone),
currentFlashAlignment(0),
doRamWrites(false),
calculatedTrimValue(0) {
LOGGING_E;
}
//=======================================================================
//
FlashProgrammer_ARM::~FlashProgrammer_ARM() {
LOGGING_E;
}
/**
* Connects to the target. \n
* - Resets target to special mode
* - Connects
* - Runs initialisation script
*
* @return error code, see \ref USBDM_ErrorCode \n
*/
USBDM_ErrorCode FlashProgrammer_ARM::resetAndConnectTarget(void) {
LOGGING;
USBDM_ErrorCode rc;
if (device == nullptr) {
return PROGRAMMING_RC_ERROR_ILLEGAL_PARAMS;
}
if (device->getTargetName().empty()) {
return PROGRAMMING_RC_ERROR_ILLEGAL_PARAMS;
}
flashReady = false;
initTargetDone = false;
TargetMode_t targetMode;
DeviceData::ResetMethod resetMethod = getResetMethod();
log.print("Setting reset method to %s\n", DeviceData::getResetMethodName(resetMethod));
switch (resetMethod) {
default:
case DeviceData::resetTargetDefault:
log.error("Unexpected reset method %s, defaulting to hardware\n", DeviceData::getResetMethodName(resetMethod));
// no break
case DeviceData::resetHardware:
targetMode = (TargetMode_t)(RESET_SPECIAL|RESET_HARDWARE);
break;
case DeviceData::resetSoftware:
targetMode = (TargetMode_t)(RESET_SPECIAL|RESET_SOFTWARE);
break;
case DeviceData::resetVendor:
targetMode = (TargetMode_t)(RESET_SPECIAL|RESET_VENDOR);
break;
}
// // Reset to special mode to allow unlocking of Flash
// rc = bdmInterface->reset(targetMode);
// if (rc != BDM_RC_OK) {
// // Try again with hardware reset
// log.print("failed reset with %s, retry with hardware\n", DeviceData::getResetMethodName(resetMethod));
// bdmInterface->connect();
// rc = bdmInterface->reset((TargetMode_t)(RESET_SPECIAL|RESET_HARDWARE));
// }
// if (rc == BDM_RC_SECURED) {
// log.error("... Device is secured\n");
// return PROGRAMMING_RC_ERROR_SECURED;
// }
// if (rc != BDM_RC_OK) {
// log.error( "... Failed Reset, %s!\n", bdmInterface->getErrorString(rc));
// return rc; //PROGRAMMING_RC_ERROR_BDM_CONNECT;
// }
// // Try auto Connect to target
// // BDM_RC_BDM_EN_FAILED usually means a secured device
// rc = bdmInterface->connect();
// switch (rc) {
// case BDM_RC_SECURED:
// case BDM_RC_BDM_EN_FAILED:
// // Treat as secured & continue
// log.error( "... Partial Connect, rc = %s!\n", bdmInterface->getErrorString(rc));
// rc = PROGRAMMING_RC_ERROR_SECURED;
// break;
// case BDM_RC_OK:
// rc = PROGRAMMING_RC_OK;
// break;
// default:
// log.error( "... Failed Connect, rc = %s!\n", bdmInterface->getErrorString(rc));
// return rc; //PROGRAMMING_RC_ERROR_BDM_CONNECT;
// }
// Use target TCL script to do entire reset and connection sequence
char args[100];
snprintf(args, sizeof(args), "resetAndConnectTarget %s", getTargetModeNameForTcl(targetMode));
rc = runTCLCommand(args);
if (rc != PROGRAMMING_RC_OK) {
log.error("Failed - initTarget TCL failed, rc = %d (%s)\n", rc, bdmInterface->getErrorString(rc));
if (rc != BDM_RC_SECURED) {
return rc;
}
}
// Use TCL script to set up target
USBDM_ErrorCode rc2 = initialiseTarget();
if (rc2 != PROGRAMMING_RC_OK) {
rc = rc2;
}
return rc;
}
//=============================================================================
//! Reads the System Device Identification Register
//!
//! @param targetSDID - location to return SDID
//! @param doInit - reset & re-connect to target first
//!
//! @return error code, see \ref USBDM_ErrorCode
//!
//! @note Assumes the target device has already been opened & USBDM options set.
//! @note Assumes the target has been reset in SPECIAL mode
//!
USBDM_ErrorCode FlashProgrammer_ARM::readTargetChipId(uint32_t *targetSDID, bool doInit) {
LOGGING_E;
doInit = doInit || (targetType == T_ARM);
const int SDIDLength = 4;
uint8_t SDIDValue[SDIDLength];
*targetSDID = 0x0000;
if (device->getTargetName().empty()) {
log.error("Target name not set\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
if (doInit) {
USBDM_ErrorCode rc = resetAndConnectTarget();
if (rc != PROGRAMMING_RC_OK) {
log.error("Failed resetAndConnectTarget()\n");
return rc;
}
}
if (bdmInterface->readMemory(SDIDLength, SDIDLength, device->getSDIDAddress(), SDIDValue) != BDM_RC_OK) {
log.error("A=0x%06X - Failed bdmInterface->readMemory()\n", device->getSDIDAddress());
return PROGRAMMING_RC_ERROR_BDM_READ;
}
uint32_t testValue;
if (SDIDLength == 4) {
*targetSDID = getData32Target(SDIDValue);
testValue = *targetSDID;
}
else {
*targetSDID = getData16Target(SDIDValue);
testValue = (uint32_t)(int32_t)(int16_t)*targetSDID;
}
// Do a sanity check on SDID (may get these values if secured w/o any error being signaled)
if ((testValue == 0xFFFFFFFF) || (testValue == 0x0)) {
log.error("A=0x%06X - Value invalid (0x%08X)\n", device->getSDIDAddress(), testValue);
return PROGRAMMING_RC_ERROR_BDM_READ;
}
log.print("A=0x%06X => 0x%08X\n", device->getSDIDAddress(), testValue);
return PROGRAMMING_RC_OK;
}
//=============================================================================
//! Check the target SDID agrees with device parameters
//!
//! @return error code, see \ref USBDM_ErrorCode
//!
//! @note Assumes the target has been connected to
//!
USBDM_ErrorCode FlashProgrammer_ARM::confirmSDID() {
LOGGING_E;
uint32_t targetSDID;
USBDM_ErrorCode rc;
if (device->getTargetName().empty()) {
log.error("Error: device parameters not set\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
// Don't check Target SDID if zero
if ((device->getSDID().mask == 0x0000) || (device->getSDID().value == 0x0000)) {
log.print("V=0x0000 => Skipping check\n");
return PROGRAMMING_RC_OK;
}
// Get SDID from target
rc = readTargetChipId(&targetSDID);
if (rc != PROGRAMMING_RC_OK) {
log.error("M=0x%8.8X, V=0x%8.8X => Failed, error reading SDID, reason = %s\n",
device->getSDID().mask,
device->getSDID().value,
bdmInterface->getErrorString(rc));
// Return this error even though the cause may be different
return PROGRAMMING_RC_ERROR_WRONG_SDID;
}
if (!device->isThisDeviceOrAlias(targetSDID)) {
log.error("M=0x%8.8X, V=0x%8.8X => Failed (Target SDID=0x%8.8X)\n",
device->getSDID().mask,
device->getSDID().value,
targetSDID);
return PROGRAMMING_RC_ERROR_WRONG_SDID;
}
log.print("V=%8.8X => OK\n", targetSDID);
return PROGRAMMING_RC_OK;
}
/**
* Prepares the target
*
* @return error code, see \ref USBDM_ErrorCode
*
* @note Assumes target has been reset & connected
*/
USBDM_ErrorCode FlashProgrammer_ARM::initialiseTarget() {
LOGGING;
USBDM_ErrorCode rc;
if (initTargetDone) {
log.print("Already done, skipped\n");
return PROGRAMMING_RC_OK;
}
char args[] = "initTarget \"\"";
rc = runTCLCommand(args);
if (rc != PROGRAMMING_RC_OK) {
log.error("Failed - initTarget TCL failed\n");
return rc;
}
initTargetDone = true;
return rc;
}
/**
* Prepares the target for Flash and eeprom operations. \n
*
* @return error code, see \ref USBDM_ErrorCode
*
* @note Assumes target has been reset & connected
*/
USBDM_ErrorCode FlashProgrammer_ARM::initialiseTargetFlash() {
LOGGING;
USBDM_ErrorCode rc;
// Check if already configured
if (flashReady) {
return PROGRAMMING_RC_OK;
}
char buffer[100];
sprintf(buffer, "initFlash %d", flashOperationInfo.targetBusFrequency);
rc = runTCLCommand(buffer);
if (rc != PROGRAMMING_RC_OK) {
log.error("Failed, initFlash TCL failed\n");
return rc;
}
// Flash is now ready for programming
flashReady = true;
return PROGRAMMING_RC_OK;
}
/**
* Does Mass Erase of Target memory using TCL script.
*
* @param resetTarget Whether to reset target before action
*
* @return error code, see \ref USBDM_ErrorCode
*/
USBDM_ErrorCode FlashProgrammer_ARM::massEraseTarget(bool resetTarget) {
LOGGING;
SetProgrammingMode pmode(bdmInterface);
USBDM_ErrorCode rc = BDM_RC_OK;
if (resetTarget) {
// Also does initialiseTarget()
rc = resetAndConnectTarget();
// Ignore some errors when mass erasing target as it is possible to mass
// erase some targets without a complete debug connection
if ((rc != BDM_RC_OK) &&
(rc != PROGRAMMING_RC_ERROR_SECURED) && // Secured device
(rc != BDM_RC_SECURED) && // Secured device
(rc != BDM_RC_BDM_EN_FAILED) && // BDM enable failed (on HCS devices)
(rc != BDM_RC_RESET_TIMEOUT_RISE) // Reset pulsing on Kinetis etc.
) {
return rc;
}
}
else {
rc = initialiseTarget();
if (rc != PROGRAMMING_RC_OK) {
return rc;
}
}
if (progressTimer != NULL) {
progressTimer->restart("Mass Erasing Target");
}
// Do Mass erase using TCL script
rc = runTCLCommand("massEraseTarget");
if (rc != PROGRAMMING_RC_OK) {
return rc;
}
// Don't reset device as it may only be temporarily unsecured!
return PROGRAMMING_RC_OK;
}
//==============================================================================
// Flag masks
#define DO_INIT_FLASH (1<<0) // Do initialisation of flash
#define DO_ERASE_BLOCK (1<<1) // Erase entire flash block e.g. Flash, FlexNVM etc
#define DO_ERASE_RANGE (1<<2) // Erase range (including option region)
#define DO_BLANK_CHECK_RANGE (1<<3) // Blank check region
#define DO_PROGRAM_RANGE (1<<4) // Program range (including option region)
#define DO_VERIFY_RANGE (1<<5) // Verify range
#define DO_PARTITION_FLEXNVM (1<<7) // Program FlexNVM DFLASH/EEPROM partitioning
#define DO_TIMING_LOOP (1<<8) // Counting loop to determine clock speed
// 24-30 reserved
#define IS_COMPLETE (1U<<31)
// Capability masks
#define CAP_ERASE_BLOCK (1<<1)
#define CAP_ERASE_RANGE (1<<2)
#define CAP_BLANK_CHECK_RANGE (1<<3)
#define CAP_PROGRAM_RANGE (1<<4)
#define CAP_VERIFY_RANGE (1<<5)
#define CAP_PARTITION_FLEXNVM (1<<7)
#define CAP_TIMING (1<<8)
#define CAP_DSC_OVERLAY (1<<11) // Indicates DSC code in pMEM overlays xRAM
#define CAP_DATA_FIXED (1<<12) // Indicates TargetFlashDataHeader is at fixed address
//
#define CAP_RELOCATABLE (1<<31) // Code may be relocated
#define OPT_SMALL_CODE (0x80)
#define OPT_PAGED_ADDRESSES (0x40)
#define OPT_WDOG_ADDRESS (0x20)
//=======================================================================
//! Loads the default Flash programming code to target memory
//!
//! @param flashOperation Intended operation in case of partial loading
//!
//! @return error code, see \ref USBDM_ErrorCode
//!
//! @note - Will load device program code or flashRegion specific if necessary
//! @note - see loadTargetProgram(MemoryRegionConstPtr, FlashOperation) for details
//!
USBDM_ErrorCode FlashProgrammer_ARM::loadTargetProgram(FlashOperation flashOperation) {
LOGGING;
FlashProgramConstPtr flashProgram = device->getFlashProgram();
return loadTargetProgram(flashProgram, flashOperation);
}
//==============================================================================
//! Loads the given Flash programming code to target memory
//!
//! @param memoryRegionPtr Memory region to load programming code for
//! @param flashOperation Intended operation in case of partial loading
//!
//!
//! @return error code, see \ref USBDM_ErrorCode
//! @note - see loadTargetProgram(MemoryRegionConstPtr, FlashOperation) for details
//!
USBDM_ErrorCode FlashProgrammer_ARM::loadTargetProgram(MemoryRegionConstPtr memoryRegionPtr, FlashOperation flashOperation) {
LOGGING_Q;
FlashProgramConstPtr flashProgram = memoryRegionPtr->getFlashprogram();
if (!flashProgram) {
// Try to get device general routines
flashProgram = device->getCommonFlashProgram();
}
return loadTargetProgram(flashProgram, flashOperation);
}
//==============================================================================
//! Loads the given Flash programming code to target memory
//!
//! @param flashProgram Flash program to load
//! @param flashOperation Intended operation in case of partial loading
//!
//! @return error code, see \ref USBDM_ErrorCode
//!
//! @note - Assumes the target has been connected to
//! Confirms download (if necessary) and checks RAM boundaries.
//!
USBDM_ErrorCode FlashProgrammer_ARM::loadTargetProgram(FlashProgramConstPtr flashProgram, FlashOperation flashOperation) {
LOGGING;
uint8_t buffer[4000] = {0};
log.print("Op=%s\n", getFlashOperationName(flashOperation));
switch(flashOperation) {
case OpSelectiveErase:
case OpBlockErase:
case OpBlankCheck:
case OpProgram:
case OpVerify:
case OpPartitionFlexNVM:
case OpTiming:
break;
default:
// All other operations don't require target Flash code
currentFlashOperation = OpNone;
log.print("No target program load needed\n");
return BDM_RC_OK;
}
// Check if we have a target flash programming code for this region
if (!flashProgram) {
log.error("Failed, no flash program found for target memory region\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
// Reload flash code if
// - code changed
// - operation changed
// - alignment changed
if (currentFlashProgram != flashProgram) {
log.print("Reloading due to change in flash code\n");
}
else if ((currentFlashOperation == OpNone) || (currentFlashOperation != flashOperation)) {
log.print("Reloading due to change in flash operation\n");
}
else if (currentFlashAlignment != flashOperationInfo.alignment) {
log.print("Reloading due to change in flash alignment\n");
}
else {
log.print("Re-using existing code\n");
return PROGRAMMING_RC_OK;
}
currentFlashOperation = OpNone;
unsigned size; // In uint8_t
uint32_t imageAddress;
USBDM_ErrorCode rc = loadSRec(flashProgram->getFlashProgram().c_str(),
buffer,
sizeof(buffer)/sizeof(buffer[0]),
&size,
&imageAddress);
if (rc != BDM_RC_OK) {
log.error("Failed, loadSRec() failed\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
// Find RAM region to use
if (!device->getCoalescedRamRegionFor(imageAddress, ramStart, ramEnd)) {
log.error("Failed to find suitable ram region for load address %08X.\n", imageAddress);
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
log.print("Using RAM region [0x%08X..0x%08X]\n", ramStart, ramEnd);
memset(&targetProgramInfo, 0, sizeof(targetProgramInfo));
MemorySpace_t memorySpace = MS_Byte;
// Probe RAM buffer
rc = probeMemory(memorySpace, ramStart);
if (rc == BDM_RC_OK) {
rc = probeMemory(memorySpace, ramEnd);
}
if (rc != BDM_RC_OK) {
log.error("Failed, probeMemory() failed\n");
return rc;
}
targetProgramInfo.smallProgram = false;
return loadLargeTargetProgram(buffer, imageAddress, size, flashProgram, flashOperation);
}
//=======================================================================
//! Loads the given Flash programming code to target memory
//!
//! @param buffer buffer containing program image
//! @param imageAddress address of start of image (may be relocated)
//! @param imageSize size of image (in uint8_t)s
//! @param flashProgram flash program corresponding to image
//! @param flashOperation intended operation in case of partial loading
//!
//! @return error code, see \ref USBDM_ErrorCode
//!
//! @note - Assumes the target has been connected to
//! Confirms download (if necessary) and checks RAM upper boundary.
//! targetProgramInfo is updated with load information
//!
//! Target Memory map
//! +---------------------------------------------------+ -+
//! | LargeTargetImageHeader flashProgramHeader; | |
//! +---------------------------------------------------+ > Unchanging for repeated operations
//! | Flash program code.... | |
//! +---------------------------------------------------+ -+
//!
USBDM_ErrorCode FlashProgrammer_ARM::loadLargeTargetProgram(
uint8_t *buffer,
uint32_t imageAddress,
uint32_t imageSize,
FlashProgramConstPtr flashProgram,
FlashOperation flashOperation) {
LOGGING;
log.print("Op=%s\n", getFlashOperationName(flashOperation));
// Find 'header' in download image
uint32_t headerAddress = getData32Target(buffer);
LargeTargetImageHeader *headerPtr = (LargeTargetImageHeader*) (buffer+(headerAddress-imageAddress));
if (headerPtr > (LargeTargetImageHeader*)(buffer+imageSize)) {
log.error("Header ptr out of range\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
// Save the programming data structure
uint32_t codeLoadAddress = targetToNative32(headerPtr->loadAddress);
uint32_t codeEntry = targetToNative32(headerPtr->entry);
uint32_t capabilities = targetToNative32(headerPtr->capabilities);
uint32_t dataHeaderAddress = targetToNative32(headerPtr->flashData);
log.print("Loaded Image (unmodified) :\n");
log.print(" flashProgramHeader headerAddress = 0x%08X\n", headerAddress);
log.print(" flashProgramHeader.loadAddress = 0x%08X\n", codeLoadAddress);
log.print(" flashProgramHeader.entry = 0x%08X\n", codeEntry);
log.print(" flashProgramHeader.capabilities = 0x%08X(%s)\n", capabilities, getProgramCapabilityNames(capabilities));
log.print(" flashProgramHeader.flashData = 0x%08X\n", dataHeaderAddress);
if (codeLoadAddress != imageAddress) {
log.error("Inconsistent actual (0x%06X) and image load addresses (0x%06X).\n",
imageAddress, codeLoadAddress);
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
uint32_t codeLoadSize = imageSize*sizeof(uint8_t);
if ((capabilities&CAP_RELOCATABLE) !=0 ) {
// Relocate Code
codeLoadAddress = (ramStart+3)&~3; // Relocate to start of RAM
if (imageAddress != codeLoadAddress) {
log.print("Loading at non-default address, load@0x%04X (relocated from=%04X)\n",
codeLoadAddress, imageAddress);
// Relocate entry point
codeEntry += codeLoadAddress - imageAddress;
}
}
if ((codeLoadAddress < ramStart) || (codeLoadAddress > ramEnd)) {
log.error("Image load address (0x%8X) is invalid: range [0x%8X, 0x%8X].\n", codeLoadAddress, ramStart, ramEnd);
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
if ((codeEntry < ramStart) || (codeEntry > ramEnd)) {
log.error("Image Entry point (0x%8X) is invalid: range [0x%8X, 0x%8X].\n", codeEntry, ramStart, ramEnd);
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
if ((capabilities&CAP_DATA_FIXED)==0) {
// Relocate Data Entry to immediately after code
dataHeaderAddress = codeLoadAddress + imageSize;
log.print("Relocating flashData @ 0x%06X\n", dataHeaderAddress);
}
// Required flash flashAlignmentMask
uint32_t flashAlignmentMask = flashOperationInfo.alignment-1;
uint32_t procAlignmentMask = 2-1;
// Save location of entry point
targetProgramInfo.entry = codeEntry;
// Were to load flash buffer (including header)
targetProgramInfo.headerAddress = dataHeaderAddress;
// Save offset of RAM data buffer
uint32_t dataLoadAddress = dataHeaderAddress+sizeof(LargeTargetFlashDataHeader);
// Align buffer address to worse case alignment for processor read
dataLoadAddress = (dataLoadAddress+procAlignmentMask)&~procAlignmentMask;
targetProgramInfo.dataOffset = dataLoadAddress-dataHeaderAddress;
// Save maximum size of the buffer (in uint8_t)
targetProgramInfo.maxDataSize = ramEnd-dataLoadAddress+1;
// Align buffer size to worse case alignment for processor read
targetProgramInfo.maxDataSize = targetProgramInfo.maxDataSize&~procAlignmentMask;
// Align buffer size to flash alignment requirement
targetProgramInfo.maxDataSize = targetProgramInfo.maxDataSize&~flashAlignmentMask;
// Save target program capabilities
targetProgramInfo.capabilities = capabilities;
// Save clock calibration factor
targetProgramInfo.calibFactor = 1;
log.print("AlignmentMask=0x%08X\n",
flashAlignmentMask);
log.print("Program code[0x%06X...0x%06X]\n",
codeLoadAddress, codeLoadAddress+imageSize-1);
log.print("Parameters[0x%06X...0x%06X]\n",
targetProgramInfo.headerAddress,
targetProgramInfo.headerAddress+targetProgramInfo.dataOffset-1);
log.print("RAM buffer[0x%06X...0x%06X]\n",
targetProgramInfo.headerAddress+targetProgramInfo.dataOffset,
targetProgramInfo.headerAddress+targetProgramInfo.dataOffset+targetProgramInfo.maxDataSize-1);
log.print("Entry=0x%06X\n", targetProgramInfo.entry);
// RS08, HCS08, HCS12 are byte aligned
// MC56F80xx deals with word addresses which are always aligned
if ((codeLoadAddress & procAlignmentMask) != 0) {
log.error("CodeLoadAddress is not aligned\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
if (((targetProgramInfo.headerAddress+targetProgramInfo.dataOffset) & procAlignmentMask) != 0) {
log.error("FlashProgramHeader.dataOffset is not aligned\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
if ((targetProgramInfo.entry & procAlignmentMask) != (targetType == T_ARM)?1:0){
log.error("FlashProgramHeader.entry is not aligned\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
// Sanity check buffer
if (((uint32_t)(targetProgramInfo.headerAddress+targetProgramInfo.dataOffset)<ramStart) ||
((uint32_t)(targetProgramInfo.headerAddress+targetProgramInfo.dataOffset+targetProgramInfo.maxDataSize-1)>ramEnd)) {
log.error("Data buffer location [0x%06X..0x%06X] is outside target RAM [0x%06X-0x%06X]\n",
targetProgramInfo.headerAddress+targetProgramInfo.dataOffset,
targetProgramInfo.headerAddress+targetProgramInfo.dataOffset+targetProgramInfo.maxDataSize-1,
ramStart, ramEnd);
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
if ((dataLoadAddress+40) > ramEnd) {
log.error("Data buffer is too small [0x%X..0x%X] \n", dataLoadAddress, ramEnd);
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
#if TARGET == MC56F80xx
MemorySpace_t memorySpace = MS_PWord;
#elif TARGET == ARM
MemorySpace_t memorySpace = MS_Long;
#elif (TARGET == S12Z)
MemorySpace_t memorySpace = (MemorySpace_t)MS_Word;
#elif (TARGET == HCS08) || (TARGET == HCS12)
MemorySpace_t memorySpace = (MemorySpace_t)(MS_Fast|MS_Byte);
#else
MemorySpace_t memorySpace = MS_Byte;
#endif
headerPtr->flashData = nativeToTarget32(targetProgramInfo.headerAddress);
log.print("Loaded Image (modified) :\n");
log.print(" flashProgramHeader.loadAddress = 0x%08X\n", targetToNative32(headerPtr->loadAddress));
log.print(" flashProgramHeader.entry = 0x%08X\n", targetToNative32(headerPtr->entry));
log.print(" flashProgramHeader.capabilities = 0x%08X(%s)\n", capabilities,getProgramCapabilityNames(capabilities));
log.print(" flashProgramHeader.flashData = 0x%08X\n", targetToNative32(headerPtr->flashData));
if (currentFlashProgram != flashProgram) {
log.print("Reloading due to change in flash code\n");
// Write the flash programming code to target memory
USBDM_ErrorCode rc = bdmInterface->writeMemory(memorySpace, codeLoadSize, codeLoadAddress, (uint8_t *)buffer);
if (rc != BDM_RC_OK) {
log.print("bdmInterface->writeMemory() Failed, rc = %d (%s)\n", rc, bdmInterface->getErrorString(rc));
return PROGRAMMING_RC_ERROR_BDM_WRITE;
}
}
else {
log.print("Suppressing code load as unchanged\n");
}
currentFlashProgram = flashProgram;
currentFlashOperation = flashOperation;
currentFlashAlignment = flashOperationInfo.alignment;
// Loaded routines support extended operations
targetProgramInfo.programOperation = DO_BLANK_CHECK_RANGE|DO_PROGRAM_RANGE|DO_VERIFY_RANGE;
return BDM_RC_OK;
}
//=======================================================================
//! Loads the given Flash programming code to target memory
//!
//! @param buffer buffer containing data to load
//! @param loadAddress address to load at
//! @param size size of data in buffer
//! @param flashProgram program to load
//! @param flashOperation operation to do
//!
//! @return error code, see \ref USBDM_ErrorCode
//!
//! @note - Assumes the target has been connected to
//! Confirms down-load (if necessary) and checks RAM upper boundary.
//!
//! Target Memory map (RAM buffer)
//! +-----------------------------------------+ -+
//! | SmallTagetFlashDataHeader flashData; | > Write/Read
//! +-----------------------------------------+ -+
//! | Data to program.... | > Write
//! +-----------------------------------------+ -+
//! | Flash program code.... | > Unchanging written once
//! +-----------------------------------------+ -+
//!
USBDM_ErrorCode FlashProgrammer_ARM::loadSmallTargetProgram(
uint8_t *buffer,
uint32_t loadAddress,
uint32_t size,
FlashProgramConstPtr flashProgram,
FlashOperation flashOperation) {
LOGGING;
log.error("Not supported\n");
return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED;
}
//! \brief Maps a Flash action vector to Text
//!
//! @param actions => action to describe
//!
//! @return pointer to static string buffer describing the actions
//!
const char *FlashProgrammer_ARM::getProgramActionNames(unsigned int actions) {
unsigned index;
static char buff[250] = "";
static const char *actionTable[] = {
"DO_INIT_FLASH|", // Do initialisation of flash
"DO_ERASE_BLOCK|", // Mass erase device
"DO_ERASE_RANGE|", // Erase range (including option region)
"DO_BLANK_CHECK_RANGE|", // Blank check region
"DO_PROGRAM_RANGE|", // Program range (including option region)
"DO_VERIFY_RANGE|", // Verify range
"??|",
"DO_PARTITION_FLEXNVM|", // Partition FlexNVM boundary
"DO_TIMING_LOOP|", // Execute timing loop on target
};
buff[0] = '\0';
for (index=0;
index<sizeof(actionTable)/sizeof(actionTable[0]);
index++) {
uint32_t mask = 1<<index;
if ((actions&mask) != 0) {
strcat(buff,actionTable[index]);
actions &= ~mask;
}
}
if (actions&IS_COMPLETE) {
actions &= ~IS_COMPLETE;
strcat(buff,"IS_COMPLETE|");
}
if (actions != 0) {
strcat(buff,"???");
}
return buff;
}
//! \brief Maps a Flash capability vector to Text
//!
//! @param actions => actions to describe
//!
//! @return pointer to static string buffer describing actions
//!
const char *FlashProgrammer_ARM::getProgramCapabilityNames(unsigned int actions) {
unsigned index;
static char buff[250] = "";
static const char *actionTable[] = {
"??|", // Do initialisation of flash
"CAP_ERASE_BLOCK|", // Mass erase device