2 Copyright (c) 2010 "Capt'ns Missing Link" Authors. All rights reserved.
3 Use of this source code is governed by a BSD-style
4 license that can be found in the LICENSE file.
6 A linux stlink access demo. The purpose of this file is to mitigate the usual
7 "reinventing the wheel" force by incompatible licenses and give you an idea,
8 how to access the stlink device. That doesn't mean you should be a free-loader
9 and not contribute your improvements to this code.
11 Author: Martin Capitanio <m@capitanio.org>
12 The stlink related constants kindly provided by Oliver Spencer (OpenOCD)
13 for use in a GPL compatible license.
15 Code format ~ TAB = 8, K&R, linux kernel source, golang oriented
16 Tested compatibility: linux, gcc >= 4.3.3
18 The communication is based on standard USB mass storage device
19 BOT (Bulk Only Transfer)
20 - Endpoint 1: BULK_IN, 64 bytes max
21 - Endpoint 2: BULK_OUT, 64 bytes max
23 All CBW transfers are ordered with the LSB (byte 0) first (little endian).
24 Any command must be answered before sending the next command.
25 Each USB transfer must complete in less than 1s.
27 SB Device Class Definition for Mass Storage Devices:
28 www.usb.org/developers/devclass_docs/usbmassbulk_10.pdf
30 dt - Data Transfer (IN/OUT)
31 CBW - Command Block Wrapper
32 CSW - Command Status Wrapper
33 RFU - Reserved for Future Use
34 scsi_pt - SCSI pass-through
38 http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blob_plain;f=Documentation/kernel-parameters.txt
39 Each entry has the form VID:PID:Flags where VID and PID are Vendor and Product
40 ID values (4-digit hex numbers) and Flags is a set of characters, each corresponding
41 to a common usb-storage quirk flag as follows:
43 a = SANE_SENSE (collect more than 18 bytes of sense data);
44 b = BAD_SENSE (don't collect more than 18 bytes of sense data);
45 c = FIX_CAPACITY (decrease the reported device capacity by one sector);
46 h = CAPACITY_HEURISTICS (decrease the reported device capacity by one sector if the number is odd);
47 i = IGNORE_DEVICE (don't bind to this device);
48 l = NOT_LOCKABLE (don't try to lock and unlock ejectable media);
49 m = MAX_SECTORS_64 (don't transfer more than 64 sectors = 32 KB at a time);
50 o = CAPACITY_OK (accept the capacity reported by the device);
51 r = IGNORE_RESIDUE (the device reports bogus residue values);
52 s = SINGLE_LUN (the device has only one Logical Unit);
53 w = NO_WP_DETECT (don't test whether the medium is write-protected).
55 Example: quirks=0419:aaf5:rl,0421:0433:rc
56 http://permalink.gmane.org/gmane.linux.usb.general/35053
58 modprobe -r usb-storage && modprobe usb-storage quirks=483:3744:l
60 Equivalently, you can add a line saying
62 options usb-storage quirks=483:3744:l
64 to your /etc/modprobe.conf or /etc/modprobe.d/local.conf (or add the "quirks=..."
65 part to an existing options line for usb-storage).
75 #include <sys/types.h>
79 // sgutils2 (apt-get install libsgutils2-dev)
80 #include <scsi/sg_lib.h>
81 #include <scsi/sg_pt.h>
83 #include "stlink-hw.h"
85 static void D(struct stlink *sl, char *txt) {
90 static void DD(struct stlink *sl, char *format, ...) {
91 if (sl->verbose > 0) {
93 va_start(list, format);
94 vfprintf(stderr, format, list);
99 // Suspends execution of the calling process for
100 // (at least) ms milliseconds.
101 static void delay(int ms) {
102 //fprintf(stderr, "*** wait %d ms\n", ms);
107 // http://www.ibm.com/developerworks/aix/library/au-endianc/index.html
109 // #define is_bigendian() ( (*(char*)&i) == 0 )
110 static inline unsigned int is_bigendian(void) {
111 static volatile const unsigned int i = 1;
112 return *(volatile const char*) &i == 0;
115 static void write_uint32(unsigned char* buf, uint32_t ui) {
116 if (!is_bigendian()) { // le -> le (don't swap)
117 buf[0] = ((unsigned char*) &ui)[0];
118 buf[1] = ((unsigned char*) &ui)[1];
119 buf[2] = ((unsigned char*) &ui)[2];
120 buf[3] = ((unsigned char*) &ui)[3];
122 buf[0] = ((unsigned char*) &ui)[3];
123 buf[1] = ((unsigned char*) &ui)[2];
124 buf[2] = ((unsigned char*) &ui)[1];
125 buf[3] = ((unsigned char*) &ui)[0];
129 static void write_uint16(unsigned char* buf, uint16_t ui) {
130 if (!is_bigendian()) { // le -> le (don't swap)
131 buf[0] = ((unsigned char*) &ui)[0];
132 buf[1] = ((unsigned char*) &ui)[1];
134 buf[0] = ((unsigned char*) &ui)[1];
135 buf[1] = ((unsigned char*) &ui)[0];
139 static uint32_t read_uint32(const unsigned char *c, const int pt) {
141 char *p = (char *) &ui;
143 if (!is_bigendian()) { // le -> le (don't swap)
157 static uint16_t read_uint16(const unsigned char *c, const int pt) {
159 char *p = (char *) &ui;
161 if (!is_bigendian()) { // le -> le (don't swap)
171 static void clear_cdb(struct stlink *sl) {
172 for (int i = 0; i < sizeof(sl->cdb_cmd_blk); i++)
173 sl->cdb_cmd_blk[i] = 0;
175 sl->cdb_cmd_blk[0] = STLINK_DEBUG_COMMAND;
176 sl->q_data_dir = Q_DATA_IN;
179 // E.g. make the valgrind happy.
180 static void clear_buf(struct stlink *sl) {
181 DD(sl, "*** clear_buf ***\n");
182 for (int i = 0; i < sizeof(sl->q_buf); i++)
187 static struct stlink* stlink_open(const char *dev_name, const int verbose) {
188 fprintf(stderr, "\n*** stlink_open [%s] ***\n", dev_name);
189 int sg_fd = scsi_pt_open_device(dev_name, RDWR, verbose);
191 fprintf(stderr, "error opening device: %s: %s\n", dev_name,
192 safe_strerror(-sg_fd));
196 struct stlink *sl = malloc(sizeof(struct stlink));
198 fprintf(stderr, "struct stlink: out of memory\n");
203 sl->verbose = verbose;
204 sl->core_stat = STLINK_CORE_STAT_UNKNOWN;
209 /* flash memory settings */
210 sl->flash_base = STM32_FLASH_BASE;
211 sl->flash_size = STM32_FLASH_SIZE;
212 sl->flash_pgsz = STM32_FLASH_PGSZ;
215 sl->sys_base = STM32_SYSTEM_BASE;
216 sl->sys_size = STM32_SYSTEM_SIZE;
218 /* sram memory settings */
219 sl->sram_base = STM32_SRAM_BASE;
220 sl->sram_size = STM32_SRAM_SIZE;
225 // close the device, free the allocated memory
226 void stlink_close(struct stlink *sl) {
227 D(sl, "\n*** stlink_close ***\n");
229 scsi_pt_close_device(sl->sg_fd);
234 //TODO rewrite/cleanup, save the error in sl
235 static void stlink_confirm_inq(struct stlink *sl, struct sg_pt_base *ptvp) {
236 const int e = sl->do_scsi_pt_err;
238 fprintf(stderr, "scsi_pt error: pass through os error: %s\n",
241 } else if (e == SCSI_PT_DO_BAD_PARAMS) {
242 fprintf(stderr, "scsi_pt error: bad pass through setup\n");
244 } else if (e == SCSI_PT_DO_TIMEOUT) {
245 fprintf(stderr, " pass through timeout\n");
248 const int duration = get_scsi_pt_duration_ms(ptvp);
249 if ((sl->verbose > 1) && (duration >= 0))
250 DD(sl, " duration=%d ms\n", duration);
252 // XXX stlink fw sends broken residue, so ignore it and use the known q_len
253 // "usb-storage quirks=483:3744:r"
254 // forces residue to be ignored and calculated, but this causes aboard if
255 // data_len = 0 and by some other data_len values.
257 const int resid = get_scsi_pt_resid(ptvp);
258 const int dsize = sl->q_len - resid;
260 const int cat = get_scsi_pt_result_category(ptvp);
265 case SCSI_PT_RESULT_GOOD:
266 if (sl->verbose && (resid > 0))
267 DD(sl, " notice: requested %d bytes but "
268 "got %d bytes, ignore [broken] residue = %d\n",
269 sl->q_len, dsize, resid);
271 case SCSI_PT_RESULT_STATUS:
273 sg_get_scsi_status_str(
274 get_scsi_pt_status_response(ptvp), sizeof(buf),
276 DD(sl, " scsi status: %s\n", buf);
279 case SCSI_PT_RESULT_SENSE:
280 slen = get_scsi_pt_sense_len(ptvp);
282 sg_get_sense_str("", sl->sense_buf, slen, (sl->verbose
283 > 1), sizeof(buf), buf);
286 if (sl->verbose && (resid > 0)) {
287 if ((sl->verbose) || (sl->q_len > 0))
288 DD(sl, " requested %d bytes but "
289 "got %d bytes\n", sl->q_len, dsize);
292 case SCSI_PT_RESULT_TRANSPORT_ERR:
294 get_scsi_pt_transport_err_str(ptvp, sizeof(buf), buf);
295 // http://tldp.org/HOWTO/SCSI-Generic-HOWTO/x291.html
296 // These codes potentially come from the firmware on a host adapter
297 // or from one of several hosts that an adapter driver controls.
298 // The 'host_status' field has the following values:
299 // [0x07] Internal error detected in the host adapter.
300 // This may not be fatal (and the command may have succeeded).
301 DD(sl, " transport: %s", buf);
304 case SCSI_PT_RESULT_OS_ERR:
306 get_scsi_pt_os_err_str(ptvp, sizeof(buf), buf);
307 DD(sl, " os: %s", buf);
311 fprintf(stderr, " unknown pass through result "
312 "category (%d)\n", cat);
316 static void stlink_q(struct stlink* sl) {
318 for (int i = 0; i < CDB_SL; i++)
319 DD(sl, " 0x%02x", (unsigned int) sl->cdb_cmd_blk[i]);
322 // Get control command descriptor of scsi structure,
323 // (one object per command!!)
324 struct sg_pt_base *ptvp = construct_scsi_pt_obj();
326 fprintf(stderr, "construct_scsi_pt_obj: out of memory\n");
330 set_scsi_pt_cdb(ptvp, sl->cdb_cmd_blk, sizeof(sl->cdb_cmd_blk));
332 // set buffer for sense (error information) data
333 set_scsi_pt_sense(ptvp, sl->sense_buf, sizeof(sl->sense_buf));
335 // Set a buffer to be used for data transferred from device
336 if (sl->q_data_dir == Q_DATA_IN) {
338 set_scsi_pt_data_in(ptvp, sl->q_buf, sl->q_len);
340 set_scsi_pt_data_out(ptvp, sl->q_buf, sl->q_len);
342 // Executes SCSI command (or at least forwards it to lower layers).
343 sl->do_scsi_pt_err = do_scsi_pt(ptvp, sl->sg_fd, SG_TIMEOUT_SEC,
346 // check for scsi errors
347 stlink_confirm_inq(sl, ptvp);
348 // TODO recycle: clear_scsi_pt_obj(struct sg_pt_base * objp);
349 destruct_scsi_pt_obj(ptvp);
352 static void stlink_print_data(struct stlink *sl) {
353 if (sl->q_len <= 0 || sl->verbose < 2)
356 fprintf(stdout, "data_len = %d 0x%x\n", sl->q_len, sl->q_len);
358 for (uint32_t i = 0; i < sl->q_len; i++) {
360 if (sl->q_data_dir == Q_DATA_OUT)
361 fprintf(stdout, "\n<- 0x%08x ", sl->q_addr + i);
363 fprintf(stdout, "\n-> 0x%08x ", sl->q_addr + i);
365 fprintf(stdout, " %02x", (unsigned int) sl->q_buf[i]);
367 fputs("\n\n", stdout);
370 // TODO thinking, cleanup
371 static void stlink_parse_version(struct stlink *sl) {
374 if (sl->q_len <= 0) {
375 fprintf(stderr, "Error: could not parse the stlink version");
378 stlink_print_data(sl);
379 uint32_t b0 = sl->q_buf[0]; //lsb
380 uint32_t b1 = sl->q_buf[1];
381 uint32_t b2 = sl->q_buf[2];
382 uint32_t b3 = sl->q_buf[3];
383 uint32_t b4 = sl->q_buf[4];
384 uint32_t b5 = sl->q_buf[5]; //msb
386 // b0 b1 || b2 b3 | b4 b5
387 // 4b | 6b | 6b || 2B | 2B
388 // stlink_v | jtag_v | swim_v || st_vid | stlink_pid
390 sl->stlink_v = (b0 & 0xf0) >> 4;
391 sl->jtag_v = ((b0 & 0x0f) << 2) | ((b1 & 0xc0) >> 6);
392 sl->swim_v = b1 & 0x3f;
393 sl->st_vid = (b3 << 8) | b2;
394 sl->stlink_pid = (b5 << 8) | b4;
399 DD(sl, "st vid = 0x%04x (expect 0x%04x)\n",
400 sl->st_vid, USB_ST_VID);
401 DD(sl, "stlink pid = 0x%04x (expect 0x%04x)\n",
402 sl->stlink_pid, USB_STLINK_PID);
403 DD(sl, "stlink version = 0x%x\n", sl->stlink_v);
404 DD(sl, "jtag version = 0x%x\n", sl->jtag_v);
405 DD(sl, "swim version = 0x%x\n", sl->swim_v);
408 " notice: the firmware doesn't support a jtag/swd interface\n");
411 " notice: the firmware doesn't support a swim interface\n");
415 static int stlink_mode(struct stlink *sl) {
417 return STLINK_DEV_UNKNOWN_MODE;
419 stlink_print_data(sl);
421 switch (sl->q_buf[0]) {
422 case STLINK_DEV_DFU_MODE:
423 DD(sl, "stlink mode: dfu\n");
424 return STLINK_DEV_DFU_MODE;
425 case STLINK_DEV_DEBUG_MODE:
426 DD(sl, "stlink mode: debug (jtag or swd)\n");
427 return STLINK_DEV_DEBUG_MODE;
428 case STLINK_DEV_MASS_MODE:
429 DD(sl, "stlink mode: mass\n");
430 return STLINK_DEV_MASS_MODE;
432 return STLINK_DEV_UNKNOWN_MODE;
435 static void stlink_stat(struct stlink *sl, char *txt) {
439 stlink_print_data(sl);
441 switch (sl->q_buf[0]) {
443 DD(sl, " %s: ok\n", txt);
446 DD(sl, " %s: false\n", txt);
449 DD(sl, " %s: unknown\n", txt);
453 static void stlink_core_stat(struct stlink *sl) {
457 stlink_print_data(sl);
459 switch (sl->q_buf[0]) {
460 case STLINK_CORE_RUNNING:
461 sl->core_stat = STLINK_CORE_RUNNING;
462 DD(sl, " core status: running\n");
464 case STLINK_CORE_HALTED:
465 sl->core_stat = STLINK_CORE_HALTED;
466 DD(sl, " core status: halted\n");
469 sl->core_stat = STLINK_CORE_STAT_UNKNOWN;
470 fprintf(stderr, " core status: unknown\n");
474 void stlink_version(struct stlink *sl) {
475 D(sl, "\n*** stlink_version ***\n");
477 sl->cdb_cmd_blk[0] = STLINK_GET_VERSION;
481 stlink_parse_version(sl);
485 // STLINK_DEV_DFU_MODE || STLINK_DEV_MASS_MODE || STLINK_DEV_DEBUG_MODE
486 // usb dfu || usb mass || jtag or swd
487 int stlink_current_mode(struct stlink *sl) {
488 D(sl, "\n*** stlink_current_mode ***\n");
490 sl->cdb_cmd_blk[0] = STLINK_GET_CURRENT_MODE;
494 return stlink_mode(sl);
497 // Exit the mass mode and enter the swd debug mode.
498 void stlink_enter_swd_mode(struct stlink *sl) {
499 D(sl, "\n*** stlink_enter_swd_mode ***\n");
501 sl->cdb_cmd_blk[1] = STLINK_DEBUG_ENTER;
502 sl->cdb_cmd_blk[2] = STLINK_DEBUG_ENTER_SWD;
503 sl->q_len = 0; // >0 -> aboard
507 // Exit the mass mode and enter the jtag debug mode.
508 // (jtag is disabled in the discovery's stlink firmware)
509 void stlink_enter_jtag_mode(struct stlink *sl) {
510 D(sl, "\n*** stlink_enter_jtag_mode ***\n");
512 sl->cdb_cmd_blk[1] = STLINK_DEBUG_ENTER;
513 sl->cdb_cmd_blk[2] = STLINK_DEBUG_ENTER_JTAG;
518 // Exit the jtag or swd mode and enter the mass mode.
519 void stlink_exit_debug_mode(struct stlink *sl) {
520 D(sl, "\n*** stlink_exit_debug_mode ***\n");
522 sl->cdb_cmd_blk[1] = STLINK_DEBUG_EXIT;
523 sl->q_len = 0; // >0 -> aboard
527 // XXX kernel driver performs reset, the device temporally disappears
528 static void stlink_exit_dfu_mode(struct stlink *sl) {
529 D(sl, "\n*** stlink_exit_dfu_mode ***\n");
531 sl->cdb_cmd_blk[0] = STLINK_DFU_COMMAND;
532 sl->cdb_cmd_blk[1] = STLINK_DFU_EXIT;
536 [135121.844564] sd 19:0:0:0: [sdb] Unhandled error code
537 [135121.844569] sd 19:0:0:0: [sdb] Result: hostbyte=DID_ERROR driverbyte=DRIVER_OK
538 [135121.844574] sd 19:0:0:0: [sdb] CDB: Read(10): 28 00 00 00 10 00 00 00 08 00
539 [135121.844584] end_request: I/O error, dev sdb, sector 4096
540 [135121.844590] Buffer I/O error on device sdb, logical block 512
541 [135130.122567] usb 6-1: reset full speed USB device using uhci_hcd and address 7
542 [135130.274551] usb 6-1: device firmware changed
543 [135130.274618] usb 6-1: USB disconnect, address 7
544 [135130.275186] VFS: busy inodes on changed media or resized disk sdb
545 [135130.275424] VFS: busy inodes on changed media or resized disk sdb
546 [135130.286758] VFS: busy inodes on changed media or resized disk sdb
547 [135130.292796] VFS: busy inodes on changed media or resized disk sdb
548 [135130.301481] VFS: busy inodes on changed media or resized disk sdb
549 [135130.304316] VFS: busy inodes on changed media or resized disk sdb
550 [135130.431113] usb 6-1: new full speed USB device using uhci_hcd and address 8
551 [135130.629444] usb-storage 6-1:1.0: Quirks match for vid 0483 pid 3744: 102a1
552 [135130.629492] scsi20 : usb-storage 6-1:1.0
553 [135131.625600] scsi 20:0:0:0: Direct-Access STM32 PQ: 0 ANSI: 0
554 [135131.627010] sd 20:0:0:0: Attached scsi generic sg2 type 0
555 [135131.633603] sd 20:0:0:0: [sdb] 64000 512-byte logical blocks: (32.7 MB/31.2 MiB)
556 [135131.633613] sd 20:0:0:0: [sdb] Assuming Write Enabled
557 [135131.633620] sd 20:0:0:0: [sdb] Assuming drive cache: write through
558 [135131.640584] sd 20:0:0:0: [sdb] Assuming Write Enabled
559 [135131.640592] sd 20:0:0:0: [sdb] Assuming drive cache: write through
561 [135131.652634] sd 20:0:0:0: [sdb] Assuming Write Enabled
562 [135131.652639] sd 20:0:0:0: [sdb] Assuming drive cache: write through
563 [135131.652645] sd 20:0:0:0: [sdb] Attached SCSI removable disk
564 [135131.671536] sd 20:0:0:0: [sdb] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
565 [135131.671548] sd 20:0:0:0: [sdb] Sense Key : Illegal Request [current]
566 [135131.671553] sd 20:0:0:0: [sdb] Add. Sense: Logical block address out of range
567 [135131.671560] sd 20:0:0:0: [sdb] CDB: Read(10): 28 00 00 00 f9 80 00 00 08 00
568 [135131.671570] end_request: I/O error, dev sdb, sector 63872
569 [135131.671575] Buffer I/O error on device sdb, logical block 7984
570 [135131.678527] sd 20:0:0:0: [sdb] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
571 [135131.678532] sd 20:0:0:0: [sdb] Sense Key : Illegal Request [current]
572 [135131.678537] sd 20:0:0:0: [sdb] Add. Sense: Logical block address out of range
573 [135131.678542] sd 20:0:0:0: [sdb] CDB: Read(10): 28 00 00 00 f9 80 00 00 08 00
574 [135131.678551] end_request: I/O error, dev sdb, sector 63872
576 [135131.853565] end_request: I/O error, dev sdb, sector 4096
580 void stlink_core_id(struct stlink *sl) {
581 D(sl, "\n*** stlink_core_id ***\n");
583 sl->cdb_cmd_blk[1] = STLINK_DEBUG_READCOREID;
587 sl->core_id = read_uint32(sl->q_buf, 0);
590 stlink_print_data(sl);
591 DD(sl, "core_id = 0x%08x\n", sl->core_id);
594 // Arm-core reset -> halted state.
595 void stlink_reset(struct stlink *sl) {
596 D(sl, "\n*** stlink_reset ***\n");
598 sl->cdb_cmd_blk[1] = STLINK_DEBUG_RESETSYS;
602 stlink_stat(sl, "core reset");
605 // Arm-core status: halted or running.
606 void stlink_status(struct stlink *sl) {
607 D(sl, "\n*** stlink_status ***\n");
609 sl->cdb_cmd_blk[1] = STLINK_DEBUG_GETSTATUS;
613 stlink_core_stat(sl);
616 // Force the core into the debug mode -> halted state.
617 void stlink_force_debug(struct stlink *sl) {
618 D(sl, "\n*** stlink_force_debug ***\n");
620 sl->cdb_cmd_blk[1] = STLINK_DEBUG_FORCEDEBUG;
624 stlink_stat(sl, "force debug");
627 // Read all arm-core registers.
628 void stlink_read_all_regs(struct stlink *sl) {
629 D(sl, "\n*** stlink_read_all_regs ***\n");
631 sl->cdb_cmd_blk[1] = STLINK_DEBUG_READALLREGS;
635 stlink_print_data(sl);
637 // 0-3 | 4-7 | ... | 60-63 | 64-67 | 68-71 | 72-75 | 76-79 | 80-83
638 // r0 | r1 | ... | r15 | xpsr | main_sp | process_sp | rw | rw2
639 for (int i = 0; i < 16; i++) {
640 sl->reg.r[i] = read_uint32(sl->q_buf, 4 * i);
642 DD(sl, "r%2d = 0x%08x\n", i, sl->reg.r[i]);
644 sl->reg.xpsr = read_uint32(sl->q_buf, 64);
645 sl->reg.main_sp = read_uint32(sl->q_buf, 68);
646 sl->reg.process_sp = read_uint32(sl->q_buf, 72);
647 sl->reg.rw = read_uint32(sl->q_buf, 76);
648 sl->reg.rw2 = read_uint32(sl->q_buf, 80);
652 DD(sl, "xpsr = 0x%08x\n", sl->reg.xpsr);
653 DD(sl, "main_sp = 0x%08x\n", sl->reg.main_sp);
654 DD(sl, "process_sp = 0x%08x\n", sl->reg.process_sp);
655 DD(sl, "rw = 0x%08x\n", sl->reg.rw);
656 DD(sl, "rw2 = 0x%08x\n", sl->reg.rw2);
659 // Read an arm-core register, the index must be in the range 0..20.
660 // 0 | 1 | ... | 15 | 16 | 17 | 18 | 19 | 20
661 // r0 | r1 | ... | r15 | xpsr | main_sp | process_sp | rw | rw2
662 void stlink_read_reg(struct stlink *sl, int r_idx) {
663 D(sl, "\n*** stlink_read_reg");
664 DD(sl, " (%d) ***\n", r_idx);
666 if (r_idx > 20 || r_idx < 0) {
667 fprintf(stderr, "Error: register index must be in [0..20]\n");
671 sl->cdb_cmd_blk[1] = STLINK_DEBUG_READREG;
672 sl->cdb_cmd_blk[2] = r_idx;
676 // 0 | 1 | ... | 15 | 16 | 17 | 18 | 19 | 20
677 // 0-3 | 4-7 | ... | 60-63 | 64-67 | 68-71 | 72-75 | 76-79 | 80-83
678 // r0 | r1 | ... | r15 | xpsr | main_sp | process_sp | rw | rw2
679 stlink_print_data(sl);
681 uint32_t r = read_uint32(sl->q_buf, 0);
682 DD(sl, "r_idx (%2d) = 0x%08x\n", r_idx, r);
692 sl->reg.process_sp = r;
695 sl->reg.rw = r; //XXX ?(primask, basemask etc.)
698 sl->reg.rw2 = r; //XXX ?(primask, basemask etc.)
701 sl->reg.r[r_idx] = r;
705 // Write an arm-core register. Index:
706 // 0 | 1 | ... | 15 | 16 | 17 | 18 | 19 | 20
707 // r0 | r1 | ... | r15 | xpsr | main_sp | process_sp | rw | rw2
708 void stlink_write_reg(struct stlink *sl, uint32_t reg, int idx) {
709 D(sl, "\n*** stlink_write_reg ***\n");
711 sl->cdb_cmd_blk[1] = STLINK_DEBUG_WRITEREG;
714 sl->cdb_cmd_blk[2] = idx;
715 write_uint32(sl->cdb_cmd_blk + 3, reg);
719 stlink_stat(sl, "write reg");
722 // Write a register of the debug module of the core.
723 // XXX ?(atomic writes)
725 void stlink_write_dreg(struct stlink *sl, uint32_t reg, uint32_t addr) {
726 D(sl, "\n*** stlink_write_dreg ***\n");
728 sl->cdb_cmd_blk[1] = STLINK_DEBUG_WRITEDEBUGREG;
729 // 2-5: address of reg of the debug module
731 write_uint32(sl->cdb_cmd_blk + 2, addr);
732 write_uint32(sl->cdb_cmd_blk + 6, reg);
736 stlink_stat(sl, "write debug reg");
739 // Force the core exit the debug mode.
740 void stlink_run(struct stlink *sl) {
741 D(sl, "\n*** stlink_run ***\n");
743 sl->cdb_cmd_blk[1] = STLINK_DEBUG_RUNCORE;
747 stlink_stat(sl, "run core");
750 // same as above with entrypoint.
751 static unsigned int is_core_halted(struct stlink*);
752 void stlink_run_at(struct stlink *sl, stm32_addr_t addr) {
753 stlink_write_reg(sl, addr, 15); /* pc register */
757 while (is_core_halted(sl) == 0)
761 // Step the arm-core.
762 void stlink_step(struct stlink *sl) {
763 D(sl, "\n*** stlink_step ***\n");
765 sl->cdb_cmd_blk[1] = STLINK_DEBUG_STEPCORE;
769 stlink_stat(sl, "step core");
773 // see Cortex-M3 Technical Reference Manual
774 void stlink_set_hw_bp(struct stlink *sl, int fp_nr, uint32_t addr, int fp) {
775 D(sl, "\n*** stlink_set_hw_bp ***\n");
777 sl->cdb_cmd_blk[1] = STLINK_DEBUG_SETFP;
778 // 2:The number of the flash patch used to set the breakpoint
779 // 3-6: Address of the breakpoint (LSB)
780 // 7: FP_ALL (0x02) / FP_UPPER (0x01) / FP_LOWER (0x00)
781 sl->q_buf[2] = fp_nr;
782 write_uint32(sl->q_buf, addr);
787 stlink_stat(sl, "set flash breakpoint");
791 void stlink_clr_hw_bp(struct stlink *sl, int fp_nr) {
792 D(sl, "\n*** stlink_clr_hw_bp ***\n");
794 sl->cdb_cmd_blk[1] = STLINK_DEBUG_CLEARFP;
795 sl->cdb_cmd_blk[2] = fp_nr;
799 stlink_stat(sl, "clear flash breakpoint");
802 // Read a "len" bytes to the sl->q_buf from the memory, max 6kB (6144 bytes)
803 void stlink_read_mem32(struct stlink *sl, uint32_t addr, uint16_t len) {
804 D(sl, "\n*** stlink_read_mem32 ***\n");
805 if (len % 4 != 0) { // !!! never ever: fw gives just wrong values
808 "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n",
813 sl->cdb_cmd_blk[1] = STLINK_DEBUG_READMEM_32BIT;
816 write_uint32(sl->cdb_cmd_blk + 2, addr);
817 write_uint16(sl->cdb_cmd_blk + 6, len);
819 // data_in 0-0x40-len
820 // !!! len _and_ q_len must be max 6k,
821 // i.e. >1024 * 6 = 6144 -> aboard)
822 // !!! if len < q_len: 64*k, 1024*n, n=1..5 -> aboard
823 // (broken residue issue)
827 stlink_print_data(sl);
830 // Write a "len" bytes from the sl->q_buf to the memory, max 64 Bytes.
831 void stlink_write_mem8(struct stlink *sl, uint32_t addr, uint16_t len) {
832 D(sl, "\n*** stlink_write_mem8 ***\n");
834 sl->cdb_cmd_blk[1] = STLINK_DEBUG_WRITEMEM_8BIT;
836 // 6-7: len (>0x40 (64) -> aboard)
837 write_uint32(sl->cdb_cmd_blk + 2, addr);
838 write_uint16(sl->cdb_cmd_blk + 6, len);
843 sl->q_data_dir = Q_DATA_OUT;
845 stlink_print_data(sl);
848 // Write a "len" bytes from the sl->q_buf to the memory, max Q_BUF_LEN bytes.
849 void stlink_write_mem32(struct stlink *sl, uint32_t addr, uint16_t len) {
850 D(sl, "\n*** stlink_write_mem32 ***\n");
854 "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n",
859 sl->cdb_cmd_blk[1] = STLINK_DEBUG_WRITEMEM_32BIT;
861 // 6-7: len "unlimited"
862 write_uint32(sl->cdb_cmd_blk + 2, addr);
863 write_uint16(sl->cdb_cmd_blk + 6, len);
865 // data_out 0-0x40-...-len
868 sl->q_data_dir = Q_DATA_OUT;
870 stlink_print_data(sl);
873 /* FPEC flash controller interface, pm0063 manual
876 #define FLASH_REGS_ADDR 0x40022000
877 #define FLASH_REGS_SIZE 0x28
879 #define FLASH_ACR (FLASH_REGS_ADDR + 0x00)
880 #define FLASH_KEYR (FLASH_REGS_ADDR + 0x04)
881 #define FLASH_SR (FLASH_REGS_ADDR + 0x0c)
882 #define FLASH_CR (FLASH_REGS_ADDR + 0x10)
883 #define FLASH_AR (FLASH_REGS_ADDR + 0x14)
884 #define FLASH_OBR (FLASH_REGS_ADDR + 0x1c)
885 #define FLASH_WRPR (FLASH_REGS_ADDR + 0x20)
887 #define FLASH_RDPTR_KEY 0x00a5
888 #define FLASH_KEY1 0x45670123
889 #define FLASH_KEY2 0xcdef89ab
891 #define FLASH_SR_BSY 0
892 #define FLASH_SR_EOP 5
894 #define FLASH_CR_PG 0
895 #define FLASH_CR_PER 1
896 #define FLASH_CR_MER 2
897 #define FLASH_CR_STRT 6
898 #define FLASH_CR_LOCK 7
900 static uint32_t __attribute__((unused)) read_flash_rdp(struct stlink* sl)
902 stlink_read_mem32(sl, FLASH_WRPR, sizeof(uint32_t));
903 return (*(uint32_t*)sl->q_buf) & 0xff;
906 static inline uint32_t read_flash_wrpr(struct stlink* sl)
908 stlink_read_mem32(sl, FLASH_WRPR, sizeof(uint32_t));
909 return *(uint32_t*)sl->q_buf;
912 static inline uint32_t read_flash_obr(struct stlink* sl)
914 stlink_read_mem32(sl, FLASH_OBR, sizeof(uint32_t));
915 return *(uint32_t*)sl->q_buf;
918 static inline uint32_t read_flash_cr(struct stlink* sl)
920 stlink_read_mem32(sl, FLASH_CR, sizeof(uint32_t));
921 return *(uint32_t*)sl->q_buf;
924 static inline unsigned int is_flash_locked(struct stlink* sl)
926 /* return non zero for true */
927 return read_flash_cr(sl) & (1 << FLASH_CR_LOCK);
930 static void unlock_flash(struct stlink* sl)
932 /* the unlock sequence consists of 2 write cycles where
933 2 key values are written to the FLASH_KEYR register.
934 an invalid sequence results in a definitive lock of
935 the FPEC block until next reset.
938 write_uint32(sl->q_buf, FLASH_KEY1);
939 stlink_write_mem32(sl, FLASH_KEYR, sizeof(uint32_t));
941 write_uint32(sl->q_buf, FLASH_KEY2);
942 stlink_write_mem32(sl, FLASH_KEYR, sizeof(uint32_t));
945 static int unlock_flash_if(struct stlink* sl)
947 /* unlock flash if already locked */
949 if (is_flash_locked(sl))
952 if (is_flash_locked(sl))
959 static void lock_flash(struct stlink* sl)
961 /* write to 1 only. reset by hw at unlock sequence */
963 const uint32_t n = read_flash_cr(sl) | (1 << FLASH_CR_LOCK);
965 write_uint32(sl->q_buf, n);
966 stlink_write_mem32(sl, FLASH_CR, sizeof(uint32_t));
969 static void set_flash_cr_pg(struct stlink* sl)
971 const uint32_t n = 1 << FLASH_CR_PG;
972 write_uint32(sl->q_buf, n);
973 stlink_write_mem32(sl, FLASH_CR, sizeof(uint32_t));
976 static void __attribute__((unused)) clear_flash_cr_pg(struct stlink* sl)
978 const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PG);
979 write_uint32(sl->q_buf, n);
980 stlink_write_mem32(sl, FLASH_CR, sizeof(uint32_t));
983 static void set_flash_cr_per(struct stlink* sl)
985 const uint32_t n = 1 << FLASH_CR_PER;
986 write_uint32(sl->q_buf, n);
987 stlink_write_mem32(sl, FLASH_CR, sizeof(uint32_t));
990 static void __attribute__((unused)) clear_flash_cr_per(struct stlink* sl)
992 const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PER);
993 write_uint32(sl->q_buf, n);
994 stlink_write_mem32(sl, FLASH_CR, sizeof(uint32_t));
997 static void set_flash_cr_mer(struct stlink* sl)
999 const uint32_t n = 1 << FLASH_CR_MER;
1000 write_uint32(sl->q_buf, n);
1001 stlink_write_mem32(sl, FLASH_CR, sizeof(uint32_t));
1004 static void __attribute__((unused)) clear_flash_cr_mer(struct stlink* sl)
1006 const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_MER);
1007 write_uint32(sl->q_buf, n);
1008 stlink_write_mem32(sl, FLASH_CR, sizeof(uint32_t));
1011 static void set_flash_cr_strt(struct stlink* sl)
1013 /* assume come on the flash_cr_per path */
1014 const uint32_t n = (1 << FLASH_CR_PER) | (1 << FLASH_CR_STRT);
1015 write_uint32(sl->q_buf, n);
1016 stlink_write_mem32(sl, FLASH_CR, sizeof(uint32_t));
1019 static inline uint32_t read_flash_acr(struct stlink* sl)
1021 stlink_read_mem32(sl, FLASH_ACR, sizeof(uint32_t));
1022 return *(uint32_t*)sl->q_buf;
1025 static inline uint32_t read_flash_sr(struct stlink* sl)
1027 stlink_read_mem32(sl, FLASH_SR, sizeof(uint32_t));
1028 return *(uint32_t*)sl->q_buf;
1031 static inline unsigned int is_flash_busy(struct stlink* sl)
1033 return read_flash_sr(sl) & (1 << FLASH_SR_BSY);
1036 static void wait_flash_busy(struct stlink* sl)
1038 /* todo: add some delays here */
1039 while (is_flash_busy(sl))
1043 static inline unsigned int is_flash_eop(struct stlink* sl)
1045 return read_flash_sr(sl) & (1 << FLASH_SR_EOP);
1048 static void __attribute__((unused)) clear_flash_sr_eop(struct stlink* sl)
1050 const uint32_t n = read_flash_sr(sl) & ~(1 << FLASH_SR_EOP);
1051 write_uint32(sl->q_buf, n);
1052 stlink_write_mem32(sl, FLASH_SR, sizeof(uint32_t));
1055 static void __attribute__((unused)) wait_flash_eop(struct stlink* sl)
1057 /* todo: add some delays here */
1058 while (is_flash_eop(sl) == 0)
1062 static inline void write_flash_ar(struct stlink* sl, uint32_t n)
1064 write_uint32(sl->q_buf, n);
1065 stlink_write_mem32(sl, FLASH_AR, sizeof(uint32_t));
1069 static void disable_flash_read_protection(struct stlink* sl)
1071 /* erase the option byte area */
1077 #if 0 /* not working */
1078 static int write_flash_mem16
1079 (struct stlink* sl, uint32_t addr, uint16_t val)
1081 /* half word writes */
1082 if (addr % 2) return -1;
1084 /* unlock if locked */
1085 unlock_flash_if(sl);
1087 /* set flash programming chosen bit */
1088 set_flash_cr_pg(sl);
1090 write_uint16(sl->q_buf, val);
1091 stlink_write_mem16(sl, addr, 2);
1093 /* wait for non business */
1094 wait_flash_busy(sl);
1098 /* check the programmed value back */
1099 stlink_read_mem16(sl, addr, 2);
1100 if (*(const uint16_t*)sl->q_buf != val)
1102 /* values differ at i * sizeof(uint16_t) */
1109 #endif /* not working */
1111 int stlink_erase_flash_page(struct stlink* sl, stm32_addr_t page)
1113 /* page an addr in the page to erase */
1115 /* wait for ongoing op to finish */
1116 wait_flash_busy(sl);
1118 /* unlock if locked */
1119 unlock_flash_if(sl);
1121 /* set the page erase bit */
1122 set_flash_cr_per(sl);
1124 /* select the page to erase */
1125 write_flash_ar(sl, page);
1127 /* start erase operation, reset by hw with bsy bit */
1128 set_flash_cr_strt(sl);
1130 /* wait for completion */
1131 wait_flash_busy(sl);
1133 /* relock the flash */
1136 /* todo: verify the erased page */
1141 int stlink_erase_flash_mass(struct stlink* sl)
1143 /* wait for ongoing op to finish */
1144 wait_flash_busy(sl);
1146 /* unlock if locked */
1147 unlock_flash_if(sl);
1149 /* set the mass erase bit */
1150 set_flash_cr_mer(sl);
1152 /* start erase operation, reset by hw with bsy bit */
1153 set_flash_cr_strt(sl);
1155 /* wait for completion */
1156 wait_flash_busy(sl);
1158 /* relock the flash */
1161 /* todo: verify the erased memory */
1166 static unsigned int is_core_halted(struct stlink* sl)
1168 /* return non zero if core is halted */
1170 return sl->q_buf[0] == STLINK_CORE_HALTED;
1173 static int write_loader_to_sram
1174 (struct stlink* sl, stm32_addr_t* addr, size_t* size)
1176 /* from openocd, contrib/loaders/flash/stm32.s */
1177 static const uint8_t loader_code[] =
1179 0x08, 0x4c, /* ldr r4, STM32_FLASH_BASE */
1180 0x1c, 0x44, /* add r4, r3 */
1181 /* write_half_word: */
1182 0x01, 0x23, /* movs r3, #0x01 */
1183 0x23, 0x61, /* str r3, [r4, #STM32_FLASH_CR_OFFSET] */
1184 0x30, 0xf8, 0x02, 0x3b, /* ldrh r3, [r0], #0x02 */
1185 0x21, 0xf8, 0x02, 0x3b, /* strh r3, [r1], #0x02 */
1187 0xe3, 0x68, /* ldr r3, [r4, #STM32_FLASH_SR_OFFSET] */
1188 0x13, 0xf0, 0x01, 0x0f, /* tst r3, #0x01 */
1189 0xfb, 0xd0, /* beq busy */
1190 0x13, 0xf0, 0x14, 0x0f, /* tst r3, #0x14 */
1191 0x01, 0xd1, /* bne exit */
1192 0x01, 0x3a, /* subs r2, r2, #0x01 */
1193 0xf0, 0xd1, /* bne write_half_word */
1195 0x00, 0xbe, /* bkpt #0x00 */
1196 0x00, 0x20, 0x02, 0x40, /* STM32_FLASH_BASE: .word 0x40022000 */
1199 memcpy(sl->q_buf, loader_code, sizeof(loader_code));
1200 stlink_write_mem32(sl, sl->sram_base, sizeof(loader_code));
1202 *addr = sl->sram_base;
1203 *size = sizeof(loader_code);
1209 typedef struct flash_loader
1211 stm32_addr_t loader_addr; /* loader sram adddr */
1212 stm32_addr_t buf_addr; /* buffer sram address */
1215 static int write_buffer_to_sram
1216 (struct stlink* sl, flash_loader_t* fl, const uint8_t* buf, size_t size)
1218 /* write the buffer right after the loader */
1219 memcpy(sl->q_buf, buf, size);
1220 stlink_write_mem8(sl, fl->buf_addr, size);
1224 static int init_flash_loader
1225 (struct stlink* sl, flash_loader_t* fl)
1229 /* allocate the loader in sram */
1230 if (write_loader_to_sram(sl, &fl->loader_addr, &size) == -1)
1232 fprintf(stderr, "write_loader_to_sram() == -1\n");
1236 /* allocate a one page buffer in sram right after loader */
1237 fl->buf_addr = fl->loader_addr + size;
1242 static int run_flash_loader
1243 (struct stlink* sl, flash_loader_t* fl, stm32_addr_t target, const uint8_t* buf, size_t size)
1245 const size_t count = size / sizeof(uint16_t);
1247 if (write_buffer_to_sram(sl, fl, buf, size) == -1)
1249 fprintf(stderr, "write_buffer_to_sram() == -1\n");
1254 stlink_write_reg(sl, fl->buf_addr, 0); /* source */
1255 stlink_write_reg(sl, target, 1); /* target */
1256 stlink_write_reg(sl, count, 2); /* count (16 bits half words) */
1257 stlink_write_reg(sl, 0, 3); /* flash bank 0 (input) */
1258 stlink_write_reg(sl, fl->loader_addr, 15); /* pc register */
1260 /* unlock and set programming mode */
1261 unlock_flash_if(sl);
1262 set_flash_cr_pg(sl);
1267 while (is_core_halted(sl) == 0)
1272 /* not all bytes have been written */
1273 stlink_read_reg(sl, 2);
1274 if (sl->reg.r[2] != 0)
1276 fprintf(stderr, "write error, count == %u\n", sl->reg.r[2]);
1283 /* memory mapped file */
1285 typedef struct mapped_file
1291 #define MAPPED_FILE_INITIALIZER { NULL, 0 }
1293 static int map_file(mapped_file_t* mf, const char* path)
1298 const int fd = open(path, O_RDONLY);
1301 fprintf(stderr, "open(%s) == -1\n", path);
1305 if (fstat(fd, &st) == -1)
1307 fprintf(stderr, "fstat() == -1\n");
1311 mf->base = (uint8_t*)mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
1312 if (mf->base == MAP_FAILED)
1314 fprintf(stderr, "mmap() == MAP_FAILED\n");
1318 mf->len = st.st_size;
1329 static void unmap_file(mapped_file_t* mf)
1331 munmap((void*)mf->base, mf->len);
1332 mf->base = (unsigned char*)MAP_FAILED;
1336 static int check_file
1337 (struct stlink* sl, mapped_file_t* mf, stm32_addr_t addr)
1341 for (off = 0; off < mf->len; off += sl->flash_pgsz)
1343 size_t aligned_size;
1345 /* adjust last page size */
1346 size_t cmp_size = sl->flash_pgsz;
1347 if ((off + sl->flash_pgsz) > mf->len)
1348 cmp_size = mf->len - off;
1350 aligned_size = cmp_size;
1351 if (aligned_size & (4 - 1))
1352 aligned_size = (cmp_size + 4) & ~(4 - 1);
1354 stlink_read_mem32(sl, addr + off, aligned_size);
1356 if (memcmp(sl->q_buf, mf->base + off, cmp_size))
1363 static int stlink_fcheck_flash
1364 (struct stlink* sl, const char* path, stm32_addr_t addr)
1366 /* check the contents of path are at addr */
1369 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1371 if (map_file(&mf, path) == -1)
1374 res = check_file(sl, &mf, addr);
1381 // The stlink_fwrite_flash should not muck with mmapped files inside itself,
1382 // and should use this function instead. (Hell, what's the reason behind mmap
1383 // there?!) But, as it is not actually used anywhere, nobody cares.
1385 #define WRITE_BLOCK_SIZE 0x40
1386 int stlink_write_flash(struct stlink* sl, stm32_addr_t addr, uint8_t* base, unsigned len) {
1391 /* check addr range is inside the flash */
1392 if (addr < sl->flash_base) {
1393 fprintf(stderr, "addr too low\n");
1395 } else if ((addr + len) < addr) {
1396 fprintf(stderr, "addr overruns\n");
1398 } else if ((addr + len) > (sl->flash_base + sl->flash_size)) {
1399 fprintf(stderr, "addr too high\n");
1401 } else if ((addr & 1) || (len & 1)) {
1402 fprintf(stderr, "unaligned addr or size\n");
1406 /* flash loader initialization */
1407 if (init_flash_loader(sl, &fl) == -1) {
1408 fprintf(stderr, "init_flash_loader() == -1\n");
1412 /* write each page. above WRITE_BLOCK_SIZE fails? */
1413 for (off = 0; off < len; off += WRITE_BLOCK_SIZE) {
1414 /* adjust last write size */
1415 size_t size = WRITE_BLOCK_SIZE;
1416 if((off + WRITE_BLOCK_SIZE) > len)
1418 printf("writing %d\n", size);
1420 // By some weird reason it fails with an error like
1421 // write error, count == 31
1422 // but it still writes all the data correctly
1423 // so, just ignore it, we are checking the data anyway
1424 if(run_flash_loader(sl, &fl, addr + off, base + off, size) == -1) {
1425 //fprintf(stderr, "run_flash_loader(0x%x) == -1\n", addr + off);
1430 for(off = 0; off < len; off += sl->flash_pgsz) {
1431 size_t aligned_size;
1433 /* adjust last page size */
1434 size_t cmp_size = sl->flash_pgsz;
1435 if ((off + sl->flash_pgsz) > len)
1436 cmp_size = len - off;
1438 aligned_size = cmp_size;
1439 if (aligned_size & (4 - 1))
1440 aligned_size = (cmp_size + 4) & ~(4 - 1);
1442 stlink_read_mem32(sl, addr + off, aligned_size);
1444 if (memcmp(sl->q_buf, base + off, cmp_size))
1451 static int stlink_fwrite_flash
1452 (struct stlink* sl, const char* path, stm32_addr_t addr)
1454 /* write the file in flash at addr */
1458 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1461 if (map_file(&mf, path) == -1)
1463 fprintf(stderr, "map_file() == -1\n");
1467 /* check addr range is inside the flash */
1468 if (addr < sl->flash_base)
1470 fprintf(stderr, "addr too low\n");
1473 else if ((addr + mf.len) < addr)
1475 fprintf(stderr, "addr overruns\n");
1478 else if ((addr + mf.len) > (sl->flash_base + sl->flash_size))
1480 fprintf(stderr, "addr too high\n");
1483 else if ((addr & 1) || (mf.len & 1))
1486 fprintf(stderr, "unaligned addr or size\n");
1490 /* erase each page. todo: mass erase faster? */
1491 for (off = 0; off < mf.len; off += sl->flash_pgsz)
1493 /* addr must be an addr inside the page */
1494 if (stlink_erase_flash_page(sl, addr + off) == -1)
1496 fprintf(stderr, "erase_flash_page(0x%x) == -1\n", addr + off);
1501 /* flash loader initialization */
1502 if (init_flash_loader(sl, &fl) == -1)
1504 fprintf(stderr, "init_flash_loader() == -1\n");
1508 /* write each page. above WRITE_BLOCK_SIZE fails? */
1509 #define WRITE_BLOCK_SIZE 0x40
1510 for (off = 0; off < mf.len; off += WRITE_BLOCK_SIZE)
1512 /* adjust last write size */
1513 size_t size = WRITE_BLOCK_SIZE;
1514 if ((off + WRITE_BLOCK_SIZE) > mf.len)
1515 size = mf.len - off;
1517 if (run_flash_loader(sl, &fl, addr + off, mf.base + off, size) == -1)
1519 fprintf(stderr, "run_flash_loader(0x%x) == -1\n", addr + off);
1524 /* check the file ha been written */
1525 if (check_file(sl, &mf, addr) == -1)
1527 fprintf(stderr, "check_file() == -1\n");
1539 static int stlink_fwrite_sram
1540 (struct stlink* sl, const char* path, stm32_addr_t addr)
1542 /* write the file in sram at addr */
1546 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1548 if (map_file(&mf, path) == -1)
1550 fprintf(stderr, "map_file() == -1\n");
1554 /* check addr range is inside the sram */
1555 if (addr < sl->sram_base)
1557 fprintf(stderr, "addr too low\n");
1560 else if ((addr + mf.len) < addr)
1562 fprintf(stderr, "addr overruns\n");
1565 else if ((addr + mf.len) > (sl->sram_base + sl->sram_size))
1567 fprintf(stderr, "addr too high\n");
1570 else if ((addr & 3) || (mf.len & 3))
1573 fprintf(stderr, "unaligned addr or size\n");
1577 /* do the copy by 1k blocks */
1578 for (off = 0; off < mf.len; off += 1024)
1581 if ((off + size) > mf.len)
1582 size = mf.len - off;
1584 memcpy(sl->q_buf, mf.base + off, size);
1586 /* round size if needed */
1590 stlink_write_mem32(sl, addr + off, size);
1593 /* check the file ha been written */
1594 if (check_file(sl, &mf, addr) == -1)
1596 fprintf(stderr, "check_file() == -1\n");
1609 static int stlink_fread
1610 (struct stlink* sl, const char* path, stm32_addr_t addr, size_t size)
1612 /* read size bytes from addr to file */
1617 const int fd = open(path, O_RDWR | O_TRUNC | O_CREAT, 00700);
1620 fprintf(stderr, "open(%s) == -1\n", path);
1624 /* do the copy by 1k blocks */
1625 for (off = 0; off < size; off += 1024)
1627 size_t read_size = 1024;
1628 if ((off + read_size) > size)
1629 read_size = off + read_size;
1631 /* round size if needed */
1633 read_size = (read_size + 4) & ~(3);
1635 stlink_read_mem32(sl, addr + off, read_size);
1637 if (write(fd, sl->q_buf, read_size) != (ssize_t)read_size)
1639 fprintf(stderr, "write() != read_size\n");
1653 // 1) open a sg device, switch the stlink from dfu to mass mode
1654 // 2) wait 5s until the kernel driver stops reseting the broken device
1655 // 3) reopen the device
1656 // 4) the device driver is now ready for a switch to jtag/swd mode
1657 // TODO thinking, better error handling, wait until the kernel driver stops reseting the plugged-in device
1658 struct stlink* stlink_quirk_open(const char *dev_name, const int verbose) {
1659 struct stlink *sl = stlink_open(dev_name, verbose);
1661 fputs("Error: could not open stlink device\n", stderr);
1667 if (sl->st_vid != USB_ST_VID || sl->stlink_pid != USB_STLINK_PID) {
1668 fprintf(stderr, "Error: the device %s is not a stlink\n",
1670 fprintf(stderr, " VID: got %04x expect %04x \n",
1671 sl->st_vid, USB_ST_VID);
1672 fprintf(stderr, " PID: got %04x expect %04x \n",
1673 sl->stlink_pid, USB_STLINK_PID);
1677 D(sl, "\n*** stlink_force_open ***\n");
1678 switch (stlink_current_mode(sl)) {
1679 case STLINK_DEV_MASS_MODE:
1681 case STLINK_DEV_DEBUG_MODE:
1685 DD(sl, "\n*** switch the stlink to mass mode ***\n");
1686 stlink_exit_dfu_mode(sl);
1687 // exit the dfu mode -> the device is gone
1688 DD(sl, "\n*** reopen the stlink device ***\n");
1693 sl = stlink_open(dev_name, verbose);
1695 fputs("Error: could not open stlink device\n", stderr);
1698 // re-query device info
1703 static void __attribute__((unused)) mark_buf(struct stlink *sl) {
1705 sl->q_buf[0] = 0x12;
1706 sl->q_buf[1] = 0x34;
1707 sl->q_buf[2] = 0x56;
1708 sl->q_buf[3] = 0x78;
1709 sl->q_buf[4] = 0x90;
1710 sl->q_buf[15] = 0x42;
1711 sl->q_buf[16] = 0x43;
1712 sl->q_buf[63] = 0x42;
1713 sl->q_buf[64] = 0x43;
1714 sl->q_buf[1024 * 6 - 1] = 0x42; //6kB
1715 sl->q_buf[1024 * 8 - 1] = 0x42; //8kB
1719 int main(int argc, char *argv[]) {
1720 // set scpi lib debug level: 0 for no debug info, 10 for lots
1721 const int scsi_verbose = 2;
1727 "\nUsage: stlink-access-test /dev/sg0, sg1, ...\n"
1728 "\n*** Notice: The stlink firmware violates the USB standard.\n"
1729 "*** If you plug-in the discovery's stlink, wait a several\n"
1730 "*** minutes to let the kernel driver swallow the broken device.\n"
1731 "*** Watch:\ntail -f /var/log/messages\n"
1732 "*** This command sequence can shorten the waiting time and fix some issues.\n"
1733 "*** Unplug the stlink and execute once as root:\n"
1734 "modprobe -r usb-storage && modprobe usb-storage quirks=483:3744:lrwsro\n\n",
1736 return EXIT_FAILURE;
1741 return EXIT_FAILURE;
1744 fputs("*** stlink access test ***\n", stderr);
1745 DD(sl, "Using sg_lib %s : scsi_pt %s\n", sg_lib_version(),
1748 struct stlink *sl = stlink_force_open(dev_name, scsi_verbose);
1750 return EXIT_FAILURE;
1752 // we are in mass mode, go to swd
1753 stlink_enter_swd_mode(sl);
1754 stlink_current_mode(sl);
1756 //----------------------------------------------------------------------
1759 //stlink_force_debug(sl);
1763 // core system control block
1764 stlink_read_mem32(sl, 0xe000ed00, 4);
1765 DD(sl, "cpu id base register: SCB_CPUID = got 0x%08x expect 0x411fc231", read_uint32(sl->q_buf, 0));
1767 stlink_read_mem32(sl, 0xe000ed90, 4);
1768 DD(sl, "mpu type register: MPU_TYPER = got 0x%08x expect 0x0", read_uint32(sl->q_buf, 0));
1770 stlink_read_mem32(sl, 0xe000edf0, 4);
1771 DD(sl, "DHCSR = 0x%08x", read_uint32(sl->q_buf, 0));
1773 stlink_read_mem32(sl, 0x4001100c, 4);
1774 DD(sl, "GPIOC_ODR = 0x%08x", read_uint32(sl->q_buf, 0));
1777 // happy new year 2011: let blink all the leds
1778 // see "RM0041 Reference manual - STM32F100xx advanced ARM-based 32-bit MCUs"
1780 #define GPIOC 0x40011000 // port C
1781 #define GPIOC_CRH (GPIOC + 0x04) // port configuration register high
1782 #define GPIOC_ODR (GPIOC + 0x0c) // port output data register
1783 #define LED_BLUE (1<<8) // pin 8
1784 #define LED_GREEN (1<<9) // pin 9
1785 stlink_read_mem32(sl, GPIOC_CRH, 4);
1786 uint32_t io_conf = read_uint32(sl->q_buf, 0);
1787 DD(sl, "GPIOC_CRH = 0x%08x", io_conf);
1789 // set: general purpose output push-pull, output mode, max speed 10 MHz.
1790 write_uint32(sl->q_buf, 0x44444411);
1791 stlink_write_mem32(sl, GPIOC_CRH, 4);
1794 for (int i = 0; i < 100; i++) {
1795 write_uint32(sl->q_buf, LED_BLUE | LED_GREEN);
1796 stlink_write_mem32(sl, GPIOC_ODR, 4);
1797 /* stlink_read_mem32(sl, 0x4001100c, 4); */
1798 /* DD(sl, "GPIOC_ODR = 0x%08x", read_uint32(sl->q_buf, 0)); */
1802 stlink_write_mem32(sl, GPIOC_ODR, 4); // PC lo
1805 write_uint32(sl->q_buf, io_conf); // set old state
1809 // TODO rtfm: stlink doesn't have flash write routines
1810 // writing to the flash area confuses the fw for the next read access
1812 //stlink_read_mem32(sl, 0, 1024*6);
1813 // flash 0x08000000 128kB
1814 fputs("++++++++++ read a flash at 0x0800 0000\n", stderr);
1815 stlink_read_mem32(sl, 0x08000000, 1024 * 6); //max 6kB
1817 stlink_read_mem32(sl, 0x08000c00, 5);
1818 stlink_read_mem32(sl, 0x08000c00, 4);
1820 stlink_write_mem32(sl, 0x08000c00, 4);
1821 stlink_read_mem32(sl, 0x08000c00, 256);
1822 stlink_read_mem32(sl, 0x08000c00, 256);
1825 // sram 0x20000000 8kB
1826 fputs("\n++++++++++ read/write 8bit, sram at 0x2000 0000 ++++++++++++++++\n\n", stderr);
1828 stlink_write_mem8(sl, 0x20000000, 16);
1831 stlink_write_mem8(sl, 0x20000000, 1);
1832 stlink_write_mem8(sl, 0x20000001, 1);
1833 stlink_write_mem8(sl, 0x2000000b, 3);
1834 stlink_read_mem32(sl, 0x20000000, 16);
1837 // a not aligned mem32 access doesn't work indeed
1838 fputs("\n++++++++++ read/write 32bit, sram at 0x2000 0000 ++++++++++++++++\n\n", stderr);
1840 stlink_write_mem8(sl, 0x20000000, 32);
1843 stlink_write_mem32(sl, 0x20000000, 1);
1844 stlink_read_mem32(sl, 0x20000000, 16);
1846 stlink_write_mem32(sl, 0x20000001, 1);
1847 stlink_read_mem32(sl, 0x20000000, 16);
1849 stlink_write_mem32(sl, 0x2000000b, 3);
1850 stlink_read_mem32(sl, 0x20000000, 16);
1853 stlink_write_mem32(sl, 0x20000000, 17);
1854 stlink_read_mem32(sl, 0x20000000, 32);
1857 // sram 0x20000000 8kB
1858 fputs("++++++++++ read/write 32bit, sram at 0x2000 0000 ++++++++++++\n", stderr);
1860 stlink_write_mem8(sl, 0x20000000, 64);
1861 stlink_read_mem32(sl, 0x20000000, 64);
1864 stlink_write_mem32(sl, 0x20000000, 1024 * 8); //8kB
1865 stlink_read_mem32(sl, 0x20000000, 1024 * 6);
1866 stlink_read_mem32(sl, 0x20000000 + 1024 * 6, 1024 * 2);
1869 stlink_read_all_regs(sl);
1871 fputs("++++++++++ write r0 = 0x12345678\n", stderr);
1872 stlink_write_reg(sl, 0x12345678, 0);
1873 stlink_read_reg(sl, 0);
1874 stlink_read_all_regs(sl);
1880 stlink_force_debug(sl);
1883 #if 1 /* read the system bootloader */
1884 fputs("\n++++++++++ reading bootloader ++++++++++++++++\n\n", stderr);
1885 stlink_fread(sl, "/tmp/barfoo", sl->sys_base, sl->sys_size);
1887 #if 0 /* read the flash memory */
1888 fputs("\n+++++++ read flash memory\n\n", stderr);
1890 stlink_read_mem32(sl, 0x08000000, 4);
1892 #if 0 /* flash programming */
1893 fputs("\n+++++++ program flash memory\n\n", stderr);
1894 stlink_fwrite_flash(sl, "/tmp/foobar", 0x08000000);
1896 #if 0 /* check file contents */
1897 fputs("\n+++++++ check flash memory\n\n", stderr);
1899 const int res = stlink_fcheck_flash(sl, "/tmp/foobar", 0x08000000);
1900 printf("_____ stlink_fcheck_flash() == %d\n", res);
1904 fputs("\n+++++++ sram write and execute\n\n", stderr);
1905 stlink_fwrite_sram(sl, "/tmp/foobar", sl->sram_base);
1906 stlink_run_at(sl, sl->sram_base);
1911 //----------------------------------------------------------------------
1912 // back to mass mode, just in case ...
1913 stlink_exit_debug_mode(sl);
1914 stlink_current_mode(sl);
1917 //fflush(stderr); fflush(stdout);
1918 return EXIT_SUCCESS;