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