nrf51 - Add async loader. Performance on nrf51822QAA/stlink-v2 from ~3.5KiB/s to...
[fw/openocd] / src / flash / nor / nrf51.c
1 /***************************************************************************
2  *   Copyright (C) 2013 Synapse Product Development                        *
3  *   Andrey Smirnov <andrew.smironv@gmail.com>                             *
4  *   Angus Gratton <gus@projectgus.com>                                    *
5  *   Erdem U. Altunyurt <spamjunkeater@gmail.com>                          *
6  *                                                                         *
7  *   This program is free software; you can redistribute it and/or modify  *
8  *   it under the terms of the GNU General Public License as published by  *
9  *   the Free Software Foundation; either version 2 of the License, or     *
10  *   (at your option) any later version.                                   *
11  *                                                                         *
12  *   This program is distributed in the hope that it will be useful,       *
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
15  *   GNU General Public License for more details.                          *
16  *                                                                         *
17  *   You should have received a copy of the GNU General Public License     *
18  *   along with this program; if not, write to the                         *
19  *   Free Software Foundation, Inc.,                                       *
20  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
21  ***************************************************************************/
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include "imp.h"
28 #include <target/algorithm.h>
29 #include <target/armv7m.h>
30 #include <helper/types.h>
31
32 enum {
33         NRF51_FLASH_BASE = 0x00000000,
34 };
35
36 enum nrf51_ficr_registers {
37         NRF51_FICR_BASE = 0x10000000, /* Factory Information Configuration Registers */
38
39 #define NRF51_FICR_REG(offset) (NRF51_FICR_BASE + offset)
40
41         NRF51_FICR_CODEPAGESIZE         = NRF51_FICR_REG(0x010),
42         NRF51_FICR_CODESIZE             = NRF51_FICR_REG(0x014),
43         NRF51_FICR_CLENR0               = NRF51_FICR_REG(0x028),
44         NRF51_FICR_PPFC                 = NRF51_FICR_REG(0x02C),
45         NRF51_FICR_NUMRAMBLOCK          = NRF51_FICR_REG(0x034),
46         NRF51_FICR_SIZERAMBLOCK0        = NRF51_FICR_REG(0x038),
47         NRF51_FICR_SIZERAMBLOCK1        = NRF51_FICR_REG(0x03C),
48         NRF51_FICR_SIZERAMBLOCK2        = NRF51_FICR_REG(0x040),
49         NRF51_FICR_SIZERAMBLOCK3        = NRF51_FICR_REG(0x044),
50         NRF51_FICR_CONFIGID             = NRF51_FICR_REG(0x05C),
51         NRF51_FICR_DEVICEID0            = NRF51_FICR_REG(0x060),
52         NRF51_FICR_DEVICEID1            = NRF51_FICR_REG(0x064),
53         NRF51_FICR_ER0                  = NRF51_FICR_REG(0x080),
54         NRF51_FICR_ER1                  = NRF51_FICR_REG(0x084),
55         NRF51_FICR_ER2                  = NRF51_FICR_REG(0x088),
56         NRF51_FICR_ER3                  = NRF51_FICR_REG(0x08C),
57         NRF51_FICR_IR0                  = NRF51_FICR_REG(0x090),
58         NRF51_FICR_IR1                  = NRF51_FICR_REG(0x094),
59         NRF51_FICR_IR2                  = NRF51_FICR_REG(0x098),
60         NRF51_FICR_IR3                  = NRF51_FICR_REG(0x09C),
61         NRF51_FICR_DEVICEADDRTYPE       = NRF51_FICR_REG(0x0A0),
62         NRF51_FICR_DEVICEADDR0          = NRF51_FICR_REG(0x0A4),
63         NRF51_FICR_DEVICEADDR1          = NRF51_FICR_REG(0x0A8),
64         NRF51_FICR_OVERRIDEN            = NRF51_FICR_REG(0x0AC),
65         NRF51_FICR_NRF_1MBIT0           = NRF51_FICR_REG(0x0B0),
66         NRF51_FICR_NRF_1MBIT1           = NRF51_FICR_REG(0x0B4),
67         NRF51_FICR_NRF_1MBIT2           = NRF51_FICR_REG(0x0B8),
68         NRF51_FICR_NRF_1MBIT3           = NRF51_FICR_REG(0x0BC),
69         NRF51_FICR_NRF_1MBIT4           = NRF51_FICR_REG(0x0C0),
70         NRF51_FICR_BLE_1MBIT0           = NRF51_FICR_REG(0x0EC),
71         NRF51_FICR_BLE_1MBIT1           = NRF51_FICR_REG(0x0F0),
72         NRF51_FICR_BLE_1MBIT2           = NRF51_FICR_REG(0x0F4),
73         NRF51_FICR_BLE_1MBIT3           = NRF51_FICR_REG(0x0F8),
74         NRF51_FICR_BLE_1MBIT4           = NRF51_FICR_REG(0x0FC),
75 };
76
77 enum nrf51_uicr_registers {
78         NRF51_UICR_BASE = 0x10001000, /* User Information
79                                        * Configuration Regsters */
80
81         NRF51_UICR_SIZE = 0x100,
82
83 #define NRF51_UICR_REG(offset) (NRF51_UICR_BASE + offset)
84
85         NRF51_UICR_CLENR0       = NRF51_UICR_REG(0x000),
86         NRF51_UICR_RBPCONF      = NRF51_UICR_REG(0x004),
87         NRF51_UICR_XTALFREQ     = NRF51_UICR_REG(0x008),
88         NRF51_UICR_FWID         = NRF51_UICR_REG(0x010),
89 };
90
91 enum nrf51_nvmc_registers {
92         NRF51_NVMC_BASE = 0x4001E000, /* Non-Volatile Memory
93                                        * Controller Regsters */
94
95 #define NRF51_NVMC_REG(offset) (NRF51_NVMC_BASE + offset)
96
97         NRF51_NVMC_READY        = NRF51_NVMC_REG(0x400),
98         NRF51_NVMC_CONFIG       = NRF51_NVMC_REG(0x504),
99         NRF51_NVMC_ERASEPAGE    = NRF51_NVMC_REG(0x508),
100         NRF51_NVMC_ERASEALL     = NRF51_NVMC_REG(0x50C),
101         NRF51_NVMC_ERASEUICR    = NRF51_NVMC_REG(0x514),
102 };
103
104 enum nrf51_nvmc_config_bits {
105         NRF51_NVMC_CONFIG_REN = 0x00,
106         NRF51_NVMC_CONFIG_WEN = 0x01,
107         NRF51_NVMC_CONFIG_EEN = 0x02,
108
109 };
110
111 struct nrf51_info {
112         uint32_t code_page_size;
113         uint32_t code_memory_size;
114
115         struct {
116                 bool probed;
117                 int (*write) (struct flash_bank *bank,
118                               struct nrf51_info *chip,
119                               const uint8_t *buffer, uint32_t offset, uint32_t count);
120         } bank[2];
121         struct target *target;
122 };
123
124 struct nrf51_device_spec {
125         uint16_t hwid;
126         const char *variant;
127         const char *build_code;
128         unsigned int flash_size_kb;
129 };
130
131 static const struct nrf51_device_spec nrf51_known_devices_table[] = {
132         {
133                 .hwid           = 0x001D,
134                 .variant        = "QFAA",
135                 .build_code     = "CA/C0",
136                 .flash_size_kb  = 256,
137         },
138         {
139                 .hwid           = 0x002A,
140                 .variant        = "QFAA",
141                 .build_code     = "FA",
142                 .flash_size_kb  = 256,
143         },
144         {
145                 .hwid           = 0x0044,
146                 .variant        = "QFAA",
147                 .build_code     = "GC",
148                 .flash_size_kb  = 256,
149         },
150         {
151                 .hwid           = 0x003C,
152                 .variant        = "QFAA",
153                 .build_code     = "G0",
154                 .flash_size_kb  = 256,
155         },
156
157         {
158                 .hwid           = 0x0020,
159                 .variant        = "CEAA",
160                 .build_code     = "BA",
161                 .flash_size_kb  = 256,
162         },
163         {
164                 .hwid           = 0x002F,
165                 .variant        = "CEAA",
166                 .build_code     = "B0",
167                 .flash_size_kb  = 256,
168         },
169         {
170                 .hwid           = 0x0040,
171                 .variant        = "CEAA",
172                 .build_code     = "CA",
173                 .flash_size_kb  = 256,
174         },
175         {
176                 .hwid           = 0x0047,
177                 .variant        = "CEAA",
178                 .build_code     = "DA",
179                 .flash_size_kb  = 256,
180         },
181         {
182                 .hwid           = 0x004D,
183                 .variant        = "CEAA",
184                 .build_code     = "D0",
185                 .flash_size_kb  = 256,
186         },
187
188         {
189                 .hwid           = 0x0026,
190                 .variant        = "QFAB",
191                 .build_code     = "AA",
192                 .flash_size_kb  = 128,
193         },
194         {
195                 .hwid           = 0x0027,
196                 .variant        = "QFAB",
197                 .build_code     = "A0",
198                 .flash_size_kb  = 128,
199         },
200         {
201                 .hwid           = 0x004C,
202                 .variant        = "QFAB",
203                 .build_code     = "B0",
204                 .flash_size_kb  = 128,
205         },
206
207 };
208
209 static int nrf51_bank_is_probed(struct flash_bank *bank)
210 {
211         struct nrf51_info *chip = bank->driver_priv;
212
213         assert(chip != NULL);
214
215         return chip->bank[bank->bank_number].probed;
216 }
217 static int nrf51_probe(struct flash_bank *bank);
218
219 static int nrf51_get_probed_chip_if_halted(struct flash_bank *bank, struct nrf51_info **chip)
220 {
221         if (bank->target->state != TARGET_HALTED) {
222                 LOG_ERROR("Target not halted");
223                 return ERROR_TARGET_NOT_HALTED;
224         }
225
226         *chip = bank->driver_priv;
227
228         int probed = nrf51_bank_is_probed(bank);
229         if (probed < 0)
230                 return probed;
231         else if (!probed)
232                 return nrf51_probe(bank);
233         else
234                 return ERROR_OK;
235 }
236
237 static int nrf51_wait_for_nvmc(struct nrf51_info *chip)
238 {
239         uint32_t ready;
240         int res;
241         int timeout = 100;
242
243         do {
244                 res = target_read_u32(chip->target, NRF51_NVMC_READY, &ready);
245                 if (res != ERROR_OK) {
246                         LOG_ERROR("Couldn't read NVMC_READY register");
247                         return res;
248                 }
249
250                 if (ready == 0x00000001)
251                         return ERROR_OK;
252
253                 alive_sleep(1);
254         } while (timeout--);
255
256         LOG_DEBUG("Timed out waiting for NVMC_READY");
257         return ERROR_FLASH_BUSY;
258 }
259
260 static int nrf51_nvmc_erase_enable(struct nrf51_info *chip)
261 {
262         int res;
263         res = target_write_u32(chip->target,
264                                NRF51_NVMC_CONFIG,
265                                NRF51_NVMC_CONFIG_EEN);
266
267         if (res != ERROR_OK) {
268                 LOG_ERROR("Failed to enable erase operation");
269                 return res;
270         }
271
272         /*
273           According to NVMC examples in Nordic SDK busy status must be
274           checked after writing to NVMC_CONFIG
275          */
276         res = nrf51_wait_for_nvmc(chip);
277         if (res != ERROR_OK)
278                 LOG_ERROR("Erase enable did not complete");
279
280         return res;
281 }
282
283 static int nrf51_nvmc_write_enable(struct nrf51_info *chip)
284 {
285         int res;
286         res = target_write_u32(chip->target,
287                                NRF51_NVMC_CONFIG,
288                                NRF51_NVMC_CONFIG_WEN);
289
290         if (res != ERROR_OK) {
291                 LOG_ERROR("Failed to enable write operation");
292                 return res;
293         }
294
295         /*
296           According to NVMC examples in Nordic SDK busy status must be
297           checked after writing to NVMC_CONFIG
298          */
299         res = nrf51_wait_for_nvmc(chip);
300         if (res != ERROR_OK)
301                 LOG_ERROR("Write enable did not complete");
302
303         return res;
304 }
305
306 static int nrf51_nvmc_read_only(struct nrf51_info *chip)
307 {
308         int res;
309         res = target_write_u32(chip->target,
310                                NRF51_NVMC_CONFIG,
311                                NRF51_NVMC_CONFIG_REN);
312
313         if (res != ERROR_OK) {
314                 LOG_ERROR("Failed to enable read-only operation");
315                 return res;
316         }
317         /*
318           According to NVMC examples in Nordic SDK busy status must be
319           checked after writing to NVMC_CONFIG
320          */
321         res = nrf51_wait_for_nvmc(chip);
322         if (res != ERROR_OK)
323                 LOG_ERROR("Read only enable did not complete");
324
325         return res;
326 }
327
328 static int nrf51_nvmc_generic_erase(struct nrf51_info *chip,
329                                uint32_t erase_register, uint32_t erase_value)
330 {
331         int res;
332
333         res = nrf51_nvmc_erase_enable(chip);
334         if (res != ERROR_OK)
335                 goto error;
336
337         res = target_write_u32(chip->target,
338                                erase_register,
339                                erase_value);
340         if (res != ERROR_OK)
341                 goto set_read_only;
342
343         res = nrf51_wait_for_nvmc(chip);
344         if (res != ERROR_OK)
345                 goto set_read_only;
346
347         return nrf51_nvmc_read_only(chip);
348
349 set_read_only:
350         nrf51_nvmc_read_only(chip);
351 error:
352         LOG_ERROR("Failed to erase reg: 0x%08"PRIx32" val: 0x%08"PRIx32,
353                   erase_register, erase_value);
354         return ERROR_FAIL;
355 }
356
357 static int nrf51_protect_check(struct flash_bank *bank)
358 {
359         int res;
360         uint32_t clenr0;
361
362         /* UICR cannot be write protected so just return early */
363         if (bank->base == NRF51_UICR_BASE)
364                 return ERROR_OK;
365
366         struct nrf51_info *chip = bank->driver_priv;
367
368         assert(chip != NULL);
369
370         res = target_read_u32(chip->target, NRF51_FICR_CLENR0,
371                               &clenr0);
372         if (res != ERROR_OK) {
373                 LOG_ERROR("Couldn't read code region 0 size[FICR]");
374                 return res;
375         }
376
377         if (clenr0 == 0xFFFFFFFF) {
378                 res = target_read_u32(chip->target, NRF51_UICR_CLENR0,
379                                       &clenr0);
380                 if (res != ERROR_OK) {
381                         LOG_ERROR("Couldn't read code region 0 size[UICR]");
382                         return res;
383                 }
384         }
385
386         for (int i = 0; i < bank->num_sectors; i++)
387                 bank->sectors[i].is_protected =
388                         clenr0 != 0xFFFFFFFF && bank->sectors[i].offset < clenr0;
389
390         return ERROR_OK;
391 }
392
393 static int nrf51_protect(struct flash_bank *bank, int set, int first, int last)
394 {
395         int res;
396         uint32_t clenr0, ppfc;
397         struct nrf51_info *chip;
398
399         /* UICR cannot be write protected so just bail out early */
400         if (bank->base == NRF51_UICR_BASE)
401                 return ERROR_FAIL;
402
403         res = nrf51_get_probed_chip_if_halted(bank, &chip);
404         if (res != ERROR_OK)
405                 return res;
406
407         if (first != 0) {
408                 LOG_ERROR("Code region 0 must start at the begining of the bank");
409                 return ERROR_FAIL;
410         }
411
412         res = target_read_u32(chip->target, NRF51_FICR_PPFC,
413                               &ppfc);
414         if (res != ERROR_OK) {
415                 LOG_ERROR("Couldn't read PPFC register");
416                 return res;
417         }
418
419         if ((ppfc & 0xFF) == 0x00) {
420                 LOG_ERROR("Code region 0 size was pre-programmed at the factory, can't change flash protection settings");
421                 return ERROR_FAIL;
422         };
423
424         res = target_read_u32(chip->target, NRF51_UICR_CLENR0,
425                               &clenr0);
426         if (res != ERROR_OK) {
427                 LOG_ERROR("Couldn't read code region 0 size[UICR]");
428                 return res;
429         }
430
431         if (clenr0 == 0xFFFFFFFF) {
432                 res = target_write_u32(chip->target, NRF51_UICR_CLENR0,
433                                        clenr0);
434                 if (res != ERROR_OK) {
435                         LOG_ERROR("Couldn't write code region 0 size[UICR]");
436                         return res;
437                 }
438
439         } else {
440                 LOG_ERROR("You need to perform chip erase before changing the protection settings");
441         }
442
443         nrf51_protect_check(bank);
444
445         return ERROR_OK;
446 }
447
448 static int nrf51_probe(struct flash_bank *bank)
449 {
450         uint32_t hwid;
451         int res;
452         struct nrf51_info *chip = bank->driver_priv;
453
454         res = target_read_u32(chip->target, NRF51_FICR_CONFIGID, &hwid);
455         if (res != ERROR_OK) {
456                 LOG_ERROR("Couldn't read CONFIGID register");
457                 return res;
458         }
459
460         hwid &= 0xFFFF; /* HWID is stored in the lower two
461                          * bytes of the CONFIGID register */
462
463         const struct nrf51_device_spec *spec = NULL;
464         for (size_t i = 0; i < ARRAY_SIZE(nrf51_known_devices_table); i++)
465                 if (hwid == nrf51_known_devices_table[i].hwid) {
466                         spec = &nrf51_known_devices_table[i];
467                         break;
468                 }
469
470         if (!chip->bank[0].probed && !chip->bank[1].probed) {
471                 if (spec)
472                         LOG_INFO("nRF51822-%s(build code: %s) %ukB Flash",
473                                  spec->variant, spec->build_code, spec->flash_size_kb);
474                 else
475                         LOG_WARNING("Unknown device (HWID 0x%08" PRIx32 ")", hwid);
476         }
477
478
479         if (bank->base == NRF51_FLASH_BASE) {
480                 res = target_read_u32(chip->target, NRF51_FICR_CODEPAGESIZE,
481                                       &chip->code_page_size);
482                 if (res != ERROR_OK) {
483                         LOG_ERROR("Couldn't read code page size");
484                         return res;
485                 }
486
487                 res = target_read_u32(chip->target, NRF51_FICR_CODESIZE,
488                                       &chip->code_memory_size);
489                 if (res != ERROR_OK) {
490                         LOG_ERROR("Couldn't read code memory size");
491                         return res;
492                 }
493
494                 if (spec && chip->code_memory_size != spec->flash_size_kb) {
495                         LOG_ERROR("Chip's reported Flash capacity does not match expected one");
496                         return ERROR_FAIL;
497                 }
498
499                 bank->size = chip->code_memory_size * 1024;
500                 bank->num_sectors = bank->size / chip->code_page_size;
501                 bank->sectors = calloc(bank->num_sectors,
502                                        sizeof((bank->sectors)[0]));
503                 if (!bank->sectors)
504                         return ERROR_FLASH_BANK_NOT_PROBED;
505
506                 /* Fill out the sector information: all NRF51 sectors are the same size and
507                  * there is always a fixed number of them. */
508                 for (int i = 0; i < bank->num_sectors; i++) {
509                         bank->sectors[i].size = chip->code_page_size;
510                         bank->sectors[i].offset = i * chip->code_page_size;
511
512                         /* mark as unknown */
513                         bank->sectors[i].is_erased = -1;
514                         bank->sectors[i].is_protected = -1;
515                 }
516
517                 nrf51_protect_check(bank);
518
519                 chip->bank[0].probed = true;
520         } else {
521                 bank->size = NRF51_UICR_SIZE;
522                 bank->num_sectors = 1;
523                 bank->sectors = calloc(bank->num_sectors,
524                                        sizeof((bank->sectors)[0]));
525                 if (!bank->sectors)
526                         return ERROR_FLASH_BANK_NOT_PROBED;
527
528                 bank->sectors[0].size = bank->size;
529                 bank->sectors[0].offset = 0;
530
531                 /* mark as unknown */
532                 bank->sectors[0].is_erased = 0;
533                 bank->sectors[0].is_protected = 0;
534
535                 chip->bank[1].probed = true;
536         }
537
538         return ERROR_OK;
539 }
540
541 static int nrf51_auto_probe(struct flash_bank *bank)
542 {
543         int probed = nrf51_bank_is_probed(bank);
544
545         if (probed < 0)
546                 return probed;
547         else if (probed)
548                 return ERROR_OK;
549         else
550                 return nrf51_probe(bank);
551 }
552
553 static struct flash_sector *nrf51_find_sector_by_address(struct flash_bank *bank, uint32_t address)
554 {
555         struct nrf51_info *chip = bank->driver_priv;
556
557         for (int i = 0; i < bank->num_sectors; i++)
558                 if (bank->sectors[i].offset <= address &&
559                     address < (bank->sectors[i].offset + chip->code_page_size))
560                         return &bank->sectors[i];
561         return NULL;
562 }
563
564 static int nrf51_erase_all(struct nrf51_info *chip)
565 {
566         LOG_DEBUG("Erasing all non-volatile memory");
567         return nrf51_nvmc_generic_erase(chip,
568                                         NRF51_NVMC_ERASEALL,
569                                         0x00000001);
570 }
571
572 static int nrf51_erase_page(struct flash_bank *bank,
573                                                         struct nrf51_info *chip,
574                                                         struct flash_sector *sector)
575 {
576         int res;
577
578         LOG_DEBUG("Erasing page at 0x%"PRIx32, sector->offset);
579         if (sector->is_protected) {
580                 LOG_ERROR("Cannot erase protected sector at 0x%x", sector->offset);
581                 return ERROR_FAIL;
582         }
583
584         if (bank->base == NRF51_UICR_BASE) {
585                 uint32_t ppfc;
586                 res = target_read_u32(chip->target, NRF51_FICR_PPFC,
587                                       &ppfc);
588                 if (res != ERROR_OK) {
589                         LOG_ERROR("Couldn't read PPFC register");
590                         return res;
591                 }
592
593                 if ((ppfc & 0xFF) == 0xFF) {
594                         /* We can't erase the UICR.  Double-check to
595                            see if it's already erased before complaining. */
596                         default_flash_blank_check(bank);
597                         if (sector->is_erased == 1)
598                                 return ERROR_OK;
599
600                         LOG_ERROR("The chip was not pre-programmed with SoftDevice stack and UICR cannot be erased separately. Please issue mass erase before trying to write to this region");
601                         return ERROR_FAIL;
602                 };
603
604                 res = nrf51_nvmc_generic_erase(chip,
605                                                NRF51_NVMC_ERASEUICR,
606                                                0x00000001);
607
608
609         } else {
610                 res = nrf51_nvmc_generic_erase(chip,
611                                                NRF51_NVMC_ERASEPAGE,
612                                                sector->offset);
613         }
614
615         if (res == ERROR_OK)
616                 sector->is_erased = 1;
617
618         return res;
619 }
620
621 static const uint8_t nrf51_flash_write_code[] = {
622         /* See contrib/loaders/flash/cortex-m0.S */
623 /* <wait_fifo>: */
624         0x0d, 0x68,             /* ldr  r5,     [r1,    #0] */
625         0x00, 0x2d,             /* cmp  r5,     #0 */
626         0x0b, 0xd0,             /* beq.n        1e <exit> */
627         0x4c, 0x68,             /* ldr  r4,     [r1,    #4] */
628         0xac, 0x42,             /* cmp  r4,     r5 */
629         0xf9, 0xd0,             /* beq.n        0 <wait_fifo> */
630         0x20, 0xcc,             /* ldmia        r4!,    {r5} */
631         0x20, 0xc3,             /* stmia        r3!,    {r5} */
632         0x94, 0x42,             /* cmp  r4,     r2 */
633         0x01, 0xd3,             /* bcc.n        18 <no_wrap> */
634         0x0c, 0x46,             /* mov  r4,     r1 */
635         0x08, 0x34,             /* adds r4,     #8 */
636 /* <no_wrap>: */
637         0x4c, 0x60,             /* str  r4, [r1,        #4] */
638         0x04, 0x38,             /* subs r0, #4 */
639         0xf0, 0xd1,             /* bne.n        0 <wait_fifo> */
640 /* <exit>: */
641         0x00, 0xbe              /* bkpt 0x0000 */
642 };
643
644
645 /* Start a low level flash write for the specified region */
646 static int nrf51_ll_flash_write(struct nrf51_info *chip, uint32_t offset, const uint8_t *buffer, uint32_t bytes)
647 {
648         struct target *target = chip->target;
649         uint32_t buffer_size = 8192;
650         struct working_area *write_algorithm;
651         struct working_area *source;
652         uint32_t address = NRF51_FLASH_BASE + offset;
653         struct reg_param reg_params[4];
654         struct armv7m_algorithm armv7m_info;
655         int retval = ERROR_OK;
656
657
658         LOG_DEBUG("Writing buffer to flash offset=0x%"PRIx32" bytes=0x%"PRIx32, offset, bytes);
659         assert(bytes % 4 == 0);
660
661         /* allocate working area with flash programming code */
662         if (target_alloc_working_area(target, sizeof(nrf51_flash_write_code),
663                         &write_algorithm) != ERROR_OK) {
664                 LOG_WARNING("no working area available, falling back to slow memory writes");
665
666                 for (; bytes > 0; bytes -= 4) {
667                         retval = target_write_memory(chip->target, offset, 4, 1, buffer);
668                         if (retval != ERROR_OK)
669                                 return retval;
670
671                         retval = nrf51_wait_for_nvmc(chip);
672                         if (retval != ERROR_OK)
673                                 return retval;
674
675                         offset += 4;
676                         buffer += 4;
677                 }
678
679                 return ERROR_OK;
680         }
681
682         LOG_WARNING("using fast async flash loader. This is currently supported");
683         LOG_WARNING("only with ST-Link and CMSIS-DAP. If you have issues, add");
684         LOG_WARNING("\"set WORKAREASIZE 0\" before sourcing nrf51.cfg to disable it");
685
686         retval = target_write_buffer(target, write_algorithm->address,
687                                 sizeof(nrf51_flash_write_code),
688                                 nrf51_flash_write_code);
689         if (retval != ERROR_OK)
690                 return retval;
691
692         /* memory buffer */
693         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
694                 buffer_size /= 2;
695                 buffer_size &= ~3UL; /* Make sure it's 4 byte aligned */
696                 if (buffer_size <= 256) {
697                         /* free working area, write algorithm already allocated */
698                         target_free_working_area(target, write_algorithm);
699
700                         LOG_WARNING("No large enough working area available, can't do block memory writes");
701                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
702                 }
703         }
704
705         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
706         armv7m_info.core_mode = ARM_MODE_THREAD;
707
708         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* byte count */
709         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* buffer start */
710         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* buffer end */
711         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN_OUT); /* target address */
712
713         buf_set_u32(reg_params[0].value, 0, 32, bytes);
714         buf_set_u32(reg_params[1].value, 0, 32, source->address);
715         buf_set_u32(reg_params[2].value, 0, 32, source->address + source->size);
716         buf_set_u32(reg_params[3].value, 0, 32, address);
717
718         retval = target_run_flash_async_algorithm(target, buffer, bytes/4, 4,
719                         0, NULL,
720                         4, reg_params,
721                         source->address, source->size,
722                         write_algorithm->address, 0,
723                         &armv7m_info);
724
725         target_free_working_area(target, source);
726         target_free_working_area(target, write_algorithm);
727
728         destroy_reg_param(&reg_params[0]);
729         destroy_reg_param(&reg_params[1]);
730         destroy_reg_param(&reg_params[2]);
731         destroy_reg_param(&reg_params[3]);
732
733         return retval;
734 }
735
736 /* Check and erase flash sectors in specified range then start a low level page write.
737    start/end must be sector aligned.
738 */
739 static int nrf51_write_pages(struct flash_bank *bank, uint32_t start, uint32_t end, const uint8_t *buffer)
740 {
741         int res = ERROR_FAIL;
742         struct nrf51_info *chip = bank->driver_priv;
743         struct flash_sector *sector;
744         uint32_t offset;
745
746         assert(start % chip->code_page_size == 0);
747         assert(end % chip->code_page_size == 0);
748
749         /* Erase all sectors */
750         for (offset = start; offset < end; offset += chip->code_page_size) {
751                 sector = nrf51_find_sector_by_address(bank, offset);
752                 if (!sector) {
753                         LOG_ERROR("Invalid sector @ 0x%08"PRIx32, offset);
754                         return ERROR_FLASH_SECTOR_INVALID;
755                 }
756
757                 if (sector->is_protected) {
758                         LOG_ERROR("Can't erase protected sector @ 0x%08"PRIx32, offset);
759                         goto error;
760                 }
761
762                 if (sector->is_erased != 1) {   /* 1 = erased, 0= not erased, -1 = unknown */
763                         res = nrf51_erase_page(bank, chip, sector);
764                         if (res != ERROR_OK) {
765                                 LOG_ERROR("Failed to erase sector @ 0x%08"PRIx32, sector->offset);
766                                 goto error;
767                         }
768                 }
769                 sector->is_erased = 0;
770         }
771
772         res = nrf51_nvmc_write_enable(chip);
773         if (res != ERROR_OK)
774                 goto error;
775
776         res = nrf51_ll_flash_write(chip, start, buffer, (end - start));
777         if (res != ERROR_OK)
778                 goto set_read_only;
779
780         return nrf51_nvmc_read_only(chip);
781
782 set_read_only:
783         nrf51_nvmc_read_only(chip);
784 error:
785         LOG_ERROR("Failed to write to nrf51 flash");
786         return res;
787 }
788
789 static int nrf51_erase(struct flash_bank *bank, int first, int last)
790 {
791         int res;
792         struct nrf51_info *chip;
793
794         res = nrf51_get_probed_chip_if_halted(bank, &chip);
795         if (res != ERROR_OK)
796                 return res;
797
798         /* For each sector to be erased */
799         for (int s = first; s <= last && res == ERROR_OK; s++)
800                 res = nrf51_erase_page(bank, chip, &bank->sectors[s]);
801
802         return res;
803 }
804
805 static int nrf51_code_flash_write(struct flash_bank *bank,
806                                   struct nrf51_info *chip,
807                                   const uint8_t *buffer, uint32_t offset, uint32_t count)
808 {
809
810         int res;
811         /* Need to perform reads to fill any gaps we need to preserve in the first page,
812            before the start of buffer, or in the last page, after the end of buffer */
813         uint32_t first_page = offset/chip->code_page_size;
814         uint32_t last_page = DIV_ROUND_UP(offset+count, chip->code_page_size);
815
816         uint32_t first_page_offset = first_page * chip->code_page_size;
817         uint32_t last_page_offset = last_page * chip->code_page_size;
818
819         LOG_DEBUG("Padding write from 0x%08"PRIx32"-0x%08"PRIx32" as 0x%08"PRIx32"-0x%08"PRIx32,
820                 offset, offset+count, first_page_offset, last_page_offset);
821
822         uint32_t page_cnt = last_page - first_page;
823         uint8_t buffer_to_flash[page_cnt*chip->code_page_size];
824
825         /* Fill in any space between start of first page and start of buffer */
826         uint32_t pre = offset - first_page_offset;
827         if (pre > 0) {
828                 res = target_read_memory(bank->target,
829                                         first_page_offset,
830                                         1,
831                                         pre,
832                                         buffer_to_flash);
833                 if (res != ERROR_OK)
834                         return res;
835         }
836
837         /* Fill in main contents of buffer */
838         memcpy(buffer_to_flash+pre, buffer, count);
839
840         /* Fill in any space between end of buffer and end of last page */
841         uint32_t post = last_page_offset - (offset+count);
842         if (post > 0) {
843                 /* Retrieve the full row contents from Flash */
844                 res = target_read_memory(bank->target,
845                                         offset + count,
846                                         1,
847                                         post,
848                                         buffer_to_flash+pre+count);
849                 if (res != ERROR_OK)
850                         return res;
851         }
852
853         return nrf51_write_pages(bank, first_page_offset, last_page_offset, buffer_to_flash);
854 }
855
856 static int nrf51_uicr_flash_write(struct flash_bank *bank,
857                                   struct nrf51_info *chip,
858                                   const uint8_t *buffer, uint32_t offset, uint32_t count)
859 {
860         int res;
861         uint8_t uicr[NRF51_UICR_SIZE];
862         struct flash_sector *sector = &bank->sectors[0];
863
864         if ((offset + count) > NRF51_UICR_SIZE)
865                 return ERROR_FAIL;
866
867         res = target_read_memory(bank->target,
868                                  NRF51_UICR_BASE,
869                                  1,
870                                  NRF51_UICR_SIZE,
871                                  uicr);
872
873         if (res != ERROR_OK)
874                 return res;
875
876         if (sector->is_erased != 1) {
877                 res = nrf51_erase_page(bank, chip, sector);
878                 if (res != ERROR_OK)
879                         return res;
880         }
881
882         res = nrf51_nvmc_write_enable(chip);
883         if (res != ERROR_OK)
884                 return res;
885
886         memcpy(&uicr[offset], buffer, count);
887
888         res = nrf51_ll_flash_write(chip, NRF51_UICR_BASE, uicr, NRF51_UICR_SIZE);
889         if (res != ERROR_OK) {
890                 nrf51_nvmc_read_only(chip);
891                 return res;
892         }
893
894         return nrf51_nvmc_read_only(chip);
895 }
896
897
898 static int nrf51_write(struct flash_bank *bank, const uint8_t *buffer,
899                        uint32_t offset, uint32_t count)
900 {
901         int res;
902         struct nrf51_info *chip;
903
904         res = nrf51_get_probed_chip_if_halted(bank, &chip);
905         if (res != ERROR_OK)
906                 return res;
907
908         return chip->bank[bank->bank_number].write(bank, chip, buffer, offset, count);
909 }
910
911
912 FLASH_BANK_COMMAND_HANDLER(nrf51_flash_bank_command)
913 {
914         static struct nrf51_info *chip;
915
916         switch (bank->base) {
917         case NRF51_FLASH_BASE:
918                 bank->bank_number = 0;
919                 break;
920         case NRF51_UICR_BASE:
921                 bank->bank_number = 1;
922                 break;
923         default:
924                 LOG_ERROR("Invalid bank address 0x%08" PRIx32, bank->base);
925                 return ERROR_FAIL;
926         }
927
928         if (!chip) {
929                 /* Create a new chip */
930                 chip = calloc(1, sizeof(*chip));
931                 if (!chip)
932                         return ERROR_FAIL;
933
934                 chip->target = bank->target;
935         }
936
937         switch (bank->base) {
938         case NRF51_FLASH_BASE:
939                 chip->bank[bank->bank_number].write = nrf51_code_flash_write;
940                 break;
941         case NRF51_UICR_BASE:
942                 chip->bank[bank->bank_number].write = nrf51_uicr_flash_write;
943                 break;
944         }
945
946         chip->bank[bank->bank_number].probed = false;
947         bank->driver_priv = chip;
948
949         return ERROR_OK;
950 }
951
952 COMMAND_HANDLER(nrf51_handle_mass_erase_command)
953 {
954         int res;
955         struct flash_bank *bank = NULL;
956         struct target *target = get_current_target(CMD_CTX);
957
958         res = get_flash_bank_by_addr(target, NRF51_FLASH_BASE, true, &bank);
959         if (res != ERROR_OK)
960                 return res;
961
962         assert(bank != NULL);
963
964         struct nrf51_info *chip;
965
966         res = nrf51_get_probed_chip_if_halted(bank, &chip);
967         if (res != ERROR_OK)
968                 return res;
969
970         uint32_t ppfc;
971
972         res = target_read_u32(target, NRF51_FICR_PPFC,
973                               &ppfc);
974         if (res != ERROR_OK) {
975                 LOG_ERROR("Couldn't read PPFC register");
976                 return res;
977         }
978
979         if ((ppfc & 0xFF) == 0x00) {
980                 LOG_ERROR("Code region 0 size was pre-programmed at the factory, "
981                           "mass erase command won't work.");
982                 return ERROR_FAIL;
983         };
984
985         res = nrf51_erase_all(chip);
986         if (res != ERROR_OK) {
987                 LOG_ERROR("Failed to erase the chip");
988                 nrf51_protect_check(bank);
989                 return res;
990         }
991
992         for (int i = 0; i < bank->num_sectors; i++)
993                 bank->sectors[i].is_erased = 1;
994
995         res = nrf51_protect_check(bank);
996         if (res != ERROR_OK) {
997                 LOG_ERROR("Failed to check chip's write protection");
998                 return res;
999         }
1000
1001         res = get_flash_bank_by_addr(target, NRF51_UICR_BASE, true, &bank);
1002         if (res != ERROR_OK)
1003                 return res;
1004
1005         bank->sectors[0].is_erased = 1;
1006
1007         return ERROR_OK;
1008 }
1009
1010 static int nrf51_info(struct flash_bank *bank, char *buf, int buf_size)
1011 {
1012         int res;
1013
1014         struct nrf51_info *chip;
1015
1016         res = nrf51_get_probed_chip_if_halted(bank, &chip);
1017         if (res != ERROR_OK)
1018                 return res;
1019
1020         static struct {
1021                 const uint32_t address;
1022                 uint32_t value;
1023         } ficr[] = {
1024                 { .address = NRF51_FICR_CODEPAGESIZE    },
1025                 { .address = NRF51_FICR_CODESIZE        },
1026                 { .address = NRF51_FICR_CLENR0          },
1027                 { .address = NRF51_FICR_PPFC            },
1028                 { .address = NRF51_FICR_NUMRAMBLOCK     },
1029                 { .address = NRF51_FICR_SIZERAMBLOCK0   },
1030                 { .address = NRF51_FICR_SIZERAMBLOCK1   },
1031                 { .address = NRF51_FICR_SIZERAMBLOCK2   },
1032                 { .address = NRF51_FICR_SIZERAMBLOCK3   },
1033                 { .address = NRF51_FICR_CONFIGID        },
1034                 { .address = NRF51_FICR_DEVICEID0       },
1035                 { .address = NRF51_FICR_DEVICEID1       },
1036                 { .address = NRF51_FICR_ER0             },
1037                 { .address = NRF51_FICR_ER1             },
1038                 { .address = NRF51_FICR_ER2             },
1039                 { .address = NRF51_FICR_ER3             },
1040                 { .address = NRF51_FICR_IR0             },
1041                 { .address = NRF51_FICR_IR1             },
1042                 { .address = NRF51_FICR_IR2             },
1043                 { .address = NRF51_FICR_IR3             },
1044                 { .address = NRF51_FICR_DEVICEADDRTYPE  },
1045                 { .address = NRF51_FICR_DEVICEADDR0     },
1046                 { .address = NRF51_FICR_DEVICEADDR1     },
1047                 { .address = NRF51_FICR_OVERRIDEN       },
1048                 { .address = NRF51_FICR_NRF_1MBIT0      },
1049                 { .address = NRF51_FICR_NRF_1MBIT1      },
1050                 { .address = NRF51_FICR_NRF_1MBIT2      },
1051                 { .address = NRF51_FICR_NRF_1MBIT3      },
1052                 { .address = NRF51_FICR_NRF_1MBIT4      },
1053                 { .address = NRF51_FICR_BLE_1MBIT0      },
1054                 { .address = NRF51_FICR_BLE_1MBIT1      },
1055                 { .address = NRF51_FICR_BLE_1MBIT2      },
1056                 { .address = NRF51_FICR_BLE_1MBIT3      },
1057                 { .address = NRF51_FICR_BLE_1MBIT4      },
1058         }, uicr[] = {
1059                 { .address = NRF51_UICR_CLENR0,         },
1060                 { .address = NRF51_UICR_RBPCONF         },
1061                 { .address = NRF51_UICR_XTALFREQ        },
1062                 { .address = NRF51_UICR_FWID            },
1063         };
1064
1065         for (size_t i = 0; i < ARRAY_SIZE(ficr); i++) {
1066                 res = target_read_u32(chip->target, ficr[i].address,
1067                                       &ficr[i].value);
1068                 if (res != ERROR_OK) {
1069                         LOG_ERROR("Couldn't read %" PRIx32, ficr[i].address);
1070                         return res;
1071                 }
1072         }
1073
1074         for (size_t i = 0; i < ARRAY_SIZE(uicr); i++) {
1075                 res = target_read_u32(chip->target, uicr[i].address,
1076                                       &uicr[i].value);
1077                 if (res != ERROR_OK) {
1078                         LOG_ERROR("Couldn't read %" PRIx32, uicr[i].address);
1079                         return res;
1080                 }
1081         }
1082
1083         snprintf(buf, buf_size,
1084                  "\n[factory information control block]\n\n"
1085                  "code page size: %"PRIu32"B\n"
1086                  "code memory size: %"PRIu32"kB\n"
1087                  "code region 0 size: %"PRIu32"kB\n"
1088                  "pre-programmed code: %s\n"
1089                  "number of ram blocks: %"PRIu32"\n"
1090                  "ram block 0 size: %"PRIu32"B\n"
1091                  "ram block 1 size: %"PRIu32"B\n"
1092                  "ram block 2 size: %"PRIu32"B\n"
1093                  "ram block 3 size: %"PRIu32 "B\n"
1094                  "config id: %" PRIx32 "\n"
1095                  "device id: 0x%"PRIx32"%08"PRIx32"\n"
1096                  "encryption root: 0x%08"PRIx32"%08"PRIx32"%08"PRIx32"%08"PRIx32"\n"
1097                  "identity root: 0x%08"PRIx32"%08"PRIx32"%08"PRIx32"%08"PRIx32"\n"
1098                  "device address type: 0x%"PRIx32"\n"
1099                  "device address: 0x%"PRIx32"%08"PRIx32"\n"
1100                  "override enable: %"PRIx32"\n"
1101                  "NRF_1MBIT values: %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32"\n"
1102                  "BLE_1MBIT values: %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32"\n"
1103                  "\n[user information control block]\n\n"
1104                  "code region 0 size: %"PRIu32"kB\n"
1105                  "read back protection configuration: %"PRIx32"\n"
1106                  "reset value for XTALFREQ: %"PRIx32"\n"
1107                  "firmware id: 0x%04"PRIx32,
1108                  ficr[0].value,
1109                  ficr[1].value,
1110                  (ficr[2].value == 0xFFFFFFFF) ? 0 : ficr[2].value / 1024,
1111                  ((ficr[3].value & 0xFF) == 0x00) ? "present" : "not present",
1112                  ficr[4].value,
1113                  ficr[5].value,
1114                  (ficr[6].value == 0xFFFFFFFF) ? 0 : ficr[6].value,
1115                  (ficr[7].value == 0xFFFFFFFF) ? 0 : ficr[7].value,
1116                  (ficr[8].value == 0xFFFFFFFF) ? 0 : ficr[8].value,
1117                  ficr[9].value,
1118                  ficr[10].value, ficr[11].value,
1119                  ficr[12].value, ficr[13].value, ficr[14].value, ficr[15].value,
1120                  ficr[16].value, ficr[17].value, ficr[18].value, ficr[19].value,
1121                  ficr[20].value,
1122                  ficr[21].value, ficr[22].value,
1123                  ficr[23].value,
1124                  ficr[24].value, ficr[25].value, ficr[26].value, ficr[27].value, ficr[28].value,
1125                  ficr[29].value, ficr[30].value, ficr[31].value, ficr[32].value, ficr[33].value,
1126                  (uicr[0].value == 0xFFFFFFFF) ? 0 : uicr[0].value / 1024,
1127                  uicr[1].value & 0xFFFF,
1128                  uicr[2].value & 0xFF,
1129                  uicr[3].value & 0xFFFF);
1130
1131         return ERROR_OK;
1132 }
1133
1134 static const struct command_registration nrf51_exec_command_handlers[] = {
1135         {
1136                 .name           = "mass_erase",
1137                 .handler        = nrf51_handle_mass_erase_command,
1138                 .mode           = COMMAND_EXEC,
1139                 .help           = "Erase all flash contents of the chip.",
1140         },
1141         COMMAND_REGISTRATION_DONE
1142 };
1143
1144 static const struct command_registration nrf51_command_handlers[] = {
1145         {
1146                 .name   = "nrf51",
1147                 .mode   = COMMAND_ANY,
1148                 .help   = "nrf51 flash command group",
1149                 .usage  = "",
1150                 .chain  = nrf51_exec_command_handlers,
1151         },
1152         COMMAND_REGISTRATION_DONE
1153 };
1154
1155 struct flash_driver nrf51_flash = {
1156         .name                   = "nrf51",
1157         .commands               = nrf51_command_handlers,
1158         .flash_bank_command     = nrf51_flash_bank_command,
1159         .info                   = nrf51_info,
1160         .erase                  = nrf51_erase,
1161         .protect                = nrf51_protect,
1162         .write                  = nrf51_write,
1163         .read                   = default_flash_read,
1164         .probe                  = nrf51_probe,
1165         .auto_probe             = nrf51_auto_probe,
1166         .erase_check            = default_flash_blank_check,
1167         .protect_check          = nrf51_protect_check,
1168 };