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