114
|
1 import struct, time
|
113
|
2 from usb import UsbContext
|
|
3
|
|
4 class STLinkException(Exception):
|
|
5 pass
|
|
6
|
115
|
7 ST_VID, STLINK2_PID = 0x0483, 0x3748
|
|
8
|
113
|
9 def checkDevice(device):
|
|
10 return device.VendorId == ST_VID and device.ProductId == STLINK2_PID
|
|
11
|
115
|
12 DFU_MODE, MASS_MODE, DEBUG_MODE = 0, 1, 2
|
117
|
13
|
|
14 CORE_RUNNING = 0x80
|
|
15 CORE_HALTED = 0x81
|
|
16
|
114
|
17 # Commands:
|
|
18 GET_VERSION = 0xf1
|
|
19 DEBUG_COMMAND = 0xf2
|
|
20 DFU_COMMAND = 0xf3
|
|
21 GET_CURRENT_MODE = 0xf5
|
|
22
|
|
23 # dfu commands:
|
|
24 DFU_EXIT = 0x7
|
113
|
25
|
114
|
26 # debug commands:
|
|
27 DEBUG_ENTER = 0x20
|
|
28 DEBUG_EXIT = 0x21
|
|
29 DEBUG_ENTER_SWD = 0xa3
|
|
30 DEBUG_GETSTATUS = 0x01
|
116
|
31 DEBUG_RESETSYS = 0x03
|
115
|
32 DEBUG_READREG = 0x5
|
|
33 DEBUG_WRITEREG = 0x6
|
|
34 DEBUG_READMEM_32BIT = 0x7
|
|
35 DEBUG_WRITEMEM_32BIT = 0x8
|
117
|
36 DEBUG_RUNCORE = 0x9
|
|
37 DEBUG_STEPCORE = 0xa
|
114
|
38
|
115
|
39 JTAG_WRITEDEBUG_32BIT = 0x35
|
114
|
40 JTAG_READDEBUG_32BIT = 0x36
|
|
41
|
|
42 # cortex M3
|
|
43 CM3_REG_CPUID = 0xE000ED00
|
|
44
|
115
|
45 # F4 specifics:
|
|
46 STM32_FLASH_BASE = 0x08000000
|
|
47 STM32_SRAM_BASE = 0x20000000
|
|
48
|
116
|
49 FLASH_KEY1 = 0x45670123
|
|
50 FLASH_KEY2 = 0xcdef89ab
|
115
|
51 # flash registers:
|
116
|
52 FLASH_F4_REGS_ADDR = 0x40023c00
|
115
|
53
|
116
|
54 FLASH_F4_KEYR = FLASH_F4_REGS_ADDR + +0x04
|
115
|
55 FLASH_F4_SR = FLASH_F4_REGS_ADDR + 0x0c
|
|
56 FLASH_F4_CR = FLASH_F4_REGS_ADDR + 0x10
|
|
57
|
|
58 FLASH_F4_CR_START = 16
|
|
59 FLASH_F4_CR_LOCK = 31
|
117
|
60 FLASH_CR_PG = 0
|
115
|
61 FLASH_F4_CR_SER = 1
|
116
|
62 FLASH_CR_MER = 2
|
115
|
63 FLASH_F4_CR_SNB = 3
|
|
64 FLASH_F4_CR_SNB_MASK = 0x38
|
|
65 FLASH_F4_SR_BSY = 16
|
|
66
|
116
|
67 # flashloaders/stm32f4.s
|
|
68 loader_code_stm32f4 = bytes([
|
|
69 0x07, 0x4b,
|
|
70
|
|
71 0x62, 0xb1,
|
|
72 0x04, 0x68,
|
|
73 0x0c, 0x60,
|
|
74
|
|
75 0xdc, 0x89,
|
|
76 0x14, 0xf0, 0x01, 0x0f,
|
|
77 0xfb, 0xd1,
|
|
78 0x00, 0xf1, 0x04, 0x00,
|
|
79 0x01, 0xf1, 0x04, 0x01,
|
|
80 0xa2, 0xf1, 0x01, 0x02,
|
|
81 0xf1, 0xe7,
|
|
82
|
|
83 0x00, 0xbe,
|
|
84
|
|
85 0x00, 0x3c, 0x02, 0x40
|
|
86 ])
|
|
87
|
115
|
88 def calculate_F4_sector(address):
|
|
89 """
|
|
90 from 0x8000000 to 0x80FFFFF
|
|
91 4 sectors of 0x4000 (16 kB)
|
|
92 1 sector of 0x10000 (64 kB)
|
|
93 7 of 0x20000 (128 kB)
|
|
94 """
|
|
95 sectorsizes = [0x4000] * 4 + [0x10000] + [0x20000] * 7
|
|
96 sectorstarts = []
|
|
97 a = STM32_FLASH_BASE
|
|
98 for sectorsize in sectorsizes:
|
|
99 sectorstarts.append(a)
|
|
100 a += sectorsize
|
|
101 # linear search:
|
|
102 sec = 0
|
|
103 while sec < len(sectorsizes) and address >= sectorstarts[sec]:
|
|
104 sec += 1
|
|
105 sec -= 1 # one back.
|
|
106 return sec, sectorsizes[sec]
|
|
107
|
|
108 def calcSectors(address, size):
|
|
109 off = 0
|
|
110 sectors = []
|
|
111 while off < size:
|
|
112 sectornum, sectorsize = calculate_F4_sector(address + off)
|
|
113 #print('num: {0} size: {1:X} offset: {2}'.format(sectornum, sectorsize, off))
|
|
114 sectors.append((sectornum, sectorsize))
|
|
115 off += sectorsize
|
|
116 return sectors
|
|
117
|
114
|
118 class STLink:
|
119
|
119 """ ST link interface code """
|
|
120 def __init__(self, stlink2=None):
|
|
121 if not stlink2:
|
|
122 context = UsbContext()
|
|
123 stlink2s = list(filter(checkDevice, context.DeviceList))
|
|
124 if not stlink2s:
|
|
125 raise STLinkException('Could not find an ST link')
|
|
126 if len(stlink2s) > 1:
|
|
127 print('More then one stlink2 found, picking first one')
|
|
128 stlink2 = stlink2s[0]
|
|
129 self.stlink2 = stlink2
|
113
|
130 def open(self):
|
119
|
131 self.devHandle = self.stlink2.open()
|
114
|
132 if self.devHandle.Configuration != 1:
|
|
133 self.devHandle.Configuration = 1
|
|
134 self.devHandle.claimInterface(0)
|
116
|
135
|
|
136 # First initialization:
|
|
137 if self.CurrentMode == DFU_MODE:
|
|
138 self.exitDfuMode()
|
|
139 if self.CurrentMode != DEBUG_MODE:
|
|
140 self.enterSwdMode()
|
|
141 self.reset()
|
114
|
142 def close(self):
|
117
|
143 # TODO
|
114
|
144 pass
|
115
|
145
|
|
146 # modes:
|
113
|
147 def getCurrentMode(self):
|
114
|
148 cmd = bytearray(16)
|
|
149 cmd[0] = GET_CURRENT_MODE
|
|
150 reply = self.send_recv(cmd, 2) # Expect 2 bytes back
|
|
151 return reply[0]
|
113
|
152 CurrentMode = property(getCurrentMode)
|
114
|
153 @property
|
|
154 def CurrentModeString(self):
|
|
155 modes = {DFU_MODE: 'dfu', MASS_MODE: 'massmode', DEBUG_MODE:'debug'}
|
|
156 return modes[self.CurrentMode]
|
|
157 def exitDfuMode(self):
|
|
158 cmd = bytearray(16)
|
115
|
159 cmd[0:2] = DFU_COMMAND, DFU_EXIT
|
114
|
160 self.send_recv(cmd)
|
|
161 def enterSwdMode(self):
|
|
162 cmd = bytearray(16)
|
115
|
163 cmd[0:3] = DEBUG_COMMAND, DEBUG_ENTER, DEBUG_ENTER_SWD
|
114
|
164 self.send_recv(cmd)
|
|
165 def exitDebugMode(self):
|
|
166 cmd = bytearray(16)
|
115
|
167 cmd[0:2] = DEBUG_COMMAND, DEBUG_EXIT
|
114
|
168 self.send_recv(cmd)
|
|
169
|
|
170 def getVersion(self):
|
|
171 cmd = bytearray(16)
|
|
172 cmd[0] = GET_VERSION
|
|
173 data = self.send_recv(cmd, 6) # Expect 6 bytes back
|
|
174 # Parse 6 bytes into various versions:
|
|
175 b0, b1, b2, b3, b4, b5 = data
|
|
176 stlink_v = b0 >> 4
|
|
177 jtag_v = ((b0 & 0xf) << 2) | (b1 >> 6)
|
|
178 swim_v = b1 & 0x3f
|
|
179 vid = (b3 << 8) | b2
|
|
180 pid = (b5 << 8) | b4
|
|
181
|
|
182 return 'stlink={0} jtag={1} swim={2} vid:pid={3:04X}:{4:04X}'.format(\
|
|
183 stlink_v, jtag_v, swim_v, vid, pid)
|
|
184 Version = property(getVersion)
|
|
185
|
|
186 @property
|
|
187 def ChipId(self):
|
|
188 return self.read_debug32(0xE0042000)
|
|
189 @property
|
|
190 def CpuId(self):
|
|
191 u32 = self.read_debug32(CM3_REG_CPUID)
|
|
192 implementer_id = (u32 >> 24) & 0x7f
|
|
193 variant = (u32 >> 20) & 0xf
|
|
194 part = (u32 >> 4) & 0xfff
|
|
195 revision = u32 & 0xf
|
|
196 return implementer_id, variant, part, revision
|
|
197
|
117
|
198 def getStatus(self):
|
114
|
199 cmd = bytearray(16)
|
115
|
200 cmd[0:2] = DEBUG_COMMAND, DEBUG_GETSTATUS
|
114
|
201 reply = self.send_recv(cmd, 2)
|
|
202 return reply[0]
|
117
|
203 Status = property(getStatus)
|
|
204 @property
|
|
205 def StatusString(self):
|
|
206 s = self.Status
|
|
207 statii = {CORE_RUNNING: 'CORE RUNNING', CORE_HALTED: 'CORE HALTED'}
|
|
208 if s in statii:
|
|
209 return statii[s]
|
|
210
|
116
|
211 def reset(self):
|
|
212 cmd = bytearray(16)
|
|
213 cmd[0:2] = DEBUG_COMMAND, DEBUG_RESETSYS
|
|
214 self.send_recv(cmd, 2)
|
113
|
215
|
115
|
216 # debug commands:
|
114
|
217 def step(self):
|
|
218 cmd = bytearray(16)
|
115
|
219 cmd[0:2] = DEBUG_COMMAND, DEBUG_STEPCORE
|
114
|
220 self.send_recv(cmd, 2)
|
|
221 def run(self):
|
|
222 cmd = bytearray(16)
|
115
|
223 cmd[0:2] = DEBUG_COMMAND, DEBUG_RUNCORE
|
114
|
224 self.send_recv(cmd, 2)
|
115
|
225
|
|
226 # flashing commands:
|
|
227 def writeFlash(self, address, content):
|
|
228 # TODO:
|
|
229 flashsize = 0x100000 # fixed 1 MB for now..
|
|
230 print('WARNING: using 1 MB as flash size')
|
|
231 pagesize = 0x4000 # fixed for now!
|
|
232
|
|
233 # Check address range:
|
|
234 if address < STM32_FLASH_BASE:
|
|
235 raise STLinkException('Flashing below flash start')
|
|
236 if address + len(content) > STM32_FLASH_BASE + flashsize:
|
|
237 raise STLinkException('Flashing above flash size')
|
|
238 if address & 1 == 1:
|
|
239 raise STLinkException('Unaligned flash')
|
|
240 if len(content) & 1 == 1:
|
|
241 print('unaligned length, padding with zero')
|
|
242 content += bytes([0])
|
|
243 if address & (pagesize - 1) != 0:
|
|
244 raise STLinkException('Address not aligned with pagesize')
|
114
|
245
|
115
|
246 # erase required space
|
|
247 sectors = calcSectors(address, len(content))
|
|
248 print('erasing {0} sectors'.format(len(sectors)))
|
|
249 for sector, secsize in sectors:
|
119
|
250 print('erasing sector {0} of {1} bytes'.format(sector, secsize))
|
115
|
251 self.eraseFlashSector(sector)
|
|
252
|
|
253 # program pages:
|
116
|
254 self.unlockFlashIf()
|
119
|
255 self.writeFlashCrPsiz(2) # writes are 32 bits aligned
|
117
|
256 self.setFlashCrPg()
|
|
257
|
119
|
258 print('writing {0} bytes'.format(len(content)), end='')
|
117
|
259 offset = 0
|
119
|
260 t1 = time.time()
|
117
|
261 while offset < len(content):
|
|
262 size = len(content) - offset
|
|
263 if size > 0x8000:
|
|
264 size = 0x8000
|
|
265
|
119
|
266 chunk = content[offset:offset + size]
|
|
267 while len(chunk) % 4 != 0:
|
|
268 print('padding chunk')
|
|
269 chunk = chunk + bytes([0])
|
|
270
|
|
271 # Use simple mem32 writes:
|
|
272 self.write_mem32(address + offset, chunk)
|
|
273
|
117
|
274 offset += size
|
119
|
275 print('.', end='', flush=True)
|
|
276 t2 = time.time()
|
|
277 print('Done!')
|
|
278 print('Speed: {0} bytes/second'.format(len(content)/(t2-t1)))
|
115
|
279
|
116
|
280 self.lockFlash()
|
|
281
|
115
|
282 # verfify program:
|
|
283 self.verifyFlash(address, content)
|
|
284 def eraseFlashSector(self, sector):
|
|
285 self.waitFlashBusy()
|
|
286 self.unlockFlashIf()
|
|
287 self.writeFlashCrSnb(sector)
|
|
288 self.setFlashCrStart()
|
|
289 self.waitFlashBusy()
|
|
290 self.lockFlash()
|
116
|
291 def eraseFlash(self):
|
|
292 self.waitFlashBusy()
|
|
293 self.unlockFlashIf()
|
|
294 self.setFlashCrMer()
|
|
295 self.setFlashCrStart()
|
|
296 self.waitFlashBusy()
|
|
297 self.clearFlashCrMer()
|
|
298 self.lockFlash()
|
115
|
299 def verifyFlash(self, address, content):
|
116
|
300 device_content = self.readFlash(address, len(content))
|
|
301 ok = content == device_content
|
|
302 print('Verify:', ok)
|
|
303 def readFlash(self, address, size):
|
119
|
304 print('Reading {1} bytes from 0x{0:X}'.format(address, size), end='')
|
115
|
305 offset = 0
|
116
|
306 tmp_size = 0x1800
|
115
|
307 t1 = time.time()
|
116
|
308 image = bytes()
|
|
309 while offset < size:
|
115
|
310 # Correct for last page:
|
116
|
311 if offset + tmp_size > size:
|
|
312 tmp_size = size - offset
|
115
|
313
|
|
314 # align size to 4 bytes:
|
116
|
315 aligned_size = tmp_size
|
115
|
316 while aligned_size % 4 != 0:
|
|
317 aligned_size += 1
|
|
318
|
|
319 mem = self.read_mem32(address + offset, aligned_size)
|
116
|
320 image += mem[:tmp_size]
|
115
|
321
|
|
322 # indicate progress:
|
116
|
323 print('.', end='', flush=True)
|
115
|
324
|
|
325 # increase for next piece:
|
116
|
326 offset += tmp_size
|
115
|
327 t2 = time.time()
|
116
|
328 assert size == len(image)
|
119
|
329 print('Done!')
|
|
330 print('Speed: {0} bytes/second'.format(size/(t2-t1)))
|
116
|
331 return image
|
115
|
332 def readFlashSr(self):
|
|
333 return self.read_debug32(FLASH_F4_SR)
|
|
334 def readFlashCr(self):
|
|
335 return self.read_debug32(FLASH_F4_CR)
|
119
|
336 def writeFlashCr(self, x):
|
|
337 self.write_debug32(FLASH_F4_CR, x)
|
115
|
338 def writeFlashCrSnb(self, sector):
|
|
339 x = self.readFlashCr()
|
|
340 x &= ~FLASH_F4_CR_SNB_MASK
|
|
341 x |= sector << FLASH_F4_CR_SNB
|
|
342 x |= 1 << FLASH_F4_CR_SER
|
119
|
343 self.writeFlashCr(x)
|
116
|
344 def setFlashCrMer(self):
|
|
345 x = self.readFlashCr()
|
|
346 x |= 1 << FLASH_CR_MER
|
119
|
347 self.writeFlashCr(x)
|
117
|
348 def setFlashCrPg(self):
|
|
349 x = self.readFlashCr()
|
|
350 x |= 1 << FLASH_CR_PG
|
119
|
351 self.writeFlashCr(x)
|
117
|
352 def writeFlashCrPsiz(self, n):
|
|
353 x = self.readFlashCr()
|
|
354 x &= (0x3 << 8)
|
|
355 x |= n << 8
|
119
|
356 self.writeFlashCr(x)
|
116
|
357 def clearFlashCrMer(self):
|
|
358 x = self.readFlashCr()
|
|
359 x &= ~(1 << FLASH_CR_MER)
|
119
|
360 self.writeFlashCr(x)
|
115
|
361 def setFlashCrStart(self):
|
|
362 x = self.readFlashCr()
|
|
363 x |= 1 << FLASH_F4_CR_START
|
119
|
364 self.writeFlashCr(x)
|
115
|
365 def isFlashBusy(self):
|
|
366 mask = 1 << FLASH_F4_SR_BSY
|
|
367 sr = self.readFlashSr()
|
119
|
368 # Check for error bits:
|
|
369 errorbits = {}
|
|
370 errorbits[7] = 'Programming sequence error'
|
|
371 errorbits[6] = 'Programming parallelism error'
|
|
372 errorbits[5] = 'Programming alignment error'
|
|
373 errorbits[4] = 'Write protection error'
|
|
374 errorbits[1] = 'Operation error'
|
|
375 #errorbits[0] = 'End of operation'
|
|
376 for bit, msg in errorbits.items():
|
|
377 if sr & (1 << bit) == (1 << bit):
|
|
378 raise STLinkException(msg)
|
|
379
|
115
|
380 return sr & mask == mask
|
|
381 def waitFlashBusy(self):
|
|
382 """ block until flash operation completes. """
|
|
383 while self.isFlashBusy():
|
|
384 pass
|
|
385 def isFlashLocked(self):
|
|
386 cr = self.readFlashCr()
|
|
387 mask = 1 << FLASH_F4_CR_LOCK
|
|
388 return cr & mask == mask
|
|
389 def unlockFlashIf(self):
|
|
390 if self.isFlashLocked():
|
|
391 self.write_debug32(FLASH_F4_KEYR, FLASH_KEY1)
|
|
392 self.write_debug32(FLASH_F4_KEYR, FLASH_KEY2)
|
|
393 if self.isFlashLocked():
|
|
394 raise STLinkException('Failed to unlock')
|
|
395 def lockFlash(self):
|
116
|
396 x = self.readFlashCr() | (1 << FLASH_F4_CR_LOCK)
|
|
397 self.write_debug32(FLASH_F4_CR, x)
|
115
|
398
|
114
|
399 # Helper 1 functions:
|
115
|
400 def write_debug32(self, address, value):
|
|
401 cmd = bytearray(16)
|
|
402 cmd[0:2] = DEBUG_COMMAND, JTAG_WRITEDEBUG_32BIT
|
119
|
403 cmd[2:10] = struct.pack('<II', address, value)
|
115
|
404 self.send_recv(cmd, 2)
|
114
|
405 def read_debug32(self, address):
|
|
406 cmd = bytearray(16)
|
115
|
407 cmd[0:2] = DEBUG_COMMAND, JTAG_READDEBUG_32BIT
|
114
|
408 cmd[2:6] = struct.pack('<I', address) # pack into u32 little endian
|
|
409 reply = self.send_recv(cmd, 8)
|
|
410 return struct.unpack('<I', reply[4:8])[0]
|
115
|
411 def write_reg(self, reg, value):
|
|
412 cmd = bytearray(16)
|
|
413 cmd[0:3] = DEBUG_COMMAND, DEBUG_WRITEREG, reg
|
|
414 cmd[3:7] = struct.pack('<I', value)
|
|
415 r = self.send_recv(cmd, 2)
|
|
416 def read_reg(self, reg):
|
|
417 cmd = bytearray(16)
|
|
418 cmd[0:3] = DEBUG_COMMAND, DEBUG_READREG, reg
|
|
419 reply = self.send_recv(cmd, 4)
|
|
420 return struct.unpack('<I', reply)[0]
|
116
|
421 def write_mem32(self, address, content):
|
|
422 assert len(content) % 4 == 0
|
|
423 cmd = bytearray(16)
|
|
424 cmd[0:2] = DEBUG_COMMAND, DEBUG_WRITEMEM_32BIT
|
119
|
425 cmd[2:8] = struct.pack('<IH', address, len(content))
|
116
|
426 self.send_recv(cmd)
|
|
427 self.send_recv(content)
|
115
|
428 def read_mem32(self, address, length):
|
|
429 assert length % 4 == 0
|
|
430 cmd = bytearray(16)
|
|
431 cmd[0:2] = DEBUG_COMMAND, DEBUG_READMEM_32BIT
|
119
|
432 cmd[2:8] = struct.pack('<IH', address, length)
|
115
|
433 reply = self.send_recv(cmd, length) # expect memory back!
|
|
434 return reply
|
114
|
435
|
|
436 # Helper 2 functions:
|
|
437 def send_recv(self, tx, rxsize=0):
|
115
|
438 """ Helper function that transmits and receives data in bulk mode. """
|
114
|
439 # TODO: we could use here the non-blocking libusb api.
|
|
440 tx = bytes(tx)
|
116
|
441 #assert len(tx) == 16
|
114
|
442 self.devHandle.bulkWrite(2, tx) # write to endpoint 2
|
|
443 if rxsize > 0:
|
|
444 return self.devHandle.bulkRead(1, rxsize) # read from endpoint 1
|
|
445
|
|
446 knownChipIds = {0x1: 'x'}
|
|
447
|
|
448 if __name__ == '__main__':
|
|
449 # Test program
|
|
450 sl = STLink()
|
|
451 sl.open()
|
|
452 print('version:', sl.Version)
|
|
453 print('mode before doing anything:', sl.CurrentModeString)
|
|
454 if sl.CurrentMode == DFU_MODE:
|
|
455 sl.exitDfuMode()
|
|
456 sl.enterSwdMode()
|
|
457 print('mode after entering swd mode:', sl.CurrentModeString)
|
|
458
|
|
459 i = sl.ChipId
|
|
460 if i in knownChipIds:
|
|
461 print('chip id: 0x{0:X} -> {1}'.format(i, knownChipIds[i]))
|
|
462 else:
|
|
463 print('chip id: 0x{0:X}'.format(i))
|
|
464 print('cpu: {0}'.format(sl.CpuId))
|
|
465
|
117
|
466 print('status: {0}'.format(sl.StatusString))
|
114
|
467
|
115
|
468 #time.sleep(2.2)
|
|
469
|
|
470 # test registers:
|
|
471 sl.write_reg(3, 0x1337)
|
116
|
472 sl.write_reg(2, 0x1332)
|
117
|
473 sl.write_reg(6, 0x12345)
|
115
|
474 assert sl.read_reg(3) == 0x1337
|
116
|
475 assert sl.read_reg(2) == 0x1332
|
117
|
476 assert sl.read_reg(6) == 0x12345
|
114
|
477
|
|
478 sl.exitDebugMode()
|
|
479 print('mode at end:', sl.CurrentModeString)
|
|
480
|
|
481 sl.close()
|
119
|
482 print('Test succes!')
|
114
|
483
|