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