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