The following patches was applied:
[fw/openocd] / src / flash / stm32x.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include "replacements.h"
28
29 #include "stm32x.h"
30 #include "flash.h"
31 #include "target.h"
32 #include "log.h"
33 #include "armv7m.h"
34 #include "algorithm.h"
35 #include "binarybuffer.h"
36
37 #include <stdlib.h>
38 #include <string.h>
39
40 static int stm32x_register_commands(struct command_context_s *cmd_ctx);
41 static int stm32x_flash_bank_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, struct flash_bank_s *bank);
42 static int stm32x_erase(struct flash_bank_s *bank, int first, int last);
43 static int stm32x_protect(struct flash_bank_s *bank, int set, int first, int last);
44 static int stm32x_write(struct flash_bank_s *bank, u8 *buffer, u32 offset, u32 count);
45 static int stm32x_probe(struct flash_bank_s *bank);
46 static int stm32x_auto_probe(struct flash_bank_s *bank);
47 //static int stm32x_handle_part_id_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
48 static int stm32x_protect_check(struct flash_bank_s *bank);
49 static int stm32x_info(struct flash_bank_s *bank, char *buf, int buf_size);
50
51 static int stm32x_handle_lock_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
52 static int stm32x_handle_unlock_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
53 static int stm32x_handle_options_read_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
54 static int stm32x_handle_options_write_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
55 static int stm32x_handle_mass_erase_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56 static int stm32x_mass_erase(struct flash_bank_s *bank);
57
58 flash_driver_t stm32x_flash =
59 {
60         .name = "stm32x",
61         .register_commands = stm32x_register_commands,
62         .flash_bank_command = stm32x_flash_bank_command,
63         .erase = stm32x_erase,
64         .protect = stm32x_protect,
65         .write = stm32x_write,
66         .probe = stm32x_probe,
67         .auto_probe = stm32x_auto_probe,
68         .erase_check = default_flash_mem_blank_check,
69         .protect_check = stm32x_protect_check,
70         .info = stm32x_info
71 };
72
73 static int stm32x_register_commands(struct command_context_s *cmd_ctx)
74 {
75         command_t *stm32x_cmd = register_command(cmd_ctx, NULL, "stm32x", NULL, COMMAND_ANY, "stm32x flash specific commands");
76         
77         register_command(cmd_ctx, stm32x_cmd, "lock", stm32x_handle_lock_command, COMMAND_EXEC,
78                                          "lock device");
79         register_command(cmd_ctx, stm32x_cmd, "unlock", stm32x_handle_unlock_command, COMMAND_EXEC,
80                                          "unlock protected device");
81         register_command(cmd_ctx, stm32x_cmd, "mass_erase", stm32x_handle_mass_erase_command, COMMAND_EXEC,
82                                          "mass erase device");
83         register_command(cmd_ctx, stm32x_cmd, "options_read", stm32x_handle_options_read_command, COMMAND_EXEC,
84                                          "read device option bytes");
85         register_command(cmd_ctx, stm32x_cmd, "options_write", stm32x_handle_options_write_command, COMMAND_EXEC,
86                                          "write device option bytes");
87         return ERROR_OK;
88 }
89
90 /* flash bank stm32x <base> <size> 0 0 <target#>
91  */
92 static int stm32x_flash_bank_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, struct flash_bank_s *bank)
93 {
94         stm32x_flash_bank_t *stm32x_info;
95         
96         if (argc < 6)
97         {
98                 LOG_WARNING("incomplete flash_bank stm32x configuration");
99                 return ERROR_FLASH_BANK_INVALID;
100         }
101         
102         stm32x_info = malloc(sizeof(stm32x_flash_bank_t));
103         bank->driver_priv = stm32x_info;
104         
105         stm32x_info->write_algorithm = NULL;
106         stm32x_info->probed = 0;
107         
108         return ERROR_OK;
109 }
110
111 static u32 stm32x_get_flash_status(flash_bank_t *bank)
112 {
113         target_t *target = bank->target;
114         u32 status;
115         
116         target_read_u32(target, STM32_FLASH_SR, &status);
117         
118         return status;
119 }
120
121 static u32 stm32x_wait_status_busy(flash_bank_t *bank, int timeout)
122 {
123         u32 status;
124         
125         /* wait for busy to clear */
126         while (((status = stm32x_get_flash_status(bank)) & FLASH_BSY) && (timeout-- > 0))
127         {
128                 LOG_DEBUG("status: 0x%x", status);
129                 alive_sleep(1);
130         }
131         
132         return status;
133 }
134
135 static int stm32x_read_options(struct flash_bank_s *bank)
136 {
137         u32 optiondata;
138         stm32x_flash_bank_t *stm32x_info = NULL;
139         target_t *target = bank->target;
140         
141         stm32x_info = bank->driver_priv;
142         
143         /* read current option bytes */
144         target_read_u32(target, STM32_FLASH_OBR, &optiondata);
145         
146         stm32x_info->option_bytes.user_options = (u16)0xFFF8|((optiondata >> 2) & 0x07);
147         stm32x_info->option_bytes.RDP = (optiondata & (1 << OPT_READOUT)) ? 0xFFFF : 0x5AA5;
148         
149         if (optiondata & (1 << OPT_READOUT))
150                 LOG_INFO("Device Security Bit Set");
151         
152         /* each bit refers to a 4bank protection */
153         target_read_u32(target, STM32_FLASH_WRPR, &optiondata);
154         
155         stm32x_info->option_bytes.protection[0] = (u16)optiondata;
156         stm32x_info->option_bytes.protection[1] = (u16)(optiondata >> 8);
157         stm32x_info->option_bytes.protection[2] = (u16)(optiondata >> 16);
158         stm32x_info->option_bytes.protection[3] = (u16)(optiondata >> 24);
159                 
160         return ERROR_OK;
161 }
162
163 static int stm32x_erase_options(struct flash_bank_s *bank)
164 {
165         stm32x_flash_bank_t *stm32x_info = NULL;
166         target_t *target = bank->target;
167         u32 status;
168         
169         stm32x_info = bank->driver_priv;
170         
171         /* read current options */
172         stm32x_read_options(bank);
173         
174         /* unlock flash registers */
175         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
176         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
177         
178         /* unlock option flash registers */
179         target_write_u32(target, STM32_FLASH_OPTKEYR, KEY1);
180         target_write_u32(target, STM32_FLASH_OPTKEYR, KEY2);
181         
182         /* erase option bytes */
183         target_write_u32(target, STM32_FLASH_CR, FLASH_OPTER|FLASH_OPTWRE);
184         target_write_u32(target, STM32_FLASH_CR, FLASH_OPTER|FLASH_STRT|FLASH_OPTWRE);
185         
186         status = stm32x_wait_status_busy(bank, 10);
187         
188         if( status & FLASH_WRPRTERR )
189                 return ERROR_FLASH_OPERATION_FAILED;
190         if( status & FLASH_PGERR )
191                 return ERROR_FLASH_OPERATION_FAILED;
192         
193         /* clear readout protection and complementary option bytes
194          * this will also force a device unlock if set */
195         stm32x_info->option_bytes.RDP = 0x5AA5;
196         
197         return ERROR_OK;
198 }
199
200 static int stm32x_write_options(struct flash_bank_s *bank)
201 {
202         stm32x_flash_bank_t *stm32x_info = NULL;
203         target_t *target = bank->target;
204         u32 status;
205         
206         stm32x_info = bank->driver_priv;
207         
208         /* unlock flash registers */
209         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
210         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
211         
212         /* unlock option flash registers */
213         target_write_u32(target, STM32_FLASH_OPTKEYR, KEY1);
214         target_write_u32(target, STM32_FLASH_OPTKEYR, KEY2);
215         
216         /* program option bytes */
217         target_write_u32(target, STM32_FLASH_CR, FLASH_OPTPG|FLASH_OPTWRE);
218                 
219         /* write user option byte */
220         target_write_u16(target, STM32_OB_USER, stm32x_info->option_bytes.user_options);
221         
222         status = stm32x_wait_status_busy(bank, 10);
223         
224         if( status & FLASH_WRPRTERR )
225                 return ERROR_FLASH_OPERATION_FAILED;
226         if( status & FLASH_PGERR )
227                 return ERROR_FLASH_OPERATION_FAILED;
228         
229         /* write protection byte 1 */
230         target_write_u16(target, STM32_OB_WRP0, stm32x_info->option_bytes.protection[0]);
231         
232         status = stm32x_wait_status_busy(bank, 10);
233         
234         if( status & FLASH_WRPRTERR )
235                 return ERROR_FLASH_OPERATION_FAILED;
236         if( status & FLASH_PGERR )
237                 return ERROR_FLASH_OPERATION_FAILED;
238         
239         /* write protection byte 2 */
240         target_write_u16(target, STM32_OB_WRP1, stm32x_info->option_bytes.protection[1]);
241         
242         status = stm32x_wait_status_busy(bank, 10);
243         
244         if( status & FLASH_WRPRTERR )
245                 return ERROR_FLASH_OPERATION_FAILED;
246         if( status & FLASH_PGERR )
247                 return ERROR_FLASH_OPERATION_FAILED;
248         
249         /* write protection byte 3 */
250         target_write_u16(target, STM32_OB_WRP2, stm32x_info->option_bytes.protection[2]);
251         
252         status = stm32x_wait_status_busy(bank, 10);
253         
254         if( status & FLASH_WRPRTERR )
255                 return ERROR_FLASH_OPERATION_FAILED;
256         if( status & FLASH_PGERR )
257                 return ERROR_FLASH_OPERATION_FAILED;
258         
259         /* write protection byte 4 */
260         target_write_u16(target, STM32_OB_WRP3, stm32x_info->option_bytes.protection[3]);
261         
262         status = stm32x_wait_status_busy(bank, 10);
263         
264         if( status & FLASH_WRPRTERR )
265                 return ERROR_FLASH_OPERATION_FAILED;
266         if( status & FLASH_PGERR )
267                 return ERROR_FLASH_OPERATION_FAILED;
268         
269         /* write readout protection bit */
270         target_write_u16(target, STM32_OB_RDP, stm32x_info->option_bytes.RDP);
271         
272         status = stm32x_wait_status_busy(bank, 10);
273         
274         if( status & FLASH_WRPRTERR )
275                 return ERROR_FLASH_OPERATION_FAILED;
276         if( status & FLASH_PGERR )
277                 return ERROR_FLASH_OPERATION_FAILED;
278         
279         target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
280         
281         return ERROR_OK;
282 }
283
284 static int stm32x_protect_check(struct flash_bank_s *bank)
285 {
286         target_t *target = bank->target;
287         stm32x_flash_bank_t *stm32x_info = bank->driver_priv;
288         
289         u32 protection;
290         int i, s;
291         int num_bits;
292         int set;
293         
294         if (target->state != TARGET_HALTED)
295         {
296                 LOG_ERROR("Target not halted");
297                 return ERROR_TARGET_NOT_HALTED;
298         }
299         
300         /* medium density - each bit refers to a 4bank protection 
301          * high density - each bit refers to a 2bank protection */
302         target_read_u32(target, STM32_FLASH_WRPR, &protection);
303         
304         /* medium density - each protection bit is for 4 * 1K pages
305          * high density - each protection bit is for 2 * 2K pages */
306         num_bits = (bank->num_sectors / stm32x_info->ppage_size);
307         
308         if (stm32x_info->ppage_size == 2)
309         {
310                 /* high density flash */
311                 
312                 set = 1;
313                 
314                 if (protection & (1 << 31))
315                         set = 0;
316                 
317                 /* bit 31 controls sector 62 - 255 protection */        
318                 for (s = 62; s < bank->num_sectors; s++)
319                 {
320                         bank->sectors[s].is_protected = set;
321                 }
322                 
323                 if (bank->num_sectors > 61)
324                         num_bits = 31;
325                 
326                 for (i = 0; i < num_bits; i++)
327                 {
328                         set = 1;
329                         
330                         if (protection & (1 << i))
331                                 set = 0;
332                         
333                         for (s = 0; s < stm32x_info->ppage_size; s++)
334                                 bank->sectors[(i * stm32x_info->ppage_size) + s].is_protected = set;
335                 }
336         }
337         else
338         {               
339                 /* medium density flash */
340                 for (i = 0; i < num_bits; i++)
341                 {
342                         set = 1;
343                         
344                         if( protection & (1 << i))
345                                 set = 0;
346                         
347                         for (s = 0; s < stm32x_info->ppage_size; s++)
348                                 bank->sectors[(i * stm32x_info->ppage_size) + s].is_protected = set;
349                 }
350         }
351         
352         return ERROR_OK;
353 }
354
355 static int stm32x_erase(struct flash_bank_s *bank, int first, int last)
356 {
357         target_t *target = bank->target;
358         int i;
359         u32 status;
360         
361         if (bank->target->state != TARGET_HALTED)
362         {
363                 LOG_ERROR("Target not halted");
364                 return ERROR_TARGET_NOT_HALTED;
365         }
366         
367         if ((first == 0) && (last == (bank->num_sectors - 1)))
368         {
369                 return stm32x_mass_erase(bank);
370         }
371         
372         /* unlock flash registers */
373         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
374         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
375         
376         for (i = first; i <= last; i++)
377         {       
378                 target_write_u32(target, STM32_FLASH_CR, FLASH_PER);
379                 target_write_u32(target, STM32_FLASH_AR, bank->base + bank->sectors[i].offset);
380                 target_write_u32(target, STM32_FLASH_CR, FLASH_PER|FLASH_STRT);
381                 
382                 status = stm32x_wait_status_busy(bank, 10);
383                 
384                 if( status & FLASH_WRPRTERR )
385                         return ERROR_FLASH_OPERATION_FAILED;
386                 if( status & FLASH_PGERR )
387                         return ERROR_FLASH_OPERATION_FAILED;
388                 bank->sectors[i].is_erased = 1;
389         }
390
391         target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
392         
393         return ERROR_OK;
394 }
395
396 static int stm32x_protect(struct flash_bank_s *bank, int set, int first, int last)
397 {
398         stm32x_flash_bank_t *stm32x_info = NULL;
399         target_t *target = bank->target;
400         u16 prot_reg[4] = {0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF};
401         int i, reg, bit;
402         int status;
403         u32 protection;
404         
405         stm32x_info = bank->driver_priv;
406         
407         if (target->state != TARGET_HALTED)
408         {
409                 LOG_ERROR("Target not halted");
410                 return ERROR_TARGET_NOT_HALTED;
411         }
412         
413         if ((first && (first % stm32x_info->ppage_size)) || ((last + 1) && (last + 1) % stm32x_info->ppage_size))
414         {
415                 LOG_WARNING("sector start/end incorrect - stm32 has %dK sector protection", stm32x_info->ppage_size);
416                 return ERROR_FLASH_SECTOR_INVALID;
417         }
418         
419         /* medium density - each bit refers to a 4bank protection 
420          * high density - each bit refers to a 2bank protection */
421         target_read_u32(target, STM32_FLASH_WRPR, &protection);
422         
423         prot_reg[0] = (u16)protection;
424         prot_reg[1] = (u16)(protection >> 8);
425         prot_reg[2] = (u16)(protection >> 16);
426         prot_reg[3] = (u16)(protection >> 24);
427         
428         if (stm32x_info->ppage_size == 2)
429         {
430                 /* high density flash */
431                 
432                 /* bit 7 controls sector 62 - 255 protection */
433                 if (last > 61)
434                 {
435                         if (set)
436                                 prot_reg[3] &= ~(1 << 7);
437                         else
438                                 prot_reg[3] |= (1 << 7);
439                 }
440                 
441                 if (first > 61)
442                         first = 62;
443                 if (last > 61)
444                         last = 61;
445                 
446                 for (i = first; i <= last; i++)
447                 {
448                         reg = (i / stm32x_info->ppage_size) / 8;
449                         bit = (i / stm32x_info->ppage_size) - (reg * 8);
450                         
451                         if( set )
452                                 prot_reg[reg] &= ~(1 << bit);
453                         else
454                                 prot_reg[reg] |= (1 << bit);
455                 }
456         }
457         else
458         {
459                 /* medium density flash */
460                 for (i = first; i <= last; i++)
461                 {
462                         reg = (i / stm32x_info->ppage_size) / 8;
463                         bit = (i / stm32x_info->ppage_size) - (reg * 8);
464                         
465                         if( set )
466                                 prot_reg[reg] &= ~(1 << bit);
467                         else
468                                 prot_reg[reg] |= (1 << bit);
469                 }
470         }
471         
472         if ((status = stm32x_erase_options(bank)) != ERROR_OK)
473                 return status;
474         
475         stm32x_info->option_bytes.protection[0] = prot_reg[0];
476         stm32x_info->option_bytes.protection[1] = prot_reg[1];
477         stm32x_info->option_bytes.protection[2] = prot_reg[2];
478         stm32x_info->option_bytes.protection[3] = prot_reg[3];
479         
480         return stm32x_write_options(bank);
481 }
482
483 static int stm32x_write_block(struct flash_bank_s *bank, u8 *buffer, u32 offset, u32 count)
484 {
485         stm32x_flash_bank_t *stm32x_info = bank->driver_priv;
486         target_t *target = bank->target;
487         u32 buffer_size = 16384;
488         working_area_t *source;
489         u32 address = bank->base + offset;
490         reg_param_t reg_params[4];
491         armv7m_algorithm_t armv7m_info;
492         int retval = ERROR_OK;
493         
494         u8 stm32x_flash_write_code[] = {
495                                                                         /* write: */
496                 0xDF, 0xF8, 0x24, 0x40,         /* ldr  r4, STM32_FLASH_CR */
497                 0x09, 0x4D,                                     /* ldr  r5, STM32_FLASH_SR */
498                 0x4F, 0xF0, 0x01, 0x03,         /* mov  r3, #1 */
499                 0x23, 0x60,                                     /* str  r3, [r4, #0] */
500                 0x30, 0xF8, 0x02, 0x3B,         /* ldrh r3, [r0], #2 */
501                 0x21, 0xF8, 0x02, 0x3B,         /* strh r3, [r1], #2 */
502                                                                         /* busy: */
503                 0x2B, 0x68,                                     /* ldr  r3, [r5, #0] */
504                 0x13, 0xF0, 0x01, 0x0F,         /* tst  r3, #0x01 */
505                 0xFB, 0xD0,                                     /* beq  busy */
506                 0x13, 0xF0, 0x14, 0x0F,         /* tst  r3, #0x14 */
507                 0x01, 0xD1,                                     /* bne  exit */
508                 0x01, 0x3A,                                     /* subs r2, r2, #1 */
509                 0xED, 0xD1,                                     /* bne  write */
510                                                                         /* exit: */
511                 0xFE, 0xE7,                                     /* b exit */
512                 0x10, 0x20, 0x02, 0x40,         /* STM32_FLASH_CR:      .word 0x40022010 */
513                 0x0C, 0x20, 0x02, 0x40          /* STM32_FLASH_SR:      .word 0x4002200C */
514         };
515         
516         /* flash write code */
517         if (target_alloc_working_area(target, sizeof(stm32x_flash_write_code), &stm32x_info->write_algorithm) != ERROR_OK)
518         {
519                 LOG_WARNING("no working area available, can't do block memory writes");
520                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
521         };
522         
523         if ((retval=target_write_buffer(target, stm32x_info->write_algorithm->address, sizeof(stm32x_flash_write_code), stm32x_flash_write_code))!=ERROR_OK)
524                 return retval;
525
526         /* memory buffer */
527         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK)
528         {
529                 buffer_size /= 2;
530                 if (buffer_size <= 256)
531                 {
532                         /* if we already allocated the writing code, but failed to get a buffer, free the algorithm */
533                         if (stm32x_info->write_algorithm)
534                                 target_free_working_area(target, stm32x_info->write_algorithm);
535                         
536                         LOG_WARNING("no large enough working area available, can't do block memory writes");
537                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
538                 }
539         };
540         
541         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
542         armv7m_info.core_mode = ARMV7M_MODE_ANY;
543         
544         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
545         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
546         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
547         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN);
548         
549         while (count > 0)
550         {
551                 u32 thisrun_count = (count > (buffer_size / 2)) ? (buffer_size / 2) : count;
552                 
553                 if ((retval = target_write_buffer(target, source->address, thisrun_count * 2, buffer))!=ERROR_OK)
554                         break;
555                 
556                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
557                 buf_set_u32(reg_params[1].value, 0, 32, address);
558                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count);
559                 
560                 if ((retval = target->type->run_algorithm(target, 0, NULL, 4, reg_params, stm32x_info->write_algorithm->address, \
561                                 stm32x_info->write_algorithm->address + (sizeof(stm32x_flash_write_code) - 10), 10000, &armv7m_info)) != ERROR_OK)
562                 {
563                         LOG_ERROR("error executing stm32x flash write algorithm");
564                         retval = ERROR_FLASH_OPERATION_FAILED;
565                         break;
566                 }
567                 
568                 if (buf_get_u32(reg_params[3].value, 0, 32) & FLASH_PGERR)
569                 {
570                         LOG_ERROR("flash memory not erased before writing");
571                         retval = ERROR_FLASH_OPERATION_FAILED;
572                         break;
573                 }
574                 
575                 if (buf_get_u32(reg_params[3].value, 0, 32) & FLASH_WRPRTERR)
576                 {
577                         LOG_ERROR("flash memory write protected");
578                         retval = ERROR_FLASH_OPERATION_FAILED;
579                         break;
580                 }
581                 
582                 buffer += thisrun_count * 2;
583                 address += thisrun_count * 2;
584                 count -= thisrun_count;
585         }
586         
587         target_free_working_area(target, source);
588         target_free_working_area(target, stm32x_info->write_algorithm);
589         
590         destroy_reg_param(&reg_params[0]);
591         destroy_reg_param(&reg_params[1]);
592         destroy_reg_param(&reg_params[2]);
593         destroy_reg_param(&reg_params[3]);
594         
595         return retval;
596 }
597
598 static int stm32x_write(struct flash_bank_s *bank, u8 *buffer, u32 offset, u32 count)
599 {
600         target_t *target = bank->target;
601         u32 words_remaining = (count / 2);
602         u32 bytes_remaining = (count & 0x00000001);
603         u32 address = bank->base + offset;
604         u32 bytes_written = 0;
605         u8 status;
606         u32 retval;
607         
608         if (bank->target->state != TARGET_HALTED)
609         {
610                 LOG_ERROR("Target not halted");
611                 return ERROR_TARGET_NOT_HALTED;
612         }
613
614         if (offset & 0x1)
615         {
616                 LOG_WARNING("offset 0x%x breaks required 2-byte alignment", offset);
617                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
618         }
619         
620         /* unlock flash registers */
621         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
622         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
623         
624         /* multiple half words (2-byte) to be programmed? */
625         if (words_remaining > 0) 
626         {
627                 /* try using a block write */
628                 if ((retval = stm32x_write_block(bank, buffer, offset, words_remaining)) != ERROR_OK)
629                 {
630                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
631                         {
632                                 /* if block write failed (no sufficient working area),
633                                  * we use normal (slow) single dword accesses */ 
634                                 LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
635                         }
636                         else if (retval == ERROR_FLASH_OPERATION_FAILED)
637                         {
638                                 LOG_ERROR("flash writing failed with error code: 0x%x", retval);
639                                 return ERROR_FLASH_OPERATION_FAILED;
640                         }
641                 }
642                 else
643                 {
644                         buffer += words_remaining * 2;
645                         address += words_remaining * 2;
646                         words_remaining = 0;
647                 }
648         }
649
650         while (words_remaining > 0)
651         {
652                 target_write_u32(target, STM32_FLASH_CR, FLASH_PG);
653                 target_write_u16(target, address, *(u16*)(buffer + bytes_written));
654                 
655                 status = stm32x_wait_status_busy(bank, 5);
656                 
657                 if( status & FLASH_WRPRTERR )
658                 {
659                         LOG_ERROR("flash memory not erased before writing");
660                         return ERROR_FLASH_OPERATION_FAILED;
661                 }
662                 if( status & FLASH_PGERR )
663                 {
664                         LOG_ERROR("flash memory write protected");
665                         return ERROR_FLASH_OPERATION_FAILED;
666                 }
667
668                 bytes_written += 2;
669                 words_remaining--;
670                 address += 2;
671         }
672         
673         if (bytes_remaining)
674         {
675                 u8 last_halfword[2] = {0xff, 0xff};
676                 int i = 0;
677                                 
678                 while(bytes_remaining > 0)
679                 {
680                         last_halfword[i++] = *(buffer + bytes_written); 
681                         bytes_remaining--;
682                         bytes_written++;
683                 }
684                 
685                 target_write_u32(target, STM32_FLASH_CR, FLASH_PG);
686                 target_write_u16(target, address, *(u16*)last_halfword);
687                 
688                 status = stm32x_wait_status_busy(bank, 5);
689                 
690                 if( status & FLASH_WRPRTERR )
691                 {
692                         LOG_ERROR("flash memory not erased before writing");
693                         return ERROR_FLASH_OPERATION_FAILED;
694                 }
695                 if( status & FLASH_PGERR )
696                 {
697                         LOG_ERROR("flash memory write protected");
698                         return ERROR_FLASH_OPERATION_FAILED;
699                 }
700         }
701         
702         target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
703         
704         return ERROR_OK;
705 }
706
707 static int stm32x_probe(struct flash_bank_s *bank)
708 {
709         target_t *target = bank->target;
710         stm32x_flash_bank_t *stm32x_info = bank->driver_priv;
711         int i;
712         u16 num_pages;
713         u32 device_id;
714         int page_size;
715         
716         if (bank->target->state != TARGET_HALTED)
717         {
718                 LOG_ERROR("Target not halted");
719                 return ERROR_TARGET_NOT_HALTED;
720         }
721
722         stm32x_info->probed = 0;
723         
724         /* read stm32 device id register */
725         target_read_u32(target, 0xE0042000, &device_id);
726         LOG_INFO( "device id = 0x%08x", device_id );
727         
728         /* get flash size from target */
729         if (target_read_u16(target, 0x1FFFF7E0, &num_pages) != ERROR_OK)
730         {
731                 /* failed reading flash size, default to max target family */
732                 num_pages = 0xffff;
733         }
734         
735         if ((device_id & 0x7ff) == 0x410)
736         {
737                 /* medium density - we have 1k pages
738                  * 4 pages for a protection area */
739                 page_size = 1024;
740                 stm32x_info->ppage_size = 4;
741                 
742                 /* check for early silicon */
743                 if (num_pages == 0xffff)
744                 {
745                         /* number of sectors incorrect on revA */
746                         LOG_WARNING( "STM32 flash size failed, probe inaccurate - assuming 128k flash" );
747                         num_pages = 128;
748                 }
749         }
750         else if ((device_id & 0x7ff) == 0x412)
751         {
752                 /* low density - we have 1k pages
753                  * 4 pages for a protection area */
754                 page_size = 1024;
755                 stm32x_info->ppage_size = 4;
756                 
757                 /* check for early silicon */
758                 if (num_pages == 0xffff)
759                 {
760                         /* number of sectors incorrect on revA */
761                         LOG_WARNING( "STM32 flash size failed, probe inaccurate - assuming 32k flash" );
762                         num_pages = 32;
763                 }
764         }
765         else if ((device_id & 0x7ff) == 0x414)
766         {
767                 /* high density - we have 2k pages
768                  * 2 pages for a protection area */
769                 page_size = 2048;
770                 stm32x_info->ppage_size = 2;
771                 
772                 /* check for early silicon */
773                 if (num_pages == 0xffff)
774                 {
775                         /* number of sectors incorrect on revZ */
776                         LOG_WARNING( "STM32 flash size failed, probe inaccurate - assuming 512k flash" );
777                         num_pages = 512;
778                 }
779         }
780         else if ((device_id & 0x7ff) == 0x418)
781         {
782                 /* connectivity line density - we have 1k pages
783                  * 4 pages for a protection area */
784                 page_size = 1024;
785                 stm32x_info->ppage_size = 4;
786                 
787                 /* check for early silicon */
788                 if (num_pages == 0xffff)
789                 {
790                         /* number of sectors incorrect on revZ */
791                         LOG_WARNING( "STM32 flash size failed, probe inaccurate - assuming 256k flash" );
792                         num_pages = 256;
793                 }
794         }
795         else
796         {
797                 LOG_WARNING( "Cannot identify target as a STM32 family." );
798                 return ERROR_FLASH_OPERATION_FAILED;
799         }
800         
801         LOG_INFO( "flash size = %dkbytes", num_pages );
802         
803         /* calculate numbers of pages */
804         num_pages /= (page_size / 1024);
805         
806         bank->base = 0x08000000;
807         bank->size = (num_pages * page_size);
808         bank->num_sectors = num_pages;
809         bank->sectors = malloc(sizeof(flash_sector_t) * num_pages);
810         
811         for (i = 0; i < num_pages; i++)
812         {
813                 bank->sectors[i].offset = i * page_size;
814                 bank->sectors[i].size = page_size;
815                 bank->sectors[i].is_erased = -1;
816                 bank->sectors[i].is_protected = 1;
817         }
818         
819         stm32x_info->probed = 1;
820         
821         return ERROR_OK;
822 }
823
824 static int stm32x_auto_probe(struct flash_bank_s *bank)
825 {
826         stm32x_flash_bank_t *stm32x_info = bank->driver_priv;
827         if (stm32x_info->probed)
828                 return ERROR_OK;
829         return stm32x_probe(bank);
830 }
831
832 #if 0
833 static int stm32x_handle_part_id_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
834 {
835         return ERROR_OK;
836 }
837 #endif
838
839 static int stm32x_info(struct flash_bank_s *bank, char *buf, int buf_size)
840 {
841         target_t *target = bank->target;
842         u32 device_id;
843         int printed;
844         
845         /* read stm32 device id register */
846         target_read_u32(target, 0xE0042000, &device_id);
847         
848         if ((device_id & 0x7ff) == 0x410)
849         {
850                 printed = snprintf(buf, buf_size, "stm32x (Medium Density) - Rev: ");
851                 buf += printed;
852                 buf_size -= printed;
853                 
854                 switch(device_id >> 16)
855                 {
856                         case 0x0000:
857                                 snprintf(buf, buf_size, "A");
858                                 break;
859                         
860                         case 0x2000:
861                                 snprintf(buf, buf_size, "B");
862                                 break;
863                         
864                         case 0x2001:
865                                 snprintf(buf, buf_size, "Z");
866                                 break;
867                         
868                         case 0x2003:
869                                 snprintf(buf, buf_size, "Y");
870                                 break;
871                         
872                         default:
873                                 snprintf(buf, buf_size, "unknown");
874                                 break;
875                 }
876         }
877         else if ((device_id & 0x7ff) == 0x412)
878         {
879                 printed = snprintf(buf, buf_size, "stm32x (Low Density) - Rev: ");
880                 buf += printed;
881                 buf_size -= printed;
882                 
883                 switch(device_id >> 16)
884                 {
885                         case 0x1000:
886                                 snprintf(buf, buf_size, "A");
887                                 break;
888                         
889                         default:
890                                 snprintf(buf, buf_size, "unknown");
891                                 break;
892                 }
893         }
894         else if ((device_id & 0x7ff) == 0x414)
895         {
896                 printed = snprintf(buf, buf_size, "stm32x (High Density) - Rev: ");
897                 buf += printed;
898                 buf_size -= printed;
899                 
900                 switch(device_id >> 16)
901                 {
902                         case 0x1000:
903                                 snprintf(buf, buf_size, "A");
904                                 break;
905                         
906                         case 0x1001:
907                                 snprintf(buf, buf_size, "Z");
908                                 break;
909                         
910                         default:
911                                 snprintf(buf, buf_size, "unknown");
912                                 break;
913                 }
914         }
915         else if ((device_id & 0x7ff) == 0x418)
916         {
917                 printed = snprintf(buf, buf_size, "stm32x (Connectivity) - Rev: ");
918                 buf += printed;
919                 buf_size -= printed;
920                 
921                 switch(device_id >> 16)
922                 {
923                         case 0x1000:
924                                 snprintf(buf, buf_size, "A");
925                                 break;
926
927                         default:
928                                 snprintf(buf, buf_size, "unknown");
929                                 break;
930                 }
931         }
932         else
933         {
934                 snprintf(buf, buf_size, "Cannot identify target as a stm32x\n");
935                 return ERROR_FLASH_OPERATION_FAILED;
936         }
937         
938         return ERROR_OK;
939 }
940
941 static int stm32x_handle_lock_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
942 {
943         flash_bank_t *bank;
944         target_t *target = NULL;
945         stm32x_flash_bank_t *stm32x_info = NULL;
946         
947         if (argc < 1)
948         {
949                 command_print(cmd_ctx, "stm32x lock <bank>");
950                 return ERROR_OK;        
951         }
952         
953         bank = get_flash_bank_by_num(strtoul(args[0], NULL, 0));
954         if (!bank)
955         {
956                 command_print(cmd_ctx, "flash bank '#%s' is out of bounds", args[0]);
957                 return ERROR_OK;
958         }
959         
960         stm32x_info = bank->driver_priv;
961         
962         target = bank->target;
963         
964         if (target->state != TARGET_HALTED)
965         {
966                 LOG_ERROR("Target not halted");
967                 return ERROR_TARGET_NOT_HALTED;
968         }
969         
970         if (stm32x_erase_options(bank) != ERROR_OK)
971         {
972                 command_print(cmd_ctx, "stm32x failed to erase options");
973                 return ERROR_OK;
974         }
975                 
976         /* set readout protection */    
977         stm32x_info->option_bytes.RDP = 0;
978         
979         if (stm32x_write_options(bank) != ERROR_OK)
980         {
981                 command_print(cmd_ctx, "stm32x failed to lock device");
982                 return ERROR_OK;
983         }
984         
985         command_print(cmd_ctx, "stm32x locked");
986         
987         return ERROR_OK;
988 }
989
990 static int stm32x_handle_unlock_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
991 {
992         flash_bank_t *bank;
993         target_t *target = NULL;
994         stm32x_flash_bank_t *stm32x_info = NULL;
995         
996         if (argc < 1)
997         {
998                 command_print(cmd_ctx, "stm32x unlock <bank>");
999                 return ERROR_OK;        
1000         }
1001         
1002         bank = get_flash_bank_by_num(strtoul(args[0], NULL, 0));
1003         if (!bank)
1004         {
1005                 command_print(cmd_ctx, "flash bank '#%s' is out of bounds", args[0]);
1006                 return ERROR_OK;
1007         }
1008         
1009         stm32x_info = bank->driver_priv;
1010         
1011         target = bank->target;
1012         
1013         if (target->state != TARGET_HALTED)
1014         {
1015                 LOG_ERROR("Target not halted");
1016                 return ERROR_TARGET_NOT_HALTED;
1017         }
1018                 
1019         if (stm32x_erase_options(bank) != ERROR_OK)
1020         {
1021                 command_print(cmd_ctx, "stm32x failed to unlock device");
1022                 return ERROR_OK;
1023         }
1024         
1025         if (stm32x_write_options(bank) != ERROR_OK)
1026         {
1027                 command_print(cmd_ctx, "stm32x failed to lock device");
1028                 return ERROR_OK;
1029         }
1030         
1031         command_print(cmd_ctx, "stm32x unlocked");
1032         
1033         return ERROR_OK;
1034 }
1035
1036 static int stm32x_handle_options_read_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1037 {
1038         flash_bank_t *bank;
1039         u32 optionbyte;
1040         target_t *target = NULL;
1041         stm32x_flash_bank_t *stm32x_info = NULL;
1042         
1043         if (argc < 1)
1044         {
1045                 command_print(cmd_ctx, "stm32x options_read <bank>");
1046                 return ERROR_OK;        
1047         }
1048         
1049         bank = get_flash_bank_by_num(strtoul(args[0], NULL, 0));
1050         if (!bank)
1051         {
1052                 command_print(cmd_ctx, "flash bank '#%s' is out of bounds", args[0]);
1053                 return ERROR_OK;
1054         }
1055         
1056         stm32x_info = bank->driver_priv;
1057         
1058         target = bank->target;
1059         
1060         if (target->state != TARGET_HALTED)
1061         {
1062                 LOG_ERROR("Target not halted");
1063                 return ERROR_TARGET_NOT_HALTED;
1064         }
1065         
1066         target_read_u32(target, STM32_FLASH_OBR, &optionbyte);
1067         command_print(cmd_ctx, "Option Byte: 0x%x", optionbyte);
1068         
1069         if (buf_get_u32((u8*)&optionbyte, OPT_ERROR, 1))
1070                 command_print(cmd_ctx, "Option Byte Complement Error");
1071         
1072         if (buf_get_u32((u8*)&optionbyte, OPT_READOUT, 1))
1073                 command_print(cmd_ctx, "Readout Protection On");
1074         else
1075                 command_print(cmd_ctx, "Readout Protection Off");
1076         
1077         if (buf_get_u32((u8*)&optionbyte, OPT_RDWDGSW, 1))
1078                 command_print(cmd_ctx, "Software Watchdog");
1079         else
1080                 command_print(cmd_ctx, "Hardware Watchdog");
1081         
1082         if (buf_get_u32((u8*)&optionbyte, OPT_RDRSTSTOP, 1))
1083                 command_print(cmd_ctx, "Stop: No reset generated");
1084         else
1085                 command_print(cmd_ctx, "Stop: Reset generated");
1086         
1087         if (buf_get_u32((u8*)&optionbyte, OPT_RDRSTSTDBY, 1))
1088                 command_print(cmd_ctx, "Standby: No reset generated");
1089         else
1090                 command_print(cmd_ctx, "Standby: Reset generated");
1091         
1092         return ERROR_OK;
1093 }
1094
1095 static int stm32x_handle_options_write_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1096 {
1097         flash_bank_t *bank;
1098         target_t *target = NULL;
1099         stm32x_flash_bank_t *stm32x_info = NULL;
1100         u16 optionbyte = 0xF8;
1101         
1102         if (argc < 4)
1103         {
1104                 command_print(cmd_ctx, "stm32x options_write <bank> <SWWDG|HWWDG> <RSTSTNDBY|NORSTSTNDBY> <RSTSTOP|NORSTSTOP>");
1105                 return ERROR_OK;
1106         }
1107         
1108         bank = get_flash_bank_by_num(strtoul(args[0], NULL, 0));
1109         if (!bank)
1110         {
1111                 command_print(cmd_ctx, "flash bank '#%s' is out of bounds", args[0]);
1112                 return ERROR_OK;
1113         }
1114         
1115         stm32x_info = bank->driver_priv;
1116         
1117         target = bank->target;
1118         
1119         if (target->state != TARGET_HALTED)
1120         {
1121                 LOG_ERROR("Target not halted");
1122                 return ERROR_TARGET_NOT_HALTED;
1123         }
1124         
1125         if (strcmp(args[1], "SWWDG") == 0)
1126         {
1127                 optionbyte |= (1<<0);
1128         }
1129         else
1130         {
1131                 optionbyte &= ~(1<<0);
1132         }
1133         
1134         if (strcmp(args[2], "NORSTSTNDBY") == 0)
1135         {
1136                 optionbyte |= (1<<1);
1137         }
1138         else
1139         {
1140                 optionbyte &= ~(1<<1);
1141         }
1142         
1143         if (strcmp(args[3], "NORSTSTOP") == 0)
1144         {
1145                 optionbyte |= (1<<2);
1146         }
1147         else
1148         {
1149                 optionbyte &= ~(1<<2);
1150         }
1151         
1152         if (stm32x_erase_options(bank) != ERROR_OK)
1153         {
1154                 command_print(cmd_ctx, "stm32x failed to erase options");
1155                 return ERROR_OK;
1156         }
1157         
1158         stm32x_info->option_bytes.user_options = optionbyte;
1159         
1160         if (stm32x_write_options(bank) != ERROR_OK)
1161         {
1162                 command_print(cmd_ctx, "stm32x failed to write options");
1163                 return ERROR_OK;
1164         }
1165         
1166         command_print(cmd_ctx, "stm32x write options complete");
1167         
1168         return ERROR_OK;
1169 }
1170
1171 static int stm32x_mass_erase(struct flash_bank_s *bank)
1172 {
1173         target_t *target = bank->target;
1174         u32 status;
1175         
1176         if (target->state != TARGET_HALTED)
1177         {
1178                 LOG_ERROR("Target not halted");
1179                 return ERROR_TARGET_NOT_HALTED;
1180         }
1181         
1182         /* unlock option flash registers */
1183         target_write_u32(target, STM32_FLASH_KEYR, KEY1);
1184         target_write_u32(target, STM32_FLASH_KEYR, KEY2);
1185         
1186         /* mass erase flash memory */
1187         target_write_u32(target, STM32_FLASH_CR, FLASH_MER);
1188         target_write_u32(target, STM32_FLASH_CR, FLASH_MER|FLASH_STRT);
1189         
1190         status = stm32x_wait_status_busy(bank, 10);
1191         
1192         target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
1193         
1194         if( status & FLASH_WRPRTERR )
1195         {
1196                 LOG_ERROR("stm32x device protected");
1197                 return ERROR_OK;
1198         }
1199         
1200         if( status & FLASH_PGERR )
1201         {
1202                 LOG_ERROR("stm32x device programming failed");
1203                 return ERROR_OK;
1204         }
1205         
1206         return ERROR_OK;
1207 }
1208
1209 static int stm32x_handle_mass_erase_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1210 {
1211         flash_bank_t *bank;
1212         int i;
1213         
1214         if (argc < 1)
1215         {
1216                 command_print(cmd_ctx, "stm32x mass_erase <bank>");
1217                 return ERROR_OK;        
1218         }
1219         
1220         bank = get_flash_bank_by_num(strtoul(args[0], NULL, 0));
1221         if (!bank)
1222         {
1223                 command_print(cmd_ctx, "flash bank '#%s' is out of bounds", args[0]);
1224                 return ERROR_OK;
1225         }
1226         
1227         if (stm32x_mass_erase(bank) == ERROR_OK)
1228         {
1229                 /* set all sectors as erased */
1230                 for (i = 0; i < bank->num_sectors; i++)
1231                 {
1232                         bank->sectors[i].is_erased = 1;
1233                 }
1234                 
1235                 command_print(cmd_ctx, "stm32x mass erase complete");
1236         }
1237         else
1238         {
1239                 command_print(cmd_ctx, "stm32x mass erase failed");
1240         }
1241         
1242         return ERROR_OK;
1243 }