flash/nor: make all working area pointers local
[fw/openocd] / src / flash / nor / em357.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  *   Copyright (C) 2011 by Erik Botö
9  *   erik.boto@pelagicore.com
10  *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program; if not, write to the                         *
23  *   Free Software Foundation, Inc.,                                       *
24  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
25  ***************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "imp.h"
32 #include <helper/binarybuffer.h>
33 #include <target/algorithm.h>
34 #include <target/armv7m.h>
35
36 /* em357 register locations */
37
38 #define EM357_FLASH_ACR         0x40008000
39 #define EM357_FLASH_KEYR        0x40008004
40 #define EM357_FLASH_OPTKEYR     0x40008008
41 #define EM357_FLASH_SR          0x4000800C
42 #define EM357_FLASH_CR          0x40008010
43 #define EM357_FLASH_AR          0x40008014
44 #define EM357_FLASH_OBR         0x4000801C
45 #define EM357_FLASH_WRPR        0x40008020
46
47 #define EM357_FPEC_CLK          0x4000402c
48 /* option byte location */
49
50 #define EM357_OB_RDP            0x08040800
51 #define EM357_OB_WRP0           0x08040808
52 #define EM357_OB_WRP1           0x0804080A
53 #define EM357_OB_WRP2           0x0804080C
54
55 /* FLASH_CR register bits */
56
57 #define FLASH_PG                (1 << 0)
58 #define FLASH_PER               (1 << 1)
59 #define FLASH_MER               (1 << 2)
60 #define FLASH_OPTPG             (1 << 4)
61 #define FLASH_OPTER             (1 << 5)
62 #define FLASH_STRT              (1 << 6)
63 #define FLASH_LOCK              (1 << 7)
64 #define FLASH_OPTWRE    (1 << 9)
65
66 /* FLASH_SR register bits */
67
68 #define FLASH_BSY               (1 << 0)
69 #define FLASH_PGERR             (1 << 2)
70 #define FLASH_WRPRTERR  (1 << 4)
71 #define FLASH_EOP               (1 << 5)
72
73 /* EM357_FLASH_OBR bit definitions (reading) */
74
75 #define OPT_ERROR               0
76 #define OPT_READOUT             1
77
78 /* register unlock keys */
79
80 #define KEY1                    0x45670123
81 #define KEY2                    0xCDEF89AB
82
83 struct em357_options {
84         uint16_t RDP;
85         uint16_t user_options;
86         uint16_t protection[3];
87 };
88
89 struct em357_flash_bank {
90         struct em357_options option_bytes;
91         int ppage_size;
92         int probed;
93 };
94
95 static int em357_mass_erase(struct flash_bank *bank);
96
97 /* flash bank em357 <base> <size> 0 0 <target#>
98  */
99 FLASH_BANK_COMMAND_HANDLER(em357_flash_bank_command)
100 {
101         struct em357_flash_bank *em357_info;
102
103         if (CMD_ARGC < 6)
104                 return ERROR_COMMAND_SYNTAX_ERROR;
105
106         em357_info = malloc(sizeof(struct em357_flash_bank));
107         bank->driver_priv = em357_info;
108
109         em357_info->probed = 0;
110
111         return ERROR_OK;
112 }
113
114 static inline int em357_get_flash_status(struct flash_bank *bank, uint32_t *status)
115 {
116         struct target *target = bank->target;
117         return target_read_u32(target, EM357_FLASH_SR, status);
118 }
119
120 static int em357_wait_status_busy(struct flash_bank *bank, int timeout)
121 {
122         struct target *target = bank->target;
123         uint32_t status;
124         int retval = ERROR_OK;
125
126         /* wait for busy to clear */
127         for (;; ) {
128                 retval = em357_get_flash_status(bank, &status);
129                 if (retval != ERROR_OK)
130                         return retval;
131                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
132                 if ((status & FLASH_BSY) == 0)
133                         break;
134                 if (timeout-- <= 0) {
135                         LOG_ERROR("timed out waiting for flash");
136                         return ERROR_FAIL;
137                 }
138                 alive_sleep(1);
139         }
140
141         if (status & FLASH_WRPRTERR) {
142                 LOG_ERROR("em357 device protected");
143                 retval = ERROR_FAIL;
144         }
145
146         if (status & FLASH_PGERR) {
147                 LOG_ERROR("em357 device programming failed");
148                 retval = ERROR_FAIL;
149         }
150
151         /* Clear but report errors */
152         if (status & (FLASH_WRPRTERR | FLASH_PGERR)) {
153                 /* If this operation fails, we ignore it and report the original
154                  * retval
155                  */
156                 target_write_u32(target, EM357_FLASH_SR, FLASH_WRPRTERR | FLASH_PGERR);
157         }
158         return retval;
159 }
160
161 static int em357_read_options(struct flash_bank *bank)
162 {
163         uint32_t optiondata;
164         struct em357_flash_bank *em357_info = NULL;
165         struct target *target = bank->target;
166
167         em357_info = bank->driver_priv;
168
169         /* read current option bytes */
170         int retval = target_read_u32(target, EM357_FLASH_OBR, &optiondata);
171         if (retval != ERROR_OK)
172                 return retval;
173
174         em357_info->option_bytes.user_options = (uint16_t)0xFFFC | ((optiondata >> 2) & 0x03);
175         em357_info->option_bytes.RDP = (optiondata & (1 << OPT_READOUT)) ? 0xFFFF : 0x5AA5;
176
177         if (optiondata & (1 << OPT_READOUT))
178                 LOG_INFO("Device Security Bit Set");
179
180         /* each bit refers to a 4bank protection */
181         retval = target_read_u32(target, EM357_FLASH_WRPR, &optiondata);
182         if (retval != ERROR_OK)
183                 return retval;
184
185         em357_info->option_bytes.protection[0] = (uint16_t)optiondata;
186         em357_info->option_bytes.protection[1] = (uint16_t)(optiondata >> 8);
187         em357_info->option_bytes.protection[2] = (uint16_t)(optiondata >> 16);
188
189         return ERROR_OK;
190 }
191
192 static int em357_erase_options(struct flash_bank *bank)
193 {
194         struct em357_flash_bank *em357_info = NULL;
195         struct target *target = bank->target;
196
197         em357_info = bank->driver_priv;
198
199         /* read current options */
200         em357_read_options(bank);
201
202         /* unlock flash registers */
203         int retval = target_write_u32(target, EM357_FLASH_KEYR, KEY1);
204         if (retval != ERROR_OK)
205                 return retval;
206
207         retval = target_write_u32(target, EM357_FLASH_KEYR, KEY2);
208         if (retval != ERROR_OK)
209                 return retval;
210
211         /* unlock option flash registers */
212         retval = target_write_u32(target, EM357_FLASH_OPTKEYR, KEY1);
213         if (retval != ERROR_OK)
214                 return retval;
215         retval = target_write_u32(target, EM357_FLASH_OPTKEYR, KEY2);
216         if (retval != ERROR_OK)
217                 return retval;
218
219         /* erase option bytes */
220         retval = target_write_u32(target, EM357_FLASH_CR, FLASH_OPTER | FLASH_OPTWRE);
221         if (retval != ERROR_OK)
222                 return retval;
223         retval = target_write_u32(target, EM357_FLASH_CR, FLASH_OPTER | FLASH_STRT | FLASH_OPTWRE);
224         if (retval != ERROR_OK)
225                 return retval;
226
227         retval = em357_wait_status_busy(bank, 10);
228         if (retval != ERROR_OK)
229                 return retval;
230
231         /* clear readout protection and complementary option bytes
232          * this will also force a device unlock if set */
233         em357_info->option_bytes.RDP = 0x5AA5;
234
235         return ERROR_OK;
236 }
237
238 static int em357_write_options(struct flash_bank *bank)
239 {
240         struct em357_flash_bank *em357_info = NULL;
241         struct target *target = bank->target;
242
243         em357_info = bank->driver_priv;
244
245         /* unlock flash registers */
246         int retval = target_write_u32(target, EM357_FLASH_KEYR, KEY1);
247         if (retval != ERROR_OK)
248                 return retval;
249         retval = target_write_u32(target, EM357_FLASH_KEYR, KEY2);
250         if (retval != ERROR_OK)
251                 return retval;
252
253         /* unlock option flash registers */
254         retval = target_write_u32(target, EM357_FLASH_OPTKEYR, KEY1);
255         if (retval != ERROR_OK)
256                 return retval;
257         retval = target_write_u32(target, EM357_FLASH_OPTKEYR, KEY2);
258         if (retval != ERROR_OK)
259                 return retval;
260
261         /* program option bytes */
262         retval = target_write_u32(target, EM357_FLASH_CR, FLASH_OPTPG | FLASH_OPTWRE);
263         if (retval != ERROR_OK)
264                 return retval;
265
266         retval = em357_wait_status_busy(bank, 10);
267         if (retval != ERROR_OK)
268                 return retval;
269
270         /* write protection byte 1 */
271         retval = target_write_u16(target, EM357_OB_WRP0, em357_info->option_bytes.protection[0]);
272         if (retval != ERROR_OK)
273                 return retval;
274
275         retval = em357_wait_status_busy(bank, 10);
276         if (retval != ERROR_OK)
277                 return retval;
278
279         /* write protection byte 2 */
280         retval = target_write_u16(target, EM357_OB_WRP1, em357_info->option_bytes.protection[1]);
281         if (retval != ERROR_OK)
282                 return retval;
283
284         retval = em357_wait_status_busy(bank, 10);
285         if (retval != ERROR_OK)
286                 return retval;
287
288         /* write protection byte 3 */
289         retval = target_write_u16(target, EM357_OB_WRP2, em357_info->option_bytes.protection[2]);
290         if (retval != ERROR_OK)
291                 return retval;
292
293         retval = em357_wait_status_busy(bank, 10);
294         if (retval != ERROR_OK)
295                 return retval;
296
297         /* write readout protection bit */
298         retval = target_write_u16(target, EM357_OB_RDP, em357_info->option_bytes.RDP);
299         if (retval != ERROR_OK)
300                 return retval;
301
302         retval = em357_wait_status_busy(bank, 10);
303         if (retval != ERROR_OK)
304                 return retval;
305
306         retval = target_write_u32(target, EM357_FLASH_CR, FLASH_LOCK);
307         if (retval != ERROR_OK)
308                 return retval;
309
310         return ERROR_OK;
311 }
312
313 static int em357_protect_check(struct flash_bank *bank)
314 {
315         struct target *target = bank->target;
316         struct em357_flash_bank *em357_info = bank->driver_priv;
317
318         uint32_t protection;
319         int i, s;
320         int num_bits;
321         int set;
322
323         if (target->state != TARGET_HALTED) {
324                 LOG_ERROR("Target not halted");
325                 return ERROR_TARGET_NOT_HALTED;
326         }
327
328         /* each bit refers to a 4bank protection (bit 0-23) */
329         int retval = target_read_u32(target, EM357_FLASH_WRPR, &protection);
330         if (retval != ERROR_OK)
331                 return retval;
332
333         /* each protection bit is for 4 * 2K pages */
334         num_bits = (bank->num_sectors / em357_info->ppage_size);
335
336         for (i = 0; i < num_bits; i++) {
337                 set = 1;
338                 if (protection & (1 << i))
339                         set = 0;
340
341                 for (s = 0; s < em357_info->ppage_size; s++)
342                         bank->sectors[(i * em357_info->ppage_size) + s].is_protected = set;
343         }
344
345         return ERROR_OK;
346 }
347
348 static int em357_erase(struct flash_bank *bank, int first, int last)
349 {
350         struct target *target = bank->target;
351         int i;
352
353         if (bank->target->state != TARGET_HALTED) {
354                 LOG_ERROR("Target not halted");
355                 return ERROR_TARGET_NOT_HALTED;
356         }
357
358         if ((first == 0) && (last == (bank->num_sectors - 1)))
359                 return em357_mass_erase(bank);
360
361         /* unlock flash registers */
362         int retval = target_write_u32(target, EM357_FLASH_KEYR, KEY1);
363         if (retval != ERROR_OK)
364                 return retval;
365         retval = target_write_u32(target, EM357_FLASH_KEYR, KEY2);
366         if (retval != ERROR_OK)
367                 return retval;
368
369         for (i = first; i <= last; i++) {
370                 retval = target_write_u32(target, EM357_FLASH_CR, FLASH_PER);
371                 if (retval != ERROR_OK)
372                         return retval;
373                 retval = target_write_u32(target, EM357_FLASH_AR,
374                                 bank->base + bank->sectors[i].offset);
375                 if (retval != ERROR_OK)
376                         return retval;
377                 retval = target_write_u32(target, EM357_FLASH_CR, FLASH_PER | FLASH_STRT);
378                 if (retval != ERROR_OK)
379                         return retval;
380
381                 retval = em357_wait_status_busy(bank, 100);
382                 if (retval != ERROR_OK)
383                         return retval;
384
385                 bank->sectors[i].is_erased = 1;
386         }
387
388         retval = target_write_u32(target, EM357_FLASH_CR, FLASH_LOCK);
389         if (retval != ERROR_OK)
390                 return retval;
391
392         return ERROR_OK;
393 }
394
395 static int em357_protect(struct flash_bank *bank, int set, int first, int last)
396 {
397         struct em357_flash_bank *em357_info = NULL;
398         struct target *target = bank->target;
399         uint16_t prot_reg[4] = {0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF};
400         int i, reg, bit;
401         int status;
402         uint32_t protection;
403
404         em357_info = bank->driver_priv;
405
406         if (target->state != TARGET_HALTED) {
407                 LOG_ERROR("Target not halted");
408                 return ERROR_TARGET_NOT_HALTED;
409         }
410
411         if ((first % em357_info->ppage_size) != 0) {
412                 LOG_WARNING("aligned start protect sector to a %d sector boundary",
413                         em357_info->ppage_size);
414                 first = first - (first % em357_info->ppage_size);
415         }
416         if (((last + 1) % em357_info->ppage_size) != 0) {
417                 LOG_WARNING("aligned end protect sector to a %d sector boundary",
418                         em357_info->ppage_size);
419                 last++;
420                 last = last - (last % em357_info->ppage_size);
421                 last--;
422         }
423
424         /* each bit refers to a 4bank protection */
425         int retval = target_read_u32(target, EM357_FLASH_WRPR, &protection);
426         if (retval != ERROR_OK)
427                 return retval;
428
429         prot_reg[0] = (uint16_t)protection;
430         prot_reg[1] = (uint16_t)(protection >> 8);
431         prot_reg[2] = (uint16_t)(protection >> 16);
432
433         for (i = first; i <= last; i++) {
434                 reg = (i / em357_info->ppage_size) / 8;
435                 bit = (i / em357_info->ppage_size) - (reg * 8);
436
437                 LOG_WARNING("reg, bit: %d, %d", reg, bit);
438                 if (set)
439                         prot_reg[reg] &= ~(1 << bit);
440                 else
441                         prot_reg[reg] |= (1 << bit);
442         }
443
444         status = em357_erase_options(bank);
445         if (retval != ERROR_OK)
446                 return status;
447
448         em357_info->option_bytes.protection[0] = prot_reg[0];
449         em357_info->option_bytes.protection[1] = prot_reg[1];
450         em357_info->option_bytes.protection[2] = prot_reg[2];
451
452         return em357_write_options(bank);
453 }
454
455 static int em357_write_block(struct flash_bank *bank, uint8_t *buffer,
456         uint32_t offset, uint32_t count)
457 {
458         struct target *target = bank->target;
459         uint32_t buffer_size = 16384;
460         struct working_area *write_algorithm;
461         struct working_area *source;
462         uint32_t address = bank->base + offset;
463         struct reg_param reg_params[4];
464         struct armv7m_algorithm armv7m_info;
465         int retval = ERROR_OK;
466
467         /* see contib/loaders/flash/stm32x.s for src, the same is used here except for
468          * a modified *_FLASH_BASE */
469
470         static const uint8_t em357_flash_write_code[] = {
471                 /* #define EM357_FLASH_CR_OFFSET        0x10
472                  * #define EM357_FLASH_SR_OFFSET        0x0C
473                  * write: */
474                 0x08, 0x4c,                                     /* ldr  r4, EM357_FLASH_BASE */
475                 0x1c, 0x44,                                     /* add  r4, r3 */
476                 /* write_half_word: */
477                 0x01, 0x23,                                     /* movs r3, #0x01 */
478                 0x23, 0x61,                                     /* str  r3, [r4,
479                                                                  *#EM357_FLASH_CR_OFFSET] */
480                 0x30, 0xf8, 0x02, 0x3b,         /* ldrh r3, [r0], #0x02 */
481                 0x21, 0xf8, 0x02, 0x3b,         /* strh r3, [r1], #0x02 */
482                 /* busy: */
483                 0xe3, 0x68,                                     /* ldr  r3, [r4,
484                                                                  *#EM357_FLASH_SR_OFFSET] */
485                 0x13, 0xf0, 0x01, 0x0f,         /* tst  r3, #0x01 */
486                 0xfb, 0xd0,                                     /* beq  busy */
487                 0x13, 0xf0, 0x14, 0x0f,         /* tst  r3, #0x14 */
488                 0x01, 0xd1,                                     /* bne  exit */
489                 0x01, 0x3a,                                     /* subs r2, r2, #0x01 */
490                 0xf0, 0xd1,                                     /* bne  write_half_word */
491                 /* exit: */
492                 0x00, 0xbe,                                     /* bkpt #0x00 */
493                 0x00, 0x80, 0x00, 0x40,         /* EM357_FLASH_BASE: .word 0x40008000 */
494         };
495
496         /* flash write code */
497         if (target_alloc_working_area(target, sizeof(em357_flash_write_code),
498                         &write_algorithm) != ERROR_OK) {
499                 LOG_WARNING("no working area available, can't do block memory writes");
500                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
501         }
502         ;
503
504         retval = target_write_buffer(target, write_algorithm->address,
505                         sizeof(em357_flash_write_code), (uint8_t *)em357_flash_write_code);
506         if (retval != ERROR_OK)
507                 return retval;
508
509         /* memory buffer */
510         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
511                 buffer_size /= 2;
512                 if (buffer_size <= 256) {
513                         /* we already allocated the writing code, but failed to get a
514                          * buffer, free the algorithm */
515                         target_free_working_area(target, write_algorithm);
516
517                         LOG_WARNING(
518                                 "no large enough working area available, can't do block memory writes");
519                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
520                 }
521         }
522         ;
523
524         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
525         armv7m_info.core_mode = ARMV7M_MODE_ANY;
526
527         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
528         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
529         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
530         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN_OUT);
531
532         while (count > 0) {
533                 uint32_t thisrun_count = (count > (buffer_size / 2)) ?
534                         (buffer_size / 2) : count;
535
536                 retval = target_write_buffer(target, source->address, thisrun_count * 2, buffer);
537                 if (retval != ERROR_OK)
538                         break;
539
540                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
541                 buf_set_u32(reg_params[1].value, 0, 32, address);
542                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count);
543                 buf_set_u32(reg_params[3].value, 0, 32, 0);
544
545                 retval = target_run_algorithm(target, 0, NULL, 4, reg_params,
546                                 write_algorithm->address, 0, 10000, &armv7m_info);
547                 if (retval != ERROR_OK) {
548                         LOG_ERROR("error executing em357 flash write algorithm");
549                         break;
550                 }
551
552                 if (buf_get_u32(reg_params[3].value, 0, 32) & FLASH_PGERR) {
553                         LOG_ERROR("flash memory not erased before writing");
554                         /* Clear but report errors */
555                         target_write_u32(target, EM357_FLASH_SR, FLASH_PGERR);
556                         retval = ERROR_FAIL;
557                         break;
558                 }
559
560                 if (buf_get_u32(reg_params[3].value, 0, 32) & FLASH_WRPRTERR) {
561                         LOG_ERROR("flash memory write protected");
562                         /* Clear but report errors */
563                         target_write_u32(target, EM357_FLASH_SR, FLASH_WRPRTERR);
564                         retval = ERROR_FAIL;
565                         break;
566                 }
567
568                 buffer += thisrun_count * 2;
569                 address += thisrun_count * 2;
570                 count -= thisrun_count;
571         }
572
573         target_free_working_area(target, source);
574         target_free_working_area(target, write_algorithm);
575
576         destroy_reg_param(&reg_params[0]);
577         destroy_reg_param(&reg_params[1]);
578         destroy_reg_param(&reg_params[2]);
579         destroy_reg_param(&reg_params[3]);
580
581         return retval;
582 }
583
584 static int em357_write(struct flash_bank *bank, uint8_t *buffer,
585         uint32_t offset, uint32_t count)
586 {
587         struct target *target = bank->target;
588         uint32_t words_remaining = (count / 2);
589         uint32_t bytes_remaining = (count & 0x00000001);
590         uint32_t address = bank->base + offset;
591         uint32_t bytes_written = 0;
592         int retval;
593
594         if (bank->target->state != TARGET_HALTED) {
595                 LOG_ERROR("Target not halted");
596                 return ERROR_TARGET_NOT_HALTED;
597         }
598
599         if (offset & 0x1) {
600                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
601                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
602         }
603
604         /* unlock flash registers */
605         retval = target_write_u32(target, EM357_FLASH_KEYR, KEY1);
606         if (retval != ERROR_OK)
607                 return retval;
608         retval = target_write_u32(target, EM357_FLASH_KEYR, KEY2);
609         if (retval != ERROR_OK)
610                 return retval;
611
612         /* multiple half words (2-byte) to be programmed? */
613         if (words_remaining > 0) {
614                 /* try using a block write */
615                 retval = em357_write_block(bank, buffer, offset, words_remaining);
616                 if (retval != ERROR_OK) {
617                         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
618                                 /* if block write failed (no sufficient working area),
619                                  * we use normal (slow) single dword accesses */
620                                 LOG_WARNING(
621                                         "couldn't use block writes, falling back to single memory accesses");
622                         }
623                 } else {
624                         buffer += words_remaining * 2;
625                         address += words_remaining * 2;
626                         words_remaining = 0;
627                 }
628         }
629
630         if ((retval != ERROR_OK) && (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE))
631                 return retval;
632
633         while (words_remaining > 0) {
634                 uint16_t value;
635                 memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
636
637                 retval = target_write_u32(target, EM357_FLASH_CR, FLASH_PG);
638                 if (retval != ERROR_OK)
639                         return retval;
640                 retval = target_write_u16(target, address, value);
641                 if (retval != ERROR_OK)
642                         return retval;
643
644                 retval = em357_wait_status_busy(bank, 5);
645                 if (retval != ERROR_OK)
646                         return retval;
647
648                 bytes_written += 2;
649                 words_remaining--;
650                 address += 2;
651         }
652
653         if (bytes_remaining) {
654                 uint16_t value = 0xffff;
655                 memcpy(&value, buffer + bytes_written, bytes_remaining);
656
657                 retval = target_write_u32(target, EM357_FLASH_CR, FLASH_PG);
658                 if (retval != ERROR_OK)
659                         return retval;
660                 retval = target_write_u16(target, address, value);
661                 if (retval != ERROR_OK)
662                         return retval;
663
664                 retval = em357_wait_status_busy(bank, 5);
665                 if (retval != ERROR_OK)
666                         return retval;
667         }
668
669         return target_write_u32(target, EM357_FLASH_CR, FLASH_LOCK);
670 }
671
672 static int em357_probe(struct flash_bank *bank)
673 {
674         struct target *target = bank->target;
675         struct em357_flash_bank *em357_info = bank->driver_priv;
676         int i;
677         uint16_t num_pages;
678         int page_size;
679         uint32_t base_address = 0x08000000;
680
681         em357_info->probed = 0;
682
683         /* Enable FPEC CLK */
684         int retval = target_write_u32(target, EM357_FPEC_CLK, 0x00000001);
685         if (retval != ERROR_OK)
686                 return retval;
687
688         page_size = 2048;
689         em357_info->ppage_size = 4;
690         num_pages = 96;
691
692         LOG_INFO("flash size = %dkbytes", num_pages*page_size/1024);
693
694         if (bank->sectors) {
695                 free(bank->sectors);
696                 bank->sectors = NULL;
697         }
698
699         bank->base = base_address;
700         bank->size = (num_pages * page_size);
701         bank->num_sectors = num_pages;
702         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
703
704         for (i = 0; i < num_pages; i++) {
705                 bank->sectors[i].offset = i * page_size;
706                 bank->sectors[i].size = page_size;
707                 bank->sectors[i].is_erased = -1;
708                 bank->sectors[i].is_protected = 1;
709         }
710
711         em357_info->probed = 1;
712
713         return ERROR_OK;
714 }
715
716 static int em357_auto_probe(struct flash_bank *bank)
717 {
718         struct em357_flash_bank *em357_info = bank->driver_priv;
719         if (em357_info->probed)
720                 return ERROR_OK;
721         return em357_probe(bank);
722 }
723
724
725 static int get_em357_info(struct flash_bank *bank, char *buf, int buf_size)
726 {
727         snprintf(buf, buf_size, "em357\n");
728         return ERROR_OK;
729 }
730
731 COMMAND_HANDLER(em357_handle_lock_command)
732 {
733         struct target *target = NULL;
734         struct em357_flash_bank *em357_info = NULL;
735
736         if (CMD_ARGC < 1)
737                 return ERROR_COMMAND_SYNTAX_ERROR;
738
739         struct flash_bank *bank;
740         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
741         if (ERROR_OK != retval)
742                 return retval;
743
744         em357_info = bank->driver_priv;
745
746         target = bank->target;
747
748         if (target->state != TARGET_HALTED) {
749                 LOG_ERROR("Target not halted");
750                 return ERROR_TARGET_NOT_HALTED;
751         }
752
753         if (em357_erase_options(bank) != ERROR_OK) {
754                 command_print(CMD_CTX, "em357 failed to erase options");
755                 return ERROR_OK;
756         }
757
758         /* set readout protection */
759         em357_info->option_bytes.RDP = 0;
760
761         if (em357_write_options(bank) != ERROR_OK) {
762                 command_print(CMD_CTX, "em357 failed to lock device");
763                 return ERROR_OK;
764         }
765
766         command_print(CMD_CTX, "em357 locked");
767
768         return ERROR_OK;
769 }
770
771 COMMAND_HANDLER(em357_handle_unlock_command)
772 {
773         struct target *target = NULL;
774
775         if (CMD_ARGC < 1)
776                 return ERROR_COMMAND_SYNTAX_ERROR;
777
778         struct flash_bank *bank;
779         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
780         if (ERROR_OK != retval)
781                 return retval;
782
783         target = bank->target;
784
785         if (target->state != TARGET_HALTED) {
786                 LOG_ERROR("Target not halted");
787                 return ERROR_TARGET_NOT_HALTED;
788         }
789
790         if (em357_erase_options(bank) != ERROR_OK) {
791                 command_print(CMD_CTX, "em357 failed to unlock device");
792                 return ERROR_OK;
793         }
794
795         if (em357_write_options(bank) != ERROR_OK) {
796                 command_print(CMD_CTX, "em357 failed to lock device");
797                 return ERROR_OK;
798         }
799
800         command_print(CMD_CTX, "em357 unlocked.\n"
801                 "INFO: a reset or power cycle is required "
802                 "for the new settings to take effect.");
803
804         return ERROR_OK;
805 }
806
807 static int em357_mass_erase(struct flash_bank *bank)
808 {
809         struct target *target = bank->target;
810
811         if (target->state != TARGET_HALTED) {
812                 LOG_ERROR("Target not halted");
813                 return ERROR_TARGET_NOT_HALTED;
814         }
815
816         /* unlock option flash registers */
817         int retval = target_write_u32(target, EM357_FLASH_KEYR, KEY1);
818         if (retval != ERROR_OK)
819                 return retval;
820         retval = target_write_u32(target, EM357_FLASH_KEYR, KEY2);
821         if (retval != ERROR_OK)
822                 return retval;
823
824         /* mass erase flash memory */
825         retval = target_write_u32(target, EM357_FLASH_CR, FLASH_MER);
826         if (retval != ERROR_OK)
827                 return retval;
828         retval = target_write_u32(target, EM357_FLASH_CR, FLASH_MER | FLASH_STRT);
829         if (retval != ERROR_OK)
830                 return retval;
831
832         retval = em357_wait_status_busy(bank, 100);
833         if (retval != ERROR_OK)
834                 return retval;
835
836         retval = target_write_u32(target, EM357_FLASH_CR, FLASH_LOCK);
837         if (retval != ERROR_OK)
838                 return retval;
839
840         return ERROR_OK;
841 }
842
843 COMMAND_HANDLER(em357_handle_mass_erase_command)
844 {
845         int i;
846
847         if (CMD_ARGC < 1)
848                 return ERROR_COMMAND_SYNTAX_ERROR;
849
850         struct flash_bank *bank;
851         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
852         if (ERROR_OK != retval)
853                 return retval;
854
855         retval = em357_mass_erase(bank);
856         if (retval == ERROR_OK) {
857                 /* set all sectors as erased */
858                 for (i = 0; i < bank->num_sectors; i++)
859                         bank->sectors[i].is_erased = 1;
860
861                 command_print(CMD_CTX, "em357 mass erase complete");
862         } else
863                 command_print(CMD_CTX, "em357 mass erase failed");
864
865         return retval;
866 }
867
868 static const struct command_registration em357_exec_command_handlers[] = {
869         {
870                 .name = "lock",
871                 .usage = "<bank>",
872                 .handler = em357_handle_lock_command,
873                 .mode = COMMAND_EXEC,
874                 .help = "Lock entire flash device.",
875         },
876         {
877                 .name = "unlock",
878                 .usage = "<bank>",
879                 .handler = em357_handle_unlock_command,
880                 .mode = COMMAND_EXEC,
881                 .help = "Unlock entire protected flash device.",
882         },
883         {
884                 .name = "mass_erase",
885                 .usage = "<bank>",
886                 .handler = em357_handle_mass_erase_command,
887                 .mode = COMMAND_EXEC,
888                 .help = "Erase entire flash device.",
889         },
890         COMMAND_REGISTRATION_DONE
891 };
892
893 static const struct command_registration em357_command_handlers[] = {
894         {
895                 .name = "em357",
896                 .mode = COMMAND_ANY,
897                 .help = "em357 flash command group",
898                 .usage = "",
899                 .chain = em357_exec_command_handlers,
900         },
901         COMMAND_REGISTRATION_DONE
902 };
903
904 struct flash_driver em357_flash = {
905         .name = "em357",
906         .commands = em357_command_handlers,
907         .flash_bank_command = em357_flash_bank_command,
908         .erase = em357_erase,
909         .protect = em357_protect,
910         .write = em357_write,
911         .read = default_flash_read,
912         .probe = em357_probe,
913         .auto_probe = em357_auto_probe,
914         .erase_check = default_flash_blank_check,
915         .protect_check = em357_protect_check,
916         .info = get_em357_info,
917 };