Support for debug interface lock of EFM32 controllers
[fw/openocd] / src / flash / nor / efm32.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 Andreas Fritiofson                              *
9  *   andreas.fritiofson@gmail.com                                          *
10  *                                                                         *
11  *   Copyright (C) 2013 by Roman Dmitrienko                                *
12  *   me@iamroman.org                                                       *
13  *                                                                         *
14  *   Copyright (C) 2014 Nemui Trinomius                                    *
15  *   nemuisan_kawausogasuki@live.jp                                        *
16  *                                                                         *
17  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program.                                              *
29  ***************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include "imp.h"
36 #include <helper/binarybuffer.h>
37 #include <target/algorithm.h>
38 #include <target/armv7m.h>
39 #include <target/cortex_m.h>
40
41 /* keep family IDs in decimal */
42 #define EFM_FAMILY_ID_GECKO             71
43 #define EFM_FAMILY_ID_GIANT_GECKO       72
44 #define EFM_FAMILY_ID_TINY_GECKO        73
45 #define EFM_FAMILY_ID_LEOPARD_GECKO     74
46 #define EFM_FAMILY_ID_WONDER_GECKO      75
47 #define EFM_FAMILY_ID_ZERO_GECKO        76
48 #define EFM_FAMILY_ID_HAPPY_GECKO       77
49 #define EZR_FAMILY_ID_WONDER_GECKO              120
50 #define EZR_FAMILY_ID_LEOPARD_GECKO             121
51
52 #define EFM32_FLASH_ERASE_TMO           100
53 #define EFM32_FLASH_WDATAREADY_TMO      100
54 #define EFM32_FLASH_WRITE_TMO           100
55
56 /* size in bytes, not words; must fit all Gecko devices */
57 #define LOCKBITS_PAGE_SZ                512
58
59 #define EFM32_MSC_INFO_BASE             0x0fe00000
60
61 #define EFM32_MSC_USER_DATA             EFM32_MSC_INFO_BASE
62 #define EFM32_MSC_LOCK_BITS             (EFM32_MSC_INFO_BASE+0x4000)
63 #define EFM32_MSC_DEV_INFO              (EFM32_MSC_INFO_BASE+0x8000)
64
65 /* PAGE_SIZE is only present in Leopard, Giant and Wonder Gecko MCUs */
66 #define EFM32_MSC_DI_PAGE_SIZE          (EFM32_MSC_DEV_INFO+0x1e7)
67 #define EFM32_MSC_DI_FLASH_SZ           (EFM32_MSC_DEV_INFO+0x1f8)
68 #define EFM32_MSC_DI_RAM_SZ             (EFM32_MSC_DEV_INFO+0x1fa)
69 #define EFM32_MSC_DI_PART_NUM           (EFM32_MSC_DEV_INFO+0x1fc)
70 #define EFM32_MSC_DI_PART_FAMILY        (EFM32_MSC_DEV_INFO+0x1fe)
71 #define EFM32_MSC_DI_PROD_REV           (EFM32_MSC_DEV_INFO+0x1ff)
72
73 #define EFM32_MSC_REGBASE               0x400c0000
74 #define EFM32_MSC_WRITECTRL             (EFM32_MSC_REGBASE+0x008)
75 #define EFM32_MSC_WRITECTRL_WREN_MASK   0x1
76 #define EFM32_MSC_WRITECMD              (EFM32_MSC_REGBASE+0x00c)
77 #define EFM32_MSC_WRITECMD_LADDRIM_MASK 0x1
78 #define EFM32_MSC_WRITECMD_ERASEPAGE_MASK 0x2
79 #define EFM32_MSC_WRITECMD_WRITEONCE_MASK 0x8
80 #define EFM32_MSC_ADDRB                 (EFM32_MSC_REGBASE+0x010)
81 #define EFM32_MSC_WDATA                 (EFM32_MSC_REGBASE+0x018)
82 #define EFM32_MSC_STATUS                (EFM32_MSC_REGBASE+0x01c)
83 #define EFM32_MSC_STATUS_BUSY_MASK      0x1
84 #define EFM32_MSC_STATUS_LOCKED_MASK    0x2
85 #define EFM32_MSC_STATUS_INVADDR_MASK   0x4
86 #define EFM32_MSC_STATUS_WDATAREADY_MASK 0x8
87 #define EFM32_MSC_STATUS_WORDTIMEOUT_MASK 0x10
88 #define EFM32_MSC_STATUS_ERASEABORTED_MASK 0x20
89 #define EFM32_MSC_LOCK                  (EFM32_MSC_REGBASE+0x03c)
90 #define EFM32_MSC_LOCK_LOCKKEY          0x1b71
91
92 struct efm32x_flash_bank {
93         int probed;
94         uint32_t lb_page[LOCKBITS_PAGE_SZ/4];
95 };
96
97 struct efm32_info {
98         uint16_t flash_sz_kib;
99         uint16_t ram_sz_kib;
100         uint16_t part_num;
101         uint8_t part_family;
102         uint8_t prod_rev;
103         uint16_t page_size;
104 };
105
106 static int efm32x_write(struct flash_bank *bank, const uint8_t *buffer,
107         uint32_t offset, uint32_t count);
108
109 static int efm32x_get_flash_size(struct flash_bank *bank, uint16_t *flash_sz)
110 {
111         return target_read_u16(bank->target, EFM32_MSC_DI_FLASH_SZ, flash_sz);
112 }
113
114 static int efm32x_get_ram_size(struct flash_bank *bank, uint16_t *ram_sz)
115 {
116         return target_read_u16(bank->target, EFM32_MSC_DI_RAM_SZ, ram_sz);
117 }
118
119 static int efm32x_get_part_num(struct flash_bank *bank, uint16_t *pnum)
120 {
121         return target_read_u16(bank->target, EFM32_MSC_DI_PART_NUM, pnum);
122 }
123
124 static int efm32x_get_part_family(struct flash_bank *bank, uint8_t *pfamily)
125 {
126         return target_read_u8(bank->target, EFM32_MSC_DI_PART_FAMILY, pfamily);
127 }
128
129 static int efm32x_get_prod_rev(struct flash_bank *bank, uint8_t *prev)
130 {
131         return target_read_u8(bank->target, EFM32_MSC_DI_PROD_REV, prev);
132 }
133
134 static int efm32x_read_info(struct flash_bank *bank,
135         struct efm32_info *efm32_info)
136 {
137         int ret;
138         uint32_t cpuid = 0;
139
140         memset(efm32_info, 0, sizeof(struct efm32_info));
141
142         ret = target_read_u32(bank->target, CPUID, &cpuid);
143         if (ERROR_OK != ret)
144                 return ret;
145
146         if (((cpuid >> 4) & 0xfff) == 0xc23) {
147                 /* Cortex M3 device */
148         } else if (((cpuid >> 4) & 0xfff) == 0xc24) {
149                 /* Cortex M4 device(WONDER GECKO) */
150         } else if (((cpuid >> 4) & 0xfff) == 0xc60) {
151                 /* Cortex M0plus device */
152         } else {
153                 LOG_ERROR("Target is not Cortex-Mx Device");
154                 return ERROR_FAIL;
155         }
156
157         ret = efm32x_get_flash_size(bank, &(efm32_info->flash_sz_kib));
158         if (ERROR_OK != ret)
159                 return ret;
160
161         ret = efm32x_get_ram_size(bank, &(efm32_info->ram_sz_kib));
162         if (ERROR_OK != ret)
163                 return ret;
164
165         ret = efm32x_get_part_num(bank, &(efm32_info->part_num));
166         if (ERROR_OK != ret)
167                 return ret;
168
169         ret = efm32x_get_part_family(bank, &(efm32_info->part_family));
170         if (ERROR_OK != ret)
171                 return ret;
172
173         ret = efm32x_get_prod_rev(bank, &(efm32_info->prod_rev));
174         if (ERROR_OK != ret)
175                 return ret;
176
177         if (EFM_FAMILY_ID_GECKO == efm32_info->part_family ||
178                         EFM_FAMILY_ID_TINY_GECKO == efm32_info->part_family)
179                 efm32_info->page_size = 512;
180         else if (EFM_FAMILY_ID_ZERO_GECKO == efm32_info->part_family ||
181                         EFM_FAMILY_ID_HAPPY_GECKO == efm32_info->part_family)
182                 efm32_info->page_size = 1024;
183         else if (EFM_FAMILY_ID_GIANT_GECKO == efm32_info->part_family ||
184                         EFM_FAMILY_ID_LEOPARD_GECKO == efm32_info->part_family) {
185                 if (efm32_info->prod_rev >= 18) {
186                         uint8_t pg_size = 0;
187                         ret = target_read_u8(bank->target, EFM32_MSC_DI_PAGE_SIZE,
188                                 &pg_size);
189                         if (ERROR_OK != ret)
190                                 return ret;
191
192                         efm32_info->page_size = (1 << ((pg_size+10) & 0xff));
193                 } else {
194                         /* EFM32 GG/LG errata: MEM_INFO_PAGE_SIZE is invalid
195                            for MCUs with PROD_REV < 18 */
196                         if (efm32_info->flash_sz_kib < 512)
197                                 efm32_info->page_size = 2048;
198                         else
199                                 efm32_info->page_size = 4096;
200                 }
201
202                 if ((2048 != efm32_info->page_size) &&
203                                 (4096 != efm32_info->page_size)) {
204                         LOG_ERROR("Invalid page size %u", efm32_info->page_size);
205                         return ERROR_FAIL;
206                 }
207         } else if (EFM_FAMILY_ID_WONDER_GECKO == efm32_info->part_family ||
208                         EZR_FAMILY_ID_WONDER_GECKO == efm32_info->part_family ||
209                         EZR_FAMILY_ID_LEOPARD_GECKO == efm32_info->part_family) {
210                 uint8_t pg_size = 0;
211                 ret = target_read_u8(bank->target, EFM32_MSC_DI_PAGE_SIZE,
212                         &pg_size);
213                 if (ERROR_OK != ret)
214                         return ret;
215
216                 efm32_info->page_size = (1 << ((pg_size+10) & 0xff));
217                 if (2048 != efm32_info->page_size) {
218                         LOG_ERROR("Invalid page size %u", efm32_info->page_size);
219                         return ERROR_FAIL;
220                 }
221         } else {
222                 LOG_ERROR("Unknown MCU family %d", efm32_info->part_family);
223                 return ERROR_FAIL;
224         }
225
226         return ERROR_OK;
227 }
228
229 /*
230  * Helper to create a human friendly string describing a part
231  */
232 static int efm32x_decode_info(struct efm32_info *info, char *buf, int buf_size)
233 {
234         int printed = 0;
235
236         switch (info->part_family) {
237                 case EZR_FAMILY_ID_WONDER_GECKO:
238                 case EZR_FAMILY_ID_LEOPARD_GECKO:
239                         printed = snprintf(buf, buf_size, "EZR32 ");
240                         break;
241                 default:
242                         printed = snprintf(buf, buf_size, "EFM32 ");
243         }
244
245         buf += printed;
246         buf_size -= printed;
247
248         if (0 >= buf_size)
249                 return ERROR_BUF_TOO_SMALL;
250
251         switch (info->part_family) {
252                 case EFM_FAMILY_ID_GECKO:
253                         printed = snprintf(buf, buf_size, "Gecko");
254                         break;
255                 case EFM_FAMILY_ID_GIANT_GECKO:
256                         printed = snprintf(buf, buf_size, "Giant Gecko");
257                         break;
258                 case EFM_FAMILY_ID_TINY_GECKO:
259                         printed = snprintf(buf, buf_size, "Tiny Gecko");
260                         break;
261                 case EFM_FAMILY_ID_LEOPARD_GECKO:
262                 case EZR_FAMILY_ID_LEOPARD_GECKO:
263                         printed = snprintf(buf, buf_size, "Leopard Gecko");
264                         break;
265                 case EFM_FAMILY_ID_WONDER_GECKO:
266                 case EZR_FAMILY_ID_WONDER_GECKO:
267                         printed = snprintf(buf, buf_size, "Wonder Gecko");
268                         break;
269                 case EFM_FAMILY_ID_ZERO_GECKO:
270                         printed = snprintf(buf, buf_size, "Zero Gecko");
271                         break;
272                 case EFM_FAMILY_ID_HAPPY_GECKO:
273                         printed = snprintf(buf, buf_size, "Happy Gecko");
274                         break;
275         }
276
277         buf += printed;
278         buf_size -= printed;
279
280         if (0 >= buf_size)
281                 return ERROR_BUF_TOO_SMALL;
282
283         printed = snprintf(buf, buf_size, " - Rev: %d", info->prod_rev);
284         buf += printed;
285         buf_size -= printed;
286
287         if (0 >= buf_size)
288                 return ERROR_BUF_TOO_SMALL;
289
290         return ERROR_OK;
291 }
292
293 /* flash bank efm32 <base> <size> 0 0 <target#>
294  */
295 FLASH_BANK_COMMAND_HANDLER(efm32x_flash_bank_command)
296 {
297         struct efm32x_flash_bank *efm32x_info;
298
299         if (CMD_ARGC < 6)
300                 return ERROR_COMMAND_SYNTAX_ERROR;
301
302         efm32x_info = malloc(sizeof(struct efm32x_flash_bank));
303
304         bank->driver_priv = efm32x_info;
305         efm32x_info->probed = 0;
306         memset(efm32x_info->lb_page, 0xff, LOCKBITS_PAGE_SZ);
307
308         return ERROR_OK;
309 }
310
311 /* set or reset given bits in a register */
312 static int efm32x_set_reg_bits(struct flash_bank *bank, uint32_t reg,
313         uint32_t bitmask, int set)
314 {
315         int ret = 0;
316         uint32_t reg_val = 0;
317
318         ret = target_read_u32(bank->target, reg, &reg_val);
319         if (ERROR_OK != ret)
320                 return ret;
321
322         if (set)
323                 reg_val |= bitmask;
324         else
325                 reg_val &= ~bitmask;
326
327         return target_write_u32(bank->target, reg, reg_val);
328 }
329
330 static int efm32x_set_wren(struct flash_bank *bank, int write_enable)
331 {
332         return efm32x_set_reg_bits(bank, EFM32_MSC_WRITECTRL,
333                 EFM32_MSC_WRITECTRL_WREN_MASK, write_enable);
334 }
335
336 static int efm32x_msc_lock(struct flash_bank *bank, int lock)
337 {
338         return target_write_u32(bank->target, EFM32_MSC_LOCK,
339                 (lock ? 0 : EFM32_MSC_LOCK_LOCKKEY));
340 }
341
342 static int efm32x_wait_status(struct flash_bank *bank, int timeout,
343         uint32_t wait_mask, int wait_for_set)
344 {
345         int ret = 0;
346         uint32_t status = 0;
347
348         while (1) {
349                 ret = target_read_u32(bank->target, EFM32_MSC_STATUS, &status);
350                 if (ERROR_OK != ret)
351                         break;
352
353                 LOG_DEBUG("status: 0x%" PRIx32 "", status);
354
355                 if (((status & wait_mask) == 0) && (0 == wait_for_set))
356                         break;
357                 else if (((status & wait_mask) != 0) && wait_for_set)
358                         break;
359
360                 if (timeout-- <= 0) {
361                         LOG_ERROR("timed out waiting for MSC status");
362                         return ERROR_FAIL;
363                 }
364
365                 alive_sleep(1);
366         }
367
368         if (status & EFM32_MSC_STATUS_ERASEABORTED_MASK)
369                 LOG_WARNING("page erase was aborted");
370
371         return ret;
372 }
373
374 static int efm32x_erase_page(struct flash_bank *bank, uint32_t addr)
375 {
376         /* this function DOES NOT set WREN; must be set already */
377         /* 1. write address to ADDRB
378            2. write LADDRIM
379            3. check status (INVADDR, LOCKED)
380            4. write ERASEPAGE
381            5. wait until !STATUS_BUSY
382          */
383         int ret = 0;
384         uint32_t status = 0;
385
386         LOG_DEBUG("erasing flash page at 0x%08" PRIx32, addr);
387
388         ret = target_write_u32(bank->target, EFM32_MSC_ADDRB, addr);
389         if (ERROR_OK != ret)
390                 return ret;
391
392         ret = efm32x_set_reg_bits(bank, EFM32_MSC_WRITECMD,
393                 EFM32_MSC_WRITECMD_LADDRIM_MASK, 1);
394         if (ERROR_OK != ret)
395                 return ret;
396
397         ret = target_read_u32(bank->target, EFM32_MSC_STATUS, &status);
398         if (ERROR_OK != ret)
399                 return ret;
400
401         LOG_DEBUG("status 0x%" PRIx32, status);
402
403         if (status & EFM32_MSC_STATUS_LOCKED_MASK) {
404                 LOG_ERROR("Page is locked");
405                 return ERROR_FAIL;
406         } else if (status & EFM32_MSC_STATUS_INVADDR_MASK) {
407                 LOG_ERROR("Invalid address 0x%" PRIx32, addr);
408                 return ERROR_FAIL;
409         }
410
411         ret = efm32x_set_reg_bits(bank, EFM32_MSC_WRITECMD,
412                 EFM32_MSC_WRITECMD_ERASEPAGE_MASK, 1);
413         if (ERROR_OK != ret)
414                 return ret;
415
416         return efm32x_wait_status(bank, EFM32_FLASH_ERASE_TMO,
417                 EFM32_MSC_STATUS_BUSY_MASK, 0);
418 }
419
420 static int efm32x_erase(struct flash_bank *bank, int first, int last)
421 {
422         struct target *target = bank->target;
423         int i = 0;
424         int ret = 0;
425
426         if (TARGET_HALTED != target->state) {
427                 LOG_ERROR("Target not halted");
428                 return ERROR_TARGET_NOT_HALTED;
429         }
430
431         efm32x_msc_lock(bank, 0);
432         ret = efm32x_set_wren(bank, 1);
433         if (ERROR_OK != ret) {
434                 LOG_ERROR("Failed to enable MSC write");
435                 return ret;
436         }
437
438         for (i = first; i <= last; i++) {
439                 ret = efm32x_erase_page(bank, bank->sectors[i].offset);
440                 if (ERROR_OK != ret)
441                         LOG_ERROR("Failed to erase page %d", i);
442         }
443
444         ret = efm32x_set_wren(bank, 0);
445         efm32x_msc_lock(bank, 1);
446
447         return ret;
448 }
449
450 static int efm32x_read_lock_data(struct flash_bank *bank)
451 {
452         struct efm32x_flash_bank *efm32x_info = bank->driver_priv;
453         struct target *target = bank->target;
454         int i = 0;
455         int data_size = 0;
456         uint32_t *ptr = NULL;
457         int ret = 0;
458
459         assert(!(bank->num_sectors & 0x1f));
460
461         data_size = bank->num_sectors / 8; /* number of data bytes */
462         data_size /= 4; /* ...and data dwords */
463
464         ptr = efm32x_info->lb_page;
465
466         for (i = 0; i < data_size; i++, ptr++) {
467                 ret = target_read_u32(target, EFM32_MSC_LOCK_BITS+i*4, ptr);
468                 if (ERROR_OK != ret) {
469                         LOG_ERROR("Failed to read PLW %d", i);
470                         return ret;
471                 }
472         }
473
474         /* also, read ULW, DLW and MLW */
475
476         /* ULW, word 126 */
477         ptr = efm32x_info->lb_page + 126;
478         ret = target_read_u32(target, EFM32_MSC_LOCK_BITS+126*4, ptr);
479         if (ERROR_OK != ret) {
480                 LOG_ERROR("Failed to read ULW");
481                 return ret;
482         }
483
484         /* DLW, word 127 */
485         ptr = efm32x_info->lb_page + 127;
486         ret = target_read_u32(target, EFM32_MSC_LOCK_BITS+127*4, ptr);
487         if (ERROR_OK != ret) {
488                 LOG_ERROR("Failed to read DLW");
489                 return ret;
490         }
491
492         /* MLW, word 125, present in GG and LG */
493         ptr = efm32x_info->lb_page + 125;
494         ret = target_read_u32(target, EFM32_MSC_LOCK_BITS+125*4, ptr);
495         if (ERROR_OK != ret) {
496                 LOG_ERROR("Failed to read MLW");
497                 return ret;
498         }
499
500         return ERROR_OK;
501 }
502
503 static int efm32x_write_lock_data(struct flash_bank *bank)
504 {
505         struct efm32x_flash_bank *efm32x_info = bank->driver_priv;
506         int ret = 0;
507
508         ret = efm32x_erase_page(bank, EFM32_MSC_LOCK_BITS);
509         if (ERROR_OK != ret) {
510                 LOG_ERROR("Failed to erase LB page");
511                 return ret;
512         }
513
514         return efm32x_write(bank, (uint8_t *)efm32x_info->lb_page, EFM32_MSC_LOCK_BITS,
515                 LOCKBITS_PAGE_SZ);
516 }
517
518 static int efm32x_get_page_lock(struct flash_bank *bank, size_t page)
519 {
520         struct efm32x_flash_bank *efm32x_info = bank->driver_priv;
521         uint32_t dw = efm32x_info->lb_page[page >> 5];
522         uint32_t mask = 0;
523
524         mask = 1 << (page & 0x1f);
525
526         return (dw & mask) ? 0 : 1;
527 }
528
529 static int efm32x_set_page_lock(struct flash_bank *bank, size_t page, int set)
530 {
531         struct efm32x_flash_bank *efm32x_info = bank->driver_priv;
532         uint32_t *dw = &efm32x_info->lb_page[page >> 5];
533         uint32_t mask = 0;
534
535         mask = 1 << (page & 0x1f);
536
537         if (!set)
538                 *dw |= mask;
539         else
540                 *dw &= ~mask;
541
542         return ERROR_OK;
543 }
544
545 static int efm32x_protect(struct flash_bank *bank, int set, int first, int last)
546 {
547         struct target *target = bank->target;
548         int i = 0;
549         int ret = 0;
550
551         if (!set) {
552                 LOG_ERROR("Erase device data to reset page locks");
553                 return ERROR_FAIL;
554         }
555
556         if (target->state != TARGET_HALTED) {
557                 LOG_ERROR("Target not halted");
558                 return ERROR_TARGET_NOT_HALTED;
559         }
560
561         for (i = first; i <= last; i++) {
562                 ret = efm32x_set_page_lock(bank, i, set);
563                 if (ERROR_OK != ret) {
564                         LOG_ERROR("Failed to set lock on page %d", i);
565                         return ret;
566                 }
567         }
568
569         ret = efm32x_write_lock_data(bank);
570         if (ERROR_OK != ret) {
571                 LOG_ERROR("Failed to write LB page");
572                 return ret;
573         }
574
575         return ERROR_OK;
576 }
577
578 static int efm32x_write_block(struct flash_bank *bank, const uint8_t *buf,
579         uint32_t offset, uint32_t count)
580 {
581         struct target *target = bank->target;
582         uint32_t buffer_size = 16384;
583         struct working_area *write_algorithm;
584         struct working_area *source;
585         uint32_t address = bank->base + offset;
586         struct reg_param reg_params[5];
587         struct armv7m_algorithm armv7m_info;
588         int ret = ERROR_OK;
589
590         /* see contrib/loaders/flash/efm32.S for src */
591         static const uint8_t efm32x_flash_write_code[] = {
592                 /* #define EFM32_MSC_WRITECTRL_OFFSET      0x008 */
593                 /* #define EFM32_MSC_WRITECMD_OFFSET       0x00c */
594                 /* #define EFM32_MSC_ADDRB_OFFSET          0x010 */
595                 /* #define EFM32_MSC_WDATA_OFFSET          0x018 */
596                 /* #define EFM32_MSC_STATUS_OFFSET         0x01c */
597                 /* #define EFM32_MSC_LOCK_OFFSET           0x03c */
598
599                         0x15, 0x4e,    /* ldr     r6, =#0x1b71 */
600                         0xc6, 0x63,    /* str     r6, [r0, #EFM32_MSC_LOCK_OFFSET] */
601                         0x01, 0x26,    /* movs    r6, #1 */
602                         0x86, 0x60,    /* str     r6, [r0, #EFM32_MSC_WRITECTRL_OFFSET] */
603
604                 /* wait_fifo: */
605                         0x16, 0x68,    /* ldr     r6, [r2, #0] */
606                         0x00, 0x2e,    /* cmp     r6, #0 */
607                         0x22, 0xd0,    /* beq     exit */
608                         0x55, 0x68,    /* ldr     r5, [r2, #4] */
609                         0xb5, 0x42,    /* cmp     r5, r6 */
610                         0xf9, 0xd0,    /* beq     wait_fifo */
611
612                         0x04, 0x61,    /* str     r4, [r0, #EFM32_MSC_ADDRB_OFFSET] */
613                         0x01, 0x26,    /* movs    r6, #1 */
614                         0xc6, 0x60,    /* str     r6, [r0, #EFM32_MSC_WRITECMD_OFFSET] */
615                         0xc6, 0x69,    /* ldr     r6, [r0, #EFM32_MSC_STATUS_OFFSET] */
616                         0x06, 0x27,    /* movs    r7, #6 */
617                         0x3e, 0x42,    /* tst     r6, r7 */
618                         0x16, 0xd1,    /* bne     error */
619
620                 /* wait_wdataready: */
621                         0xc6, 0x69,    /* ldr     r6, [r0, #EFM32_MSC_STATUS_OFFSET] */
622                         0x08, 0x27,    /* movs    r7, #8 */
623                         0x3e, 0x42,    /* tst     r6, r7 */
624                         0xfb, 0xd0,    /* beq     wait_wdataready */
625
626                         0x2e, 0x68,    /* ldr     r6, [r5] */
627                         0x86, 0x61,    /* str     r6, [r0, #EFM32_MSC_WDATA_OFFSET] */
628                         0x08, 0x26,    /* movs    r6, #8 */
629                         0xc6, 0x60,    /* str     r6, [r0, #EFM32_MSC_WRITECMD_OFFSET] */
630
631                         0x04, 0x35,    /* adds    r5, #4 */
632                         0x04, 0x34,    /* adds    r4, #4 */
633
634                 /* busy: */
635                         0xc6, 0x69,    /* ldr     r6, [r0, #EFM32_MSC_STATUS_OFFSET] */
636                         0x01, 0x27,    /* movs    r7, #1 */
637                         0x3e, 0x42,    /* tst     r6, r7 */
638                         0xfb, 0xd1,    /* bne     busy */
639
640                         0x9d, 0x42,    /* cmp     r5, r3 */
641                         0x01, 0xd3,    /* bcc     no_wrap */
642                         0x15, 0x46,    /* mov     r5, r2 */
643                         0x08, 0x35,    /* adds    r5, #8 */
644
645                 /* no_wrap: */
646                         0x55, 0x60,    /* str     r5, [r2, #4] */
647                         0x01, 0x39,    /* subs    r1, r1, #1 */
648                         0x00, 0x29,    /* cmp     r1, #0 */
649                         0x02, 0xd0,    /* beq     exit */
650                         0xdb, 0xe7,    /* b       wait_fifo */
651
652                 /* error: */
653                         0x00, 0x20,    /* movs    r0, #0 */
654                         0x50, 0x60,    /* str     r0, [r2, #4] */
655
656                 /* exit: */
657                         0x30, 0x46,    /* mov     r0, r6 */
658                         0x00, 0xbe,    /* bkpt    #0 */
659
660                 /* LOCKKEY */
661                         0x71, 0x1b, 0x00, 0x00
662         };
663
664         /* flash write code */
665         if (target_alloc_working_area(target, sizeof(efm32x_flash_write_code),
666                         &write_algorithm) != ERROR_OK) {
667                 LOG_WARNING("no working area available, can't do block memory writes");
668                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
669         }
670
671         ret = target_write_buffer(target, write_algorithm->address,
672                         sizeof(efm32x_flash_write_code), efm32x_flash_write_code);
673         if (ret != ERROR_OK)
674                 return ret;
675
676         /* memory buffer */
677         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) {
678                 buffer_size /= 2;
679                 buffer_size &= ~3UL; /* Make sure it's 4 byte aligned */
680                 if (buffer_size <= 256) {
681                         /* we already allocated the writing code, but failed to get a
682                          * buffer, free the algorithm */
683                         target_free_working_area(target, write_algorithm);
684
685                         LOG_WARNING("no large enough working area available, can't do block memory writes");
686                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
687                 }
688         }
689
690         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* flash base (in), status (out) */
691         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* count (word-32bit) */
692         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* buffer start */
693         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);    /* buffer end */
694         init_reg_param(&reg_params[4], "r4", 32, PARAM_IN_OUT); /* target address */
695
696         buf_set_u32(reg_params[0].value, 0, 32, EFM32_MSC_REGBASE);
697         buf_set_u32(reg_params[1].value, 0, 32, count);
698         buf_set_u32(reg_params[2].value, 0, 32, source->address);
699         buf_set_u32(reg_params[3].value, 0, 32, source->address + source->size);
700         buf_set_u32(reg_params[4].value, 0, 32, address);
701
702         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
703         armv7m_info.core_mode = ARM_MODE_THREAD;
704
705         ret = target_run_flash_async_algorithm(target, buf, count, 4,
706                         0, NULL,
707                         5, reg_params,
708                         source->address, source->size,
709                         write_algorithm->address, 0,
710                         &armv7m_info);
711
712         if (ret == ERROR_FLASH_OPERATION_FAILED) {
713                 LOG_ERROR("flash write failed at address 0x%"PRIx32,
714                                 buf_get_u32(reg_params[4].value, 0, 32));
715
716                 if (buf_get_u32(reg_params[0].value, 0, 32) &
717                                 EFM32_MSC_STATUS_LOCKED_MASK) {
718                         LOG_ERROR("flash memory write protected");
719                 }
720
721                 if (buf_get_u32(reg_params[0].value, 0, 32) &
722                                 EFM32_MSC_STATUS_INVADDR_MASK) {
723                         LOG_ERROR("invalid flash memory write address");
724                 }
725         }
726
727         target_free_working_area(target, source);
728         target_free_working_area(target, write_algorithm);
729
730         destroy_reg_param(&reg_params[0]);
731         destroy_reg_param(&reg_params[1]);
732         destroy_reg_param(&reg_params[2]);
733         destroy_reg_param(&reg_params[3]);
734         destroy_reg_param(&reg_params[4]);
735
736         return ret;
737 }
738
739 static int efm32x_write_word(struct flash_bank *bank, uint32_t addr,
740         uint32_t val)
741 {
742         /* this function DOES NOT set WREN; must be set already */
743         /* 1. write address to ADDRB
744            2. write LADDRIM
745            3. check status (INVADDR, LOCKED)
746            4. wait for WDATAREADY
747            5. write data to WDATA
748            6. write WRITECMD_WRITEONCE to WRITECMD
749            7. wait until !STATUS_BUSY
750          */
751
752         /* FIXME: EFM32G ref states (7.3.2) that writes should be
753          * performed twice per dword */
754
755         int ret = 0;
756         uint32_t status = 0;
757
758         /* if not called, GDB errors will be reported during large writes */
759         keep_alive();
760
761         ret = target_write_u32(bank->target, EFM32_MSC_ADDRB, addr);
762         if (ERROR_OK != ret)
763                 return ret;
764
765         ret = efm32x_set_reg_bits(bank, EFM32_MSC_WRITECMD,
766                 EFM32_MSC_WRITECMD_LADDRIM_MASK, 1);
767         if (ERROR_OK != ret)
768                 return ret;
769
770         ret = target_read_u32(bank->target, EFM32_MSC_STATUS, &status);
771         if (ERROR_OK != ret)
772                 return ret;
773
774         LOG_DEBUG("status 0x%" PRIx32, status);
775
776         if (status & EFM32_MSC_STATUS_LOCKED_MASK) {
777                 LOG_ERROR("Page is locked");
778                 return ERROR_FAIL;
779         } else if (status & EFM32_MSC_STATUS_INVADDR_MASK) {
780                 LOG_ERROR("Invalid address 0x%" PRIx32, addr);
781                 return ERROR_FAIL;
782         }
783
784         ret = efm32x_wait_status(bank, EFM32_FLASH_WDATAREADY_TMO,
785                 EFM32_MSC_STATUS_WDATAREADY_MASK, 1);
786         if (ERROR_OK != ret) {
787                 LOG_ERROR("Wait for WDATAREADY failed");
788                 return ret;
789         }
790
791         ret = target_write_u32(bank->target, EFM32_MSC_WDATA, val);
792         if (ERROR_OK != ret) {
793                 LOG_ERROR("WDATA write failed");
794                 return ret;
795         }
796
797         ret = target_write_u32(bank->target, EFM32_MSC_WRITECMD,
798                 EFM32_MSC_WRITECMD_WRITEONCE_MASK);
799         if (ERROR_OK != ret) {
800                 LOG_ERROR("WRITECMD write failed");
801                 return ret;
802         }
803
804         ret = efm32x_wait_status(bank, EFM32_FLASH_WRITE_TMO,
805                 EFM32_MSC_STATUS_BUSY_MASK, 0);
806         if (ERROR_OK != ret) {
807                 LOG_ERROR("Wait for BUSY failed");
808                 return ret;
809         }
810
811         return ERROR_OK;
812 }
813
814 static int efm32x_write(struct flash_bank *bank, const uint8_t *buffer,
815                 uint32_t offset, uint32_t count)
816 {
817         struct target *target = bank->target;
818         uint8_t *new_buffer = NULL;
819
820         if (target->state != TARGET_HALTED) {
821                 LOG_ERROR("Target not halted");
822                 return ERROR_TARGET_NOT_HALTED;
823         }
824
825         if (offset & 0x3) {
826                 LOG_ERROR("offset 0x%" PRIx32 " breaks required 4-byte "
827                         "alignment", offset);
828                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
829         }
830
831         if (count & 0x3) {
832                 uint32_t old_count = count;
833                 count = (old_count | 3) + 1;
834                 new_buffer = malloc(count);
835                 if (new_buffer == NULL) {
836                         LOG_ERROR("odd number of bytes to write and no memory "
837                                 "for padding buffer");
838                         return ERROR_FAIL;
839                 }
840                 LOG_INFO("odd number of bytes to write (%" PRIu32 "), extending to %" PRIu32 " "
841                         "and padding with 0xff", old_count, count);
842                 memset(new_buffer, 0xff, count);
843                 buffer = memcpy(new_buffer, buffer, old_count);
844         }
845
846         uint32_t words_remaining = count / 4;
847         int retval, retval2;
848
849         /* unlock flash registers */
850         efm32x_msc_lock(bank, 0);
851         retval = efm32x_set_wren(bank, 1);
852         if (retval != ERROR_OK)
853                 goto cleanup;
854
855         /* try using a block write */
856         retval = efm32x_write_block(bank, buffer, offset, words_remaining);
857
858         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
859                 /* if block write failed (no sufficient working area),
860                  * we use normal (slow) single word accesses */
861                 LOG_WARNING("couldn't use block writes, falling back to single "
862                         "memory accesses");
863
864                 while (words_remaining > 0) {
865                         uint32_t value;
866                         memcpy(&value, buffer, sizeof(uint32_t));
867
868                         retval = efm32x_write_word(bank, offset, value);
869                         if (retval != ERROR_OK)
870                                 goto reset_pg_and_lock;
871
872                         words_remaining--;
873                         buffer += 4;
874                         offset += 4;
875                 }
876         }
877
878 reset_pg_and_lock:
879         retval2 = efm32x_set_wren(bank, 0);
880         efm32x_msc_lock(bank, 1);
881         if (retval == ERROR_OK)
882                 retval = retval2;
883
884 cleanup:
885         if (new_buffer)
886                 free(new_buffer);
887
888         return retval;
889 }
890
891 static int efm32x_probe(struct flash_bank *bank)
892 {
893         struct efm32x_flash_bank *efm32x_info = bank->driver_priv;
894         struct efm32_info efm32_mcu_info;
895         int ret;
896         int i;
897         uint32_t base_address = 0x00000000;
898         char buf[256];
899
900         efm32x_info->probed = 0;
901         memset(efm32x_info->lb_page, 0xff, LOCKBITS_PAGE_SZ);
902
903         ret = efm32x_read_info(bank, &efm32_mcu_info);
904         if (ERROR_OK != ret)
905                 return ret;
906
907         ret = efm32x_decode_info(&efm32_mcu_info, buf, sizeof(buf));
908         if (ERROR_OK != ret)
909                 return ret;
910
911         LOG_INFO("detected part: %s", buf);
912         LOG_INFO("flash size = %dkbytes", efm32_mcu_info.flash_sz_kib);
913         LOG_INFO("flash page size = %dbytes", efm32_mcu_info.page_size);
914
915         assert(0 != efm32_mcu_info.page_size);
916
917         int num_pages = efm32_mcu_info.flash_sz_kib * 1024 /
918                 efm32_mcu_info.page_size;
919
920         assert(num_pages > 0);
921
922         if (bank->sectors) {
923                 free(bank->sectors);
924                 bank->sectors = NULL;
925         }
926
927         bank->base = base_address;
928         bank->size = (num_pages * efm32_mcu_info.page_size);
929         bank->num_sectors = num_pages;
930
931         ret = efm32x_read_lock_data(bank);
932         if (ERROR_OK != ret) {
933                 LOG_ERROR("Failed to read LB data");
934                 return ret;
935         }
936
937         bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
938
939         for (i = 0; i < num_pages; i++) {
940                 bank->sectors[i].offset = i * efm32_mcu_info.page_size;
941                 bank->sectors[i].size = efm32_mcu_info.page_size;
942                 bank->sectors[i].is_erased = -1;
943                 bank->sectors[i].is_protected = 1;
944         }
945
946         efm32x_info->probed = 1;
947
948         return ERROR_OK;
949 }
950
951 static int efm32x_auto_probe(struct flash_bank *bank)
952 {
953         struct efm32x_flash_bank *efm32x_info = bank->driver_priv;
954         if (efm32x_info->probed)
955                 return ERROR_OK;
956         return efm32x_probe(bank);
957 }
958
959 static int efm32x_protect_check(struct flash_bank *bank)
960 {
961         struct target *target = bank->target;
962         int ret = 0;
963         int i = 0;
964
965         if (target->state != TARGET_HALTED) {
966                 LOG_ERROR("Target not halted");
967                 return ERROR_TARGET_NOT_HALTED;
968         }
969
970         ret = efm32x_read_lock_data(bank);
971         if (ERROR_OK != ret) {
972                 LOG_ERROR("Failed to read LB data");
973                 return ret;
974         }
975
976         assert(NULL != bank->sectors);
977
978         for (i = 0; i < bank->num_sectors; i++)
979                 bank->sectors[i].is_protected = efm32x_get_page_lock(bank, i);
980
981         return ERROR_OK;
982 }
983
984 static int get_efm32x_info(struct flash_bank *bank, char *buf, int buf_size)
985 {
986         struct efm32_info info;
987         int ret = 0;
988
989         ret = efm32x_read_info(bank, &info);
990         if (ERROR_OK != ret) {
991                 LOG_ERROR("Failed to read EFM32 info");
992                 return ret;
993         }
994
995         return efm32x_decode_info(&info, buf, buf_size);
996 }
997
998 COMMAND_HANDLER(efm32x_handle_debuglock_command)
999 {
1000         struct target *target = NULL;
1001
1002         if (CMD_ARGC < 1)
1003                 return ERROR_COMMAND_SYNTAX_ERROR;
1004
1005         struct flash_bank *bank;
1006         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1007         if (ERROR_OK != retval)
1008                 return retval;
1009
1010         struct efm32x_flash_bank *efm32x_info = bank->driver_priv;
1011
1012         target = bank->target;
1013
1014         if (target->state != TARGET_HALTED) {
1015                 LOG_ERROR("Target not halted");
1016                 return ERROR_TARGET_NOT_HALTED;
1017         }
1018
1019         uint32_t *ptr;
1020         ptr = efm32x_info->lb_page + 127;
1021         *ptr = 0;
1022
1023         retval = efm32x_write_lock_data(bank);
1024         if (ERROR_OK != retval) {
1025                 LOG_ERROR("Failed to write LB page");
1026                 return retval;
1027         }
1028
1029         command_print(CMD_CTX, "efm32x debug interface locked, reset the device to apply");
1030
1031         return ERROR_OK;
1032 }
1033
1034 static const struct command_registration efm32x_exec_command_handlers[] = {
1035         {
1036                 .name = "debuglock",
1037                 .handler = efm32x_handle_debuglock_command,
1038                 .mode = COMMAND_EXEC,
1039                 .usage = "bank_id",
1040                 .help = "Lock the debug interface of the device.",
1041         },
1042         COMMAND_REGISTRATION_DONE
1043 };
1044
1045 static const struct command_registration efm32x_command_handlers[] = {
1046         {
1047                 .name = "efm32",
1048                 .mode = COMMAND_ANY,
1049                 .help = "efm32 flash command group",
1050                 .usage = "",
1051                 .chain = efm32x_exec_command_handlers,
1052         },
1053         COMMAND_REGISTRATION_DONE
1054 };
1055
1056 struct flash_driver efm32_flash = {
1057         .name = "efm32",
1058         .commands = efm32x_command_handlers,
1059         .flash_bank_command = efm32x_flash_bank_command,
1060         .erase = efm32x_erase,
1061         .protect = efm32x_protect,
1062         .write = efm32x_write,
1063         .read = default_flash_read,
1064         .probe = efm32x_probe,
1065         .auto_probe = efm32x_auto_probe,
1066         .erase_check = default_flash_blank_check,
1067         .protect_check = efm32x_protect_check,
1068         .info = get_efm32x_info,
1069 };