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:
|
113
|
119 def __init__(self):
|
|
120 self.context = UsbContext()
|
|
121 def open(self):
|
|
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]
|
114
|
129 self.devHandle = stlink2.open()
|
|
130 if self.devHandle.Configuration != 1:
|
|
131 self.devHandle.Configuration = 1
|
|
132 self.devHandle.claimInterface(0)
|
116
|
133
|
|
134 # First initialization:
|
|
135 if self.CurrentMode == DFU_MODE:
|
|
136 self.exitDfuMode()
|
|
137 if self.CurrentMode != DEBUG_MODE:
|
|
138 self.enterSwdMode()
|
|
139 self.reset()
|
114
|
140 def close(self):
|
117
|
141 # TODO
|
114
|
142 pass
|
115
|
143
|
|
144 # modes:
|
113
|
145 def getCurrentMode(self):
|
114
|
146 cmd = bytearray(16)
|
|
147 cmd[0] = GET_CURRENT_MODE
|
|
148 reply = self.send_recv(cmd, 2) # Expect 2 bytes back
|
|
149 return reply[0]
|
113
|
150 CurrentMode = property(getCurrentMode)
|
114
|
151 @property
|
|
152 def CurrentModeString(self):
|
|
153 modes = {DFU_MODE: 'dfu', MASS_MODE: 'massmode', DEBUG_MODE:'debug'}
|
|
154 return modes[self.CurrentMode]
|
|
155 def exitDfuMode(self):
|
|
156 cmd = bytearray(16)
|
115
|
157 cmd[0:2] = DFU_COMMAND, DFU_EXIT
|
114
|
158 self.send_recv(cmd)
|
|
159 def enterSwdMode(self):
|
|
160 cmd = bytearray(16)
|
115
|
161 cmd[0:3] = DEBUG_COMMAND, DEBUG_ENTER, DEBUG_ENTER_SWD
|
114
|
162 self.send_recv(cmd)
|
|
163 def exitDebugMode(self):
|
|
164 cmd = bytearray(16)
|
115
|
165 cmd[0:2] = DEBUG_COMMAND, DEBUG_EXIT
|
114
|
166 self.send_recv(cmd)
|
|
167
|
|
168 def getVersion(self):
|
|
169 cmd = bytearray(16)
|
|
170 cmd[0] = GET_VERSION
|
|
171 data = self.send_recv(cmd, 6) # Expect 6 bytes back
|
|
172 # Parse 6 bytes into various versions:
|
|
173 b0, b1, b2, b3, b4, b5 = data
|
|
174 stlink_v = b0 >> 4
|
|
175 jtag_v = ((b0 & 0xf) << 2) | (b1 >> 6)
|
|
176 swim_v = b1 & 0x3f
|
|
177 vid = (b3 << 8) | b2
|
|
178 pid = (b5 << 8) | b4
|
|
179
|
|
180 return 'stlink={0} jtag={1} swim={2} vid:pid={3:04X}:{4:04X}'.format(\
|
|
181 stlink_v, jtag_v, swim_v, vid, pid)
|
|
182 Version = property(getVersion)
|
|
183
|
|
184 @property
|
|
185 def ChipId(self):
|
|
186 return self.read_debug32(0xE0042000)
|
|
187 @property
|
|
188 def CpuId(self):
|
|
189 u32 = self.read_debug32(CM3_REG_CPUID)
|
|
190 implementer_id = (u32 >> 24) & 0x7f
|
|
191 variant = (u32 >> 20) & 0xf
|
|
192 part = (u32 >> 4) & 0xfff
|
|
193 revision = u32 & 0xf
|
|
194 return implementer_id, variant, part, revision
|
|
195
|
117
|
196 def getStatus(self):
|
114
|
197 cmd = bytearray(16)
|
115
|
198 cmd[0:2] = DEBUG_COMMAND, DEBUG_GETSTATUS
|
114
|
199 reply = self.send_recv(cmd, 2)
|
|
200 return reply[0]
|
117
|
201 Status = property(getStatus)
|
|
202 @property
|
|
203 def StatusString(self):
|
|
204 s = self.Status
|
|
205 statii = {CORE_RUNNING: 'CORE RUNNING', CORE_HALTED: 'CORE HALTED'}
|
|
206 if s in statii:
|
|
207 return statii[s]
|
|
208
|
116
|
209 def reset(self):
|
|
210 cmd = bytearray(16)
|
|
211 cmd[0:2] = DEBUG_COMMAND, DEBUG_RESETSYS
|
|
212 self.send_recv(cmd, 2)
|
113
|
213
|
115
|
214 # debug commands:
|
114
|
215 def step(self):
|
|
216 cmd = bytearray(16)
|
115
|
217 cmd[0:2] = DEBUG_COMMAND, DEBUG_STEPCORE
|
114
|
218 self.send_recv(cmd, 2)
|
|
219 def run(self):
|
|
220 cmd = bytearray(16)
|
115
|
221 cmd[0:2] = DEBUG_COMMAND, DEBUG_RUNCORE
|
114
|
222 self.send_recv(cmd, 2)
|
115
|
223
|
|
224 # flashing commands:
|
|
225 def writeFlash(self, address, content):
|
|
226 # TODO:
|
|
227 flashsize = 0x100000 # fixed 1 MB for now..
|
|
228 print('WARNING: using 1 MB as flash size')
|
|
229 pagesize = 0x4000 # fixed for now!
|
|
230
|
|
231 # Check address range:
|
|
232 if address < STM32_FLASH_BASE:
|
|
233 raise STLinkException('Flashing below flash start')
|
|
234 if address + len(content) > STM32_FLASH_BASE + flashsize:
|
|
235 raise STLinkException('Flashing above flash size')
|
|
236 if address & 1 == 1:
|
|
237 raise STLinkException('Unaligned flash')
|
|
238 if len(content) & 1 == 1:
|
|
239 print('unaligned length, padding with zero')
|
|
240 content += bytes([0])
|
|
241 if address & (pagesize - 1) != 0:
|
|
242 raise STLinkException('Address not aligned with pagesize')
|
114
|
243
|
115
|
244 # erase required space
|
|
245 sectors = calcSectors(address, len(content))
|
|
246 print('erasing {0} sectors'.format(len(sectors)))
|
|
247 for sector, secsize in sectors:
|
|
248 print('erasing sector {0} of size {1}'.format(sector, secsize))
|
|
249 self.eraseFlashSector(sector)
|
|
250
|
|
251 # program pages:
|
116
|
252 self.initFlashLoader()
|
|
253 self.unlockFlashIf()
|
117
|
254 self.writeFlashCrPsiz(2)
|
|
255 self.setFlashCrPg()
|
|
256
|
|
257 offset = 0
|
|
258 while offset < len(content):
|
|
259 size = len(content) - offset
|
|
260 if size > 0x8000:
|
|
261 size = 0x8000
|
|
262
|
|
263 self.runFlashLoader(address + offset, content[offset:offset + size])
|
|
264 offset += size
|
115
|
265
|
116
|
266 self.lockFlash()
|
|
267
|
115
|
268 # verfify program:
|
|
269 self.verifyFlash(address, content)
|
|
270 def eraseFlashSector(self, sector):
|
|
271 self.waitFlashBusy()
|
|
272 self.unlockFlashIf()
|
|
273 self.writeFlashCrSnb(sector)
|
|
274 self.setFlashCrStart()
|
|
275 self.waitFlashBusy()
|
|
276 self.lockFlash()
|
116
|
277 def eraseFlash(self):
|
|
278 self.waitFlashBusy()
|
|
279 self.unlockFlashIf()
|
|
280 self.setFlashCrMer()
|
|
281 self.setFlashCrStart()
|
|
282 self.waitFlashBusy()
|
|
283 self.clearFlashCrMer()
|
|
284 self.lockFlash()
|
115
|
285 def verifyFlash(self, address, content):
|
116
|
286 device_content = self.readFlash(address, len(content))
|
|
287 ok = content == device_content
|
|
288 print('Verify:', ok)
|
|
289 def readFlash(self, address, size):
|
|
290 print('reading', address, size)
|
115
|
291 offset = 0
|
116
|
292 tmp_size = 0x1800
|
115
|
293 t1 = time.time()
|
116
|
294 image = bytes()
|
|
295 while offset < size:
|
115
|
296 # Correct for last page:
|
116
|
297 if offset + tmp_size > size:
|
|
298 tmp_size = size - offset
|
115
|
299
|
|
300 # align size to 4 bytes:
|
116
|
301 aligned_size = tmp_size
|
115
|
302 while aligned_size % 4 != 0:
|
|
303 aligned_size += 1
|
|
304
|
|
305 mem = self.read_mem32(address + offset, aligned_size)
|
116
|
306 image += mem[:tmp_size]
|
115
|
307
|
|
308 # indicate progress:
|
116
|
309 print('.', end='', flush=True)
|
115
|
310
|
|
311 # increase for next piece:
|
116
|
312 offset += tmp_size
|
115
|
313 t2 = time.time()
|
116
|
314 assert size == len(image)
|
|
315 print('done! {0} bytes/second'.format(size/(t2-t1)))
|
|
316 return image
|
|
317 def initFlashLoader(self):
|
|
318 # TODO: support other loader code.
|
|
319 self.write_mem32(STM32_SRAM_BASE, loader_code_stm32f4)
|
117
|
320 def runFlashLoader(self, targetaddress, buf):
|
|
321 bufAddress = STM32_SRAM_BASE + len(loader_code_stm32f4)
|
|
322 print('running flash loader for {0} bytes'.format(len(buf)))
|
|
323 self.write_buffer_to_sram(buf)
|
|
324 count = int(len(buf) / 4)
|
|
325 if len(buf) % 4 != 0: count += 1
|
|
326 self.write_reg(0, bufAddress)
|
|
327 self.write_reg(1, targetaddress)
|
|
328 self.write_reg(2, count)
|
|
329 self.write_reg(15, STM32_SRAM_BASE) # pc
|
|
330
|
|
331 self.run() # Let loose cpu!
|
|
332
|
|
333 while self.Status == CORE_RUNNING:
|
|
334 pass
|
|
335
|
|
336 r2 = self.read_reg(2)
|
|
337 if r2 != 0:
|
|
338 raise STLinkException("write error! {0}".format(r2))
|
|
339 def write_buffer_to_sram(self, buf):
|
|
340 bufAddress = STM32_SRAM_BASE + len(loader_code_stm32f4)
|
|
341 chunk = len(buf) >> 2
|
|
342 rem = len(buf) & 0x3
|
|
343 if chunk > 0:
|
|
344 self.write_mem32(bufAddress, buf[:chunk])
|
|
345 if rem > 0:
|
|
346 self.write_mem8(bufAddress + chunk, buf[chunk:chunk+rem])
|
|
347
|
115
|
348 def readFlashSr(self):
|
|
349 return self.read_debug32(FLASH_F4_SR)
|
|
350 def readFlashCr(self):
|
|
351 return self.read_debug32(FLASH_F4_CR)
|
|
352 def writeFlashCrSnb(self, sector):
|
|
353 x = self.readFlashCr()
|
|
354 x &= ~FLASH_F4_CR_SNB_MASK
|
|
355 x |= sector << FLASH_F4_CR_SNB
|
|
356 x |= 1 << FLASH_F4_CR_SER
|
|
357 self.write_debug32(FLASH_F4_CR, x)
|
116
|
358 def setFlashCrMer(self):
|
|
359 x = self.readFlashCr()
|
|
360 x |= 1 << FLASH_CR_MER
|
|
361 self.write_debug32(FLASH_F4_CR, x)
|
117
|
362 def setFlashCrPg(self):
|
|
363 x = self.readFlashCr()
|
|
364 x |= 1 << FLASH_CR_PG
|
|
365 self.write_debug32(FLASH_F4_CR, x)
|
|
366 def writeFlashCrPsiz(self, n):
|
|
367 x = self.readFlashCr()
|
|
368 x &= (0x3 << 8)
|
|
369 x |= n << 8
|
|
370 print('psiz', n)
|
|
371 self.write_debug32(FLASH_F4_CR, x)
|
116
|
372 def clearFlashCrMer(self):
|
|
373 x = self.readFlashCr()
|
|
374 x &= ~(1 << FLASH_CR_MER)
|
|
375 self.write_debug32(FLASH_F4_CR, x)
|
115
|
376 def setFlashCrStart(self):
|
|
377 x = self.readFlashCr()
|
|
378 x |= 1 << FLASH_F4_CR_START
|
|
379 self.write_debug32(FLASH_F4_CR, x)
|
|
380 def isFlashBusy(self):
|
|
381 mask = 1 << FLASH_F4_SR_BSY
|
|
382 sr = self.readFlashSr()
|
|
383 return sr & mask == mask
|
|
384 def waitFlashBusy(self):
|
|
385 """ block until flash operation completes. """
|
|
386 while self.isFlashBusy():
|
|
387 pass
|
|
388 def isFlashLocked(self):
|
|
389 cr = self.readFlashCr()
|
|
390 mask = 1 << FLASH_F4_CR_LOCK
|
|
391 return cr & mask == mask
|
|
392 def unlockFlashIf(self):
|
|
393 if self.isFlashLocked():
|
116
|
394 print('unlocking')
|
115
|
395 self.write_debug32(FLASH_F4_KEYR, FLASH_KEY1)
|
|
396 self.write_debug32(FLASH_F4_KEYR, FLASH_KEY2)
|
|
397 if self.isFlashLocked():
|
|
398 raise STLinkException('Failed to unlock')
|
|
399 def lockFlash(self):
|
116
|
400 print('locking')
|
|
401 x = self.readFlashCr() | (1 << FLASH_F4_CR_LOCK)
|
|
402 self.write_debug32(FLASH_F4_CR, x)
|
115
|
403
|
114
|
404 # Helper 1 functions:
|
115
|
405 def write_debug32(self, address, value):
|
|
406 cmd = bytearray(16)
|
|
407 cmd[0:2] = DEBUG_COMMAND, JTAG_WRITEDEBUG_32BIT
|
|
408 cmd[2:6] = struct.pack('<I', address)
|
|
409 cmd[6:10] = struct.pack('<I', value)
|
|
410 self.send_recv(cmd, 2)
|
114
|
411 def read_debug32(self, address):
|
|
412 cmd = bytearray(16)
|
115
|
413 cmd[0:2] = DEBUG_COMMAND, JTAG_READDEBUG_32BIT
|
114
|
414 cmd[2:6] = struct.pack('<I', address) # pack into u32 little endian
|
|
415 reply = self.send_recv(cmd, 8)
|
|
416 return struct.unpack('<I', reply[4:8])[0]
|
115
|
417 def write_reg(self, reg, value):
|
|
418 cmd = bytearray(16)
|
|
419 cmd[0:3] = DEBUG_COMMAND, DEBUG_WRITEREG, reg
|
|
420 cmd[3:7] = struct.pack('<I', value)
|
|
421 r = self.send_recv(cmd, 2)
|
|
422 def read_reg(self, reg):
|
|
423 cmd = bytearray(16)
|
|
424 cmd[0:3] = DEBUG_COMMAND, DEBUG_READREG, reg
|
|
425 reply = self.send_recv(cmd, 4)
|
|
426 return struct.unpack('<I', reply)[0]
|
116
|
427 def write_mem32(self, address, content):
|
|
428 assert len(content) % 4 == 0
|
|
429 cmd = bytearray(16)
|
|
430 cmd[0:2] = DEBUG_COMMAND, DEBUG_WRITEMEM_32BIT
|
|
431 cmd[2:6] = struct.pack('<I', address)
|
|
432 cmd[6:8] = struct.pack('<H', len(content))
|
|
433 self.send_recv(cmd)
|
|
434 self.send_recv(content)
|
115
|
435 def read_mem32(self, address, length):
|
|
436 assert length % 4 == 0
|
|
437 cmd = bytearray(16)
|
|
438 cmd[0:2] = DEBUG_COMMAND, DEBUG_READMEM_32BIT
|
|
439 cmd[2:6] = struct.pack('<I', address)
|
|
440 cmd[6:8] = struct.pack('<H', length) # uint16
|
|
441 reply = self.send_recv(cmd, length) # expect memory back!
|
|
442 return reply
|
114
|
443
|
|
444 # Helper 2 functions:
|
|
445 def send_recv(self, tx, rxsize=0):
|
115
|
446 """ Helper function that transmits and receives data in bulk mode. """
|
114
|
447 # TODO: we could use here the non-blocking libusb api.
|
|
448 tx = bytes(tx)
|
116
|
449 #assert len(tx) == 16
|
114
|
450 self.devHandle.bulkWrite(2, tx) # write to endpoint 2
|
|
451 if rxsize > 0:
|
|
452 return self.devHandle.bulkRead(1, rxsize) # read from endpoint 1
|
|
453
|
|
454 knownChipIds = {0x1: 'x'}
|
|
455
|
|
456 if __name__ == '__main__':
|
|
457 # Test program
|
|
458 sl = STLink()
|
|
459 sl.open()
|
|
460 print('version:', sl.Version)
|
|
461 print('mode before doing anything:', sl.CurrentModeString)
|
|
462 if sl.CurrentMode == DFU_MODE:
|
|
463 sl.exitDfuMode()
|
|
464 sl.enterSwdMode()
|
|
465 print('mode after entering swd mode:', sl.CurrentModeString)
|
|
466
|
|
467 i = sl.ChipId
|
|
468 if i in knownChipIds:
|
|
469 print('chip id: 0x{0:X} -> {1}'.format(i, knownChipIds[i]))
|
|
470 else:
|
|
471 print('chip id: 0x{0:X}'.format(i))
|
|
472 print('cpu: {0}'.format(sl.CpuId))
|
|
473
|
117
|
474 print('status: {0}'.format(sl.StatusString))
|
114
|
475
|
115
|
476 #time.sleep(2.2)
|
|
477
|
|
478 # test registers:
|
|
479 sl.write_reg(3, 0x1337)
|
116
|
480 sl.write_reg(2, 0x1332)
|
117
|
481 sl.write_reg(6, 0x12345)
|
115
|
482 assert sl.read_reg(3) == 0x1337
|
116
|
483 assert sl.read_reg(2) == 0x1332
|
117
|
484 assert sl.read_reg(6) == 0x12345
|
114
|
485
|
|
486 sl.exitDebugMode()
|
|
487 print('mode at end:', sl.CurrentModeString)
|
|
488
|
|
489 sl.close()
|
|
490
|