]> git.sur5r.net Git - openocd/blob - src/flash/nor/nrf5.c
ad80e02e0d1e20dced366a88696d336ea8cd6f0f
[openocd] / src / flash / nor / nrf5.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, see <http://www.gnu.org/licenses/>. *
19  ***************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include "imp.h"
26 #include <target/algorithm.h>
27 #include <target/armv7m.h>
28 #include <helper/types.h>
29
30 enum {
31         NRF5_FLASH_BASE = 0x00000000,
32 };
33
34 enum nrf5_ficr_registers {
35         NRF5_FICR_BASE = 0x10000000, /* Factory Information Configuration Registers */
36
37 #define NRF5_FICR_REG(offset) (NRF5_FICR_BASE + offset)
38
39         NRF5_FICR_CODEPAGESIZE          = NRF5_FICR_REG(0x010),
40         NRF5_FICR_CODESIZE              = NRF5_FICR_REG(0x014),
41         NRF5_FICR_CLENR0                = NRF5_FICR_REG(0x028),
42         NRF5_FICR_PPFC                  = NRF5_FICR_REG(0x02C),
43         NRF5_FICR_NUMRAMBLOCK           = NRF5_FICR_REG(0x034),
44         NRF5_FICR_SIZERAMBLOCK0 = NRF5_FICR_REG(0x038),
45         NRF5_FICR_SIZERAMBLOCK1 = NRF5_FICR_REG(0x03C),
46         NRF5_FICR_SIZERAMBLOCK2 = NRF5_FICR_REG(0x040),
47         NRF5_FICR_SIZERAMBLOCK3 = NRF5_FICR_REG(0x044),
48         NRF5_FICR_CONFIGID              = NRF5_FICR_REG(0x05C),
49         NRF5_FICR_DEVICEID0             = NRF5_FICR_REG(0x060),
50         NRF5_FICR_DEVICEID1             = NRF5_FICR_REG(0x064),
51         NRF5_FICR_ER0                   = NRF5_FICR_REG(0x080),
52         NRF5_FICR_ER1                   = NRF5_FICR_REG(0x084),
53         NRF5_FICR_ER2                   = NRF5_FICR_REG(0x088),
54         NRF5_FICR_ER3                   = NRF5_FICR_REG(0x08C),
55         NRF5_FICR_IR0                   = NRF5_FICR_REG(0x090),
56         NRF5_FICR_IR1                   = NRF5_FICR_REG(0x094),
57         NRF5_FICR_IR2                   = NRF5_FICR_REG(0x098),
58         NRF5_FICR_IR3                   = NRF5_FICR_REG(0x09C),
59         NRF5_FICR_DEVICEADDRTYPE        = NRF5_FICR_REG(0x0A0),
60         NRF5_FICR_DEVICEADDR0           = NRF5_FICR_REG(0x0A4),
61         NRF5_FICR_DEVICEADDR1           = NRF5_FICR_REG(0x0A8),
62         NRF5_FICR_OVERRIDEN             = NRF5_FICR_REG(0x0AC),
63         NRF5_FICR_NRF_1MBIT0            = NRF5_FICR_REG(0x0B0),
64         NRF5_FICR_NRF_1MBIT1            = NRF5_FICR_REG(0x0B4),
65         NRF5_FICR_NRF_1MBIT2            = NRF5_FICR_REG(0x0B8),
66         NRF5_FICR_NRF_1MBIT3            = NRF5_FICR_REG(0x0BC),
67         NRF5_FICR_NRF_1MBIT4            = NRF5_FICR_REG(0x0C0),
68         NRF5_FICR_BLE_1MBIT0            = NRF5_FICR_REG(0x0EC),
69         NRF5_FICR_BLE_1MBIT1            = NRF5_FICR_REG(0x0F0),
70         NRF5_FICR_BLE_1MBIT2            = NRF5_FICR_REG(0x0F4),
71         NRF5_FICR_BLE_1MBIT3            = NRF5_FICR_REG(0x0F8),
72         NRF5_FICR_BLE_1MBIT4            = NRF5_FICR_REG(0x0FC),
73 };
74
75 enum nrf5_uicr_registers {
76         NRF5_UICR_BASE = 0x10001000, /* User Information
77                                        * Configuration Regsters */
78
79         NRF5_UICR_SIZE = 0x100,
80
81 #define NRF5_UICR_REG(offset) (NRF5_UICR_BASE + offset)
82
83         NRF5_UICR_CLENR0        = NRF5_UICR_REG(0x000),
84         NRF5_UICR_RBPCONF       = NRF5_UICR_REG(0x004),
85         NRF5_UICR_XTALFREQ      = NRF5_UICR_REG(0x008),
86         NRF5_UICR_FWID          = NRF5_UICR_REG(0x010),
87 };
88
89 enum nrf5_nvmc_registers {
90         NRF5_NVMC_BASE = 0x4001E000, /* Non-Volatile Memory
91                                        * Controller Regsters */
92
93 #define NRF5_NVMC_REG(offset) (NRF5_NVMC_BASE + offset)
94
95         NRF5_NVMC_READY = NRF5_NVMC_REG(0x400),
96         NRF5_NVMC_CONFIG        = NRF5_NVMC_REG(0x504),
97         NRF5_NVMC_ERASEPAGE     = NRF5_NVMC_REG(0x508),
98         NRF5_NVMC_ERASEALL      = NRF5_NVMC_REG(0x50C),
99         NRF5_NVMC_ERASEUICR     = NRF5_NVMC_REG(0x514),
100 };
101
102 enum nrf5_nvmc_config_bits {
103         NRF5_NVMC_CONFIG_REN = 0x00,
104         NRF5_NVMC_CONFIG_WEN = 0x01,
105         NRF5_NVMC_CONFIG_EEN = 0x02,
106
107 };
108
109 struct nrf5_info {
110         uint32_t code_page_size;
111
112         struct {
113                 bool probed;
114                 int (*write) (struct flash_bank *bank,
115                               struct nrf5_info *chip,
116                               const uint8_t *buffer, uint32_t offset, uint32_t count);
117         } bank[2];
118         struct target *target;
119 };
120
121 struct nrf5_device_spec {
122         uint16_t hwid;
123         const char *part;
124         const char *variant;
125         const char *build_code;
126         unsigned int flash_size_kb;
127 };
128
129 #define NRF5_DEVICE_DEF(id, pt, var, bcode, fsize) \
130 {                                                   \
131 .hwid          = (id),                              \
132 .part          = pt,                                \
133 .variant       = var,                               \
134 .build_code    = bcode,                             \
135 .flash_size_kb = (fsize),                           \
136 }
137
138 /* The known devices table below is derived from the "nRF51 Series
139  * Compatibility Matrix" document, which can be found by searching for
140  * ATTN-51 on the Nordic Semi website:
141  *
142  * http://www.nordicsemi.com/eng/content/search?SearchText=ATTN-51
143  *
144  * Up to date with Matrix v2.0, plus some additional HWIDs.
145  *
146  * The additional HWIDs apply where the build code in the matrix is
147  * shown as Gx0, Bx0, etc. In these cases the HWID in the matrix is
148  * for x==0, x!=0 means different (unspecified) HWIDs.
149  */
150 static const struct nrf5_device_spec nrf5_known_devices_table[] = {
151         /* nRF51822 Devices (IC rev 1). */
152         NRF5_DEVICE_DEF(0x001D, "51822", "QFAA", "CA/C0", 256),
153         NRF5_DEVICE_DEF(0x0026, "51822", "QFAB", "AA",    128),
154         NRF5_DEVICE_DEF(0x0027, "51822", "QFAB", "A0",    128),
155         NRF5_DEVICE_DEF(0x0020, "51822", "CEAA", "BA",    256),
156         NRF5_DEVICE_DEF(0x002F, "51822", "CEAA", "B0",    256),
157
158         /* Some early nRF51-DK (PCA10028) & nRF51-Dongle (PCA10031) boards
159            with built-in jlink seem to use engineering samples not listed
160            in the nRF51 Series Compatibility Matrix V1.0. */
161         NRF5_DEVICE_DEF(0x0071, "51822", "QFAC", "AB",    256),
162
163         /* nRF51822 Devices (IC rev 2). */
164         NRF5_DEVICE_DEF(0x002A, "51822", "QFAA", "FA0",   256),
165         NRF5_DEVICE_DEF(0x0044, "51822", "QFAA", "GC0",   256),
166         NRF5_DEVICE_DEF(0x003C, "51822", "QFAA", "G0",    256),
167         NRF5_DEVICE_DEF(0x0057, "51822", "QFAA", "G2",    256),
168         NRF5_DEVICE_DEF(0x0058, "51822", "QFAA", "G3",    256),
169         NRF5_DEVICE_DEF(0x004C, "51822", "QFAB", "B0",    128),
170         NRF5_DEVICE_DEF(0x0040, "51822", "CEAA", "CA0",   256),
171         NRF5_DEVICE_DEF(0x0047, "51822", "CEAA", "DA0",   256),
172         NRF5_DEVICE_DEF(0x004D, "51822", "CEAA", "D00",   256),
173
174         /* nRF51822 Devices (IC rev 3). */
175         NRF5_DEVICE_DEF(0x0072, "51822", "QFAA", "H0",    256),
176         NRF5_DEVICE_DEF(0x00D1, "51822", "QFAA", "H2",    256),
177         NRF5_DEVICE_DEF(0x007B, "51822", "QFAB", "C0",    128),
178         NRF5_DEVICE_DEF(0x0083, "51822", "QFAC", "A0",    256),
179         NRF5_DEVICE_DEF(0x0084, "51822", "QFAC", "A1",    256),
180         NRF5_DEVICE_DEF(0x007D, "51822", "CDAB", "A0",    128),
181         NRF5_DEVICE_DEF(0x0079, "51822", "CEAA", "E0",    256),
182         NRF5_DEVICE_DEF(0x0087, "51822", "CFAC", "A0",    256),
183         NRF5_DEVICE_DEF(0x008F, "51822", "QFAA", "H1",    256),
184
185         /* nRF51422 Devices (IC rev 1). */
186         NRF5_DEVICE_DEF(0x001E, "51422", "QFAA", "CA",    256),
187         NRF5_DEVICE_DEF(0x0024, "51422", "QFAA", "C0",    256),
188         NRF5_DEVICE_DEF(0x0031, "51422", "CEAA", "A0A",   256),
189
190         /* nRF51422 Devices (IC rev 2). */
191         NRF5_DEVICE_DEF(0x002D, "51422", "QFAA", "DAA",   256),
192         NRF5_DEVICE_DEF(0x002E, "51422", "QFAA", "E0",    256),
193         NRF5_DEVICE_DEF(0x0061, "51422", "QFAB", "A00",   128),
194         NRF5_DEVICE_DEF(0x0050, "51422", "CEAA", "B0",    256),
195
196         /* nRF51422 Devices (IC rev 3). */
197         NRF5_DEVICE_DEF(0x0073, "51422", "QFAA", "F0",    256),
198         NRF5_DEVICE_DEF(0x007C, "51422", "QFAB", "B0",    128),
199         NRF5_DEVICE_DEF(0x0085, "51422", "QFAC", "A0",    256),
200         NRF5_DEVICE_DEF(0x0086, "51422", "QFAC", "A1",    256),
201         NRF5_DEVICE_DEF(0x007E, "51422", "CDAB", "A0",    128),
202         NRF5_DEVICE_DEF(0x007A, "51422", "CEAA", "C0",    256),
203         NRF5_DEVICE_DEF(0x0088, "51422", "CFAC", "A0",    256),
204
205         /* nRF52832 Devices */
206         NRF5_DEVICE_DEF(0x00C7, "52832", "QFAA", "B0",    512),
207         NRF5_DEVICE_DEF(0x0139, "52832", "QFAA", "E0",    512),
208 };
209
210 static int nrf5_bank_is_probed(struct flash_bank *bank)
211 {
212         struct nrf5_info *chip = bank->driver_priv;
213
214         assert(chip != NULL);
215
216         return chip->bank[bank->bank_number].probed;
217 }
218 static int nrf5_probe(struct flash_bank *bank);
219
220 static int nrf5_get_probed_chip_if_halted(struct flash_bank *bank, struct nrf5_info **chip)
221 {
222         if (bank->target->state != TARGET_HALTED) {
223                 LOG_ERROR("Target not halted");
224                 return ERROR_TARGET_NOT_HALTED;
225         }
226
227         *chip = bank->driver_priv;
228
229         int probed = nrf5_bank_is_probed(bank);
230         if (probed < 0)
231                 return probed;
232         else if (!probed)
233                 return nrf5_probe(bank);
234         else
235                 return ERROR_OK;
236 }
237
238 static int nrf5_wait_for_nvmc(struct nrf5_info *chip)
239 {
240         uint32_t ready;
241         int res;
242         int timeout = 100;
243
244         do {
245                 res = target_read_u32(chip->target, NRF5_NVMC_READY, &ready);
246                 if (res != ERROR_OK) {
247                         LOG_ERROR("Couldn't read NVMC_READY register");
248                         return res;
249                 }
250
251                 if (ready == 0x00000001)
252                         return ERROR_OK;
253
254                 alive_sleep(1);
255         } while (timeout--);
256
257         LOG_DEBUG("Timed out waiting for NVMC_READY");
258         return ERROR_FLASH_BUSY;
259 }
260
261 static int nrf5_nvmc_erase_enable(struct nrf5_info *chip)
262 {
263         int res;
264         res = target_write_u32(chip->target,
265                                NRF5_NVMC_CONFIG,
266                                NRF5_NVMC_CONFIG_EEN);
267
268         if (res != ERROR_OK) {
269                 LOG_ERROR("Failed to enable erase operation");
270                 return res;
271         }
272
273         /*
274           According to NVMC examples in Nordic SDK busy status must be
275           checked after writing to NVMC_CONFIG
276          */
277         res = nrf5_wait_for_nvmc(chip);
278         if (res != ERROR_OK)
279                 LOG_ERROR("Erase enable did not complete");
280
281         return res;
282 }
283
284 static int nrf5_nvmc_write_enable(struct nrf5_info *chip)
285 {
286         int res;
287         res = target_write_u32(chip->target,
288                                NRF5_NVMC_CONFIG,
289                                NRF5_NVMC_CONFIG_WEN);
290
291         if (res != ERROR_OK) {
292                 LOG_ERROR("Failed to enable write operation");
293                 return res;
294         }
295
296         /*
297           According to NVMC examples in Nordic SDK busy status must be
298           checked after writing to NVMC_CONFIG
299          */
300         res = nrf5_wait_for_nvmc(chip);
301         if (res != ERROR_OK)
302                 LOG_ERROR("Write enable did not complete");
303
304         return res;
305 }
306
307 static int nrf5_nvmc_read_only(struct nrf5_info *chip)
308 {
309         int res;
310         res = target_write_u32(chip->target,
311                                NRF5_NVMC_CONFIG,
312                                NRF5_NVMC_CONFIG_REN);
313
314         if (res != ERROR_OK) {
315                 LOG_ERROR("Failed to enable read-only operation");
316                 return res;
317         }
318         /*
319           According to NVMC examples in Nordic SDK busy status must be
320           checked after writing to NVMC_CONFIG
321          */
322         res = nrf5_wait_for_nvmc(chip);
323         if (res != ERROR_OK)
324                 LOG_ERROR("Read only enable did not complete");
325
326         return res;
327 }
328
329 static int nrf5_nvmc_generic_erase(struct nrf5_info *chip,
330                                uint32_t erase_register, uint32_t erase_value)
331 {
332         int res;
333
334         res = nrf5_nvmc_erase_enable(chip);
335         if (res != ERROR_OK)
336                 goto error;
337
338         res = target_write_u32(chip->target,
339                                erase_register,
340                                erase_value);
341         if (res != ERROR_OK)
342                 goto set_read_only;
343
344         res = nrf5_wait_for_nvmc(chip);
345         if (res != ERROR_OK)
346                 goto set_read_only;
347
348         return nrf5_nvmc_read_only(chip);
349
350 set_read_only:
351         nrf5_nvmc_read_only(chip);
352 error:
353         LOG_ERROR("Failed to erase reg: 0x%08"PRIx32" val: 0x%08"PRIx32,
354                   erase_register, erase_value);
355         return ERROR_FAIL;
356 }
357
358 static int nrf5_protect_check(struct flash_bank *bank)
359 {
360         int res;
361         uint32_t clenr0;
362
363         /* UICR cannot be write protected so just return early */
364         if (bank->base == NRF5_UICR_BASE)
365                 return ERROR_OK;
366
367         struct nrf5_info *chip = bank->driver_priv;
368
369         assert(chip != NULL);
370
371         res = target_read_u32(chip->target, NRF5_FICR_CLENR0,
372                               &clenr0);
373         if (res != ERROR_OK) {
374                 LOG_ERROR("Couldn't read code region 0 size[FICR]");
375                 return res;
376         }
377
378         if (clenr0 == 0xFFFFFFFF) {
379                 res = target_read_u32(chip->target, NRF5_UICR_CLENR0,
380                                       &clenr0);
381                 if (res != ERROR_OK) {
382                         LOG_ERROR("Couldn't read code region 0 size[UICR]");
383                         return res;
384                 }
385         }
386
387         for (int i = 0; i < bank->num_sectors; i++)
388                 bank->sectors[i].is_protected =
389                         clenr0 != 0xFFFFFFFF && bank->sectors[i].offset < clenr0;
390
391         return ERROR_OK;
392 }
393
394 static int nrf5_protect(struct flash_bank *bank, int set, int first, int last)
395 {
396         int res;
397         uint32_t clenr0, ppfc;
398         struct nrf5_info *chip;
399
400         /* UICR cannot be write protected so just bail out early */
401         if (bank->base == NRF5_UICR_BASE)
402                 return ERROR_FAIL;
403
404         res = nrf5_get_probed_chip_if_halted(bank, &chip);
405         if (res != ERROR_OK)
406                 return res;
407
408         if (first != 0) {
409                 LOG_ERROR("Code region 0 must start at the begining of the bank");
410                 return ERROR_FAIL;
411         }
412
413         res = target_read_u32(chip->target, NRF5_FICR_PPFC,
414                               &ppfc);
415         if (res != ERROR_OK) {
416                 LOG_ERROR("Couldn't read PPFC register");
417                 return res;
418         }
419
420         if ((ppfc & 0xFF) == 0x00) {
421                 LOG_ERROR("Code region 0 size was pre-programmed at the factory, can't change flash protection settings");
422                 return ERROR_FAIL;
423         }
424
425         res = target_read_u32(chip->target, NRF5_UICR_CLENR0,
426                               &clenr0);
427         if (res != ERROR_OK) {
428                 LOG_ERROR("Couldn't read code region 0 size[UICR]");
429                 return res;
430         }
431
432         if (clenr0 == 0xFFFFFFFF) {
433                 res = target_write_u32(chip->target, NRF5_UICR_CLENR0,
434                                        clenr0);
435                 if (res != ERROR_OK) {
436                         LOG_ERROR("Couldn't write code region 0 size[UICR]");
437                         return res;
438                 }
439
440         } else {
441                 LOG_ERROR("You need to perform chip erase before changing the protection settings");
442         }
443
444         nrf5_protect_check(bank);
445
446         return ERROR_OK;
447 }
448
449 static int nrf5_probe(struct flash_bank *bank)
450 {
451         uint32_t hwid;
452         int res;
453         struct nrf5_info *chip = bank->driver_priv;
454
455         res = target_read_u32(chip->target, NRF5_FICR_CONFIGID, &hwid);
456         if (res != ERROR_OK) {
457                 LOG_ERROR("Couldn't read CONFIGID register");
458                 return res;
459         }
460
461         hwid &= 0xFFFF; /* HWID is stored in the lower two
462                          * bytes of the CONFIGID register */
463
464         const struct nrf5_device_spec *spec = NULL;
465         for (size_t i = 0; i < ARRAY_SIZE(nrf5_known_devices_table); i++) {
466                 if (hwid == nrf5_known_devices_table[i].hwid) {
467                         spec = &nrf5_known_devices_table[i];
468                         break;
469                 }
470         }
471
472         if (!chip->bank[0].probed && !chip->bank[1].probed) {
473                 if (spec)
474                         LOG_INFO("nRF%s-%s(build code: %s) %ukB Flash",
475                                  spec->part, spec->variant, spec->build_code,
476                                  spec->flash_size_kb);
477                 else
478                         LOG_WARNING("Unknown device (HWID 0x%08" PRIx32 ")", hwid);
479         }
480
481         if (bank->base == NRF5_FLASH_BASE) {
482                 /* The value stored in NRF5_FICR_CODEPAGESIZE is the number of bytes in one page of FLASH. */
483                 res = target_read_u32(chip->target, NRF5_FICR_CODEPAGESIZE,
484                                 &chip->code_page_size);
485                 if (res != ERROR_OK) {
486                         LOG_ERROR("Couldn't read code page size");
487                         return res;
488                 }
489
490                 /* Note the register name is misleading,
491                  * NRF5_FICR_CODESIZE is the number of pages in flash memory, not the number of bytes! */
492                 uint32_t num_sectors;
493                 res = target_read_u32(chip->target, NRF5_FICR_CODESIZE, &num_sectors);
494                 if (res != ERROR_OK) {
495                         LOG_ERROR("Couldn't read code memory size");
496                         return res;
497                 }
498
499                 bank->num_sectors = num_sectors;
500                 bank->size = num_sectors * chip->code_page_size;
501
502                 if (spec && bank->size / 1024 != spec->flash_size_kb)
503                         LOG_WARNING("Chip's reported Flash capacity does not match expected one");
504
505                 bank->sectors = calloc(bank->num_sectors,
506                                        sizeof((bank->sectors)[0]));
507                 if (!bank->sectors)
508                         return ERROR_FLASH_BANK_NOT_PROBED;
509
510                 /* Fill out the sector information: all NRF5 sectors are the same size and
511                  * there is always a fixed number of them. */
512                 for (int i = 0; i < bank->num_sectors; i++) {
513                         bank->sectors[i].size = chip->code_page_size;
514                         bank->sectors[i].offset = i * chip->code_page_size;
515
516                         /* mark as unknown */
517                         bank->sectors[i].is_erased = -1;
518                         bank->sectors[i].is_protected = -1;
519                 }
520
521                 nrf5_protect_check(bank);
522
523                 chip->bank[0].probed = true;
524         } else {
525                 bank->size = NRF5_UICR_SIZE;
526                 bank->num_sectors = 1;
527                 bank->sectors = calloc(bank->num_sectors,
528                                        sizeof((bank->sectors)[0]));
529                 if (!bank->sectors)
530                         return ERROR_FLASH_BANK_NOT_PROBED;
531
532                 bank->sectors[0].size = bank->size;
533                 bank->sectors[0].offset = 0;
534
535                 bank->sectors[0].is_erased = 0;
536                 bank->sectors[0].is_protected = 0;
537
538                 chip->bank[1].probed = true;
539         }
540
541         return ERROR_OK;
542 }
543
544 static int nrf5_auto_probe(struct flash_bank *bank)
545 {
546         int probed = nrf5_bank_is_probed(bank);
547
548         if (probed < 0)
549                 return probed;
550         else if (probed)
551                 return ERROR_OK;
552         else
553                 return nrf5_probe(bank);
554 }
555
556 static int nrf5_erase_all(struct nrf5_info *chip)
557 {
558         LOG_DEBUG("Erasing all non-volatile memory");
559         return nrf5_nvmc_generic_erase(chip,
560                                         NRF5_NVMC_ERASEALL,
561                                         0x00000001);
562 }
563
564 static int nrf5_erase_page(struct flash_bank *bank,
565                                                         struct nrf5_info *chip,
566                                                         struct flash_sector *sector)
567 {
568         int res;
569
570         LOG_DEBUG("Erasing page at 0x%"PRIx32, sector->offset);
571         if (sector->is_protected) {
572                 LOG_ERROR("Cannot erase protected sector at 0x%" PRIx32, sector->offset);
573                 return ERROR_FAIL;
574         }
575
576         if (bank->base == NRF5_UICR_BASE) {
577                 uint32_t ppfc;
578                 res = target_read_u32(chip->target, NRF5_FICR_PPFC,
579                                       &ppfc);
580                 if (res != ERROR_OK) {
581                         LOG_ERROR("Couldn't read PPFC register");
582                         return res;
583                 }
584
585                 if ((ppfc & 0xFF) == 0xFF) {
586                         /* We can't erase the UICR.  Double-check to
587                            see if it's already erased before complaining. */
588                         default_flash_blank_check(bank);
589                         if (sector->is_erased == 1)
590                                 return ERROR_OK;
591
592                         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");
593                         return ERROR_FAIL;
594                 }
595
596                 res = nrf5_nvmc_generic_erase(chip,
597                                                NRF5_NVMC_ERASEUICR,
598                                                0x00000001);
599
600
601         } else {
602                 res = nrf5_nvmc_generic_erase(chip,
603                                                NRF5_NVMC_ERASEPAGE,
604                                                sector->offset);
605         }
606
607         return res;
608 }
609
610 static const uint8_t nrf5_flash_write_code[] = {
611         /* See contrib/loaders/flash/cortex-m0.S */
612 /* <wait_fifo>: */
613         0x0d, 0x68,             /* ldr  r5,     [r1,    #0] */
614         0x00, 0x2d,             /* cmp  r5,     #0 */
615         0x0b, 0xd0,             /* beq.n        1e <exit> */
616         0x4c, 0x68,             /* ldr  r4,     [r1,    #4] */
617         0xac, 0x42,             /* cmp  r4,     r5 */
618         0xf9, 0xd0,             /* beq.n        0 <wait_fifo> */
619         0x20, 0xcc,             /* ldmia        r4!,    {r5} */
620         0x20, 0xc3,             /* stmia        r3!,    {r5} */
621         0x94, 0x42,             /* cmp  r4,     r2 */
622         0x01, 0xd3,             /* bcc.n        18 <no_wrap> */
623         0x0c, 0x46,             /* mov  r4,     r1 */
624         0x08, 0x34,             /* adds r4,     #8 */
625 /* <no_wrap>: */
626         0x4c, 0x60,             /* str  r4, [r1,        #4] */
627         0x04, 0x38,             /* subs r0, #4 */
628         0xf0, 0xd1,             /* bne.n        0 <wait_fifo> */
629 /* <exit>: */
630         0x00, 0xbe              /* bkpt 0x0000 */
631 };
632
633
634 /* Start a low level flash write for the specified region */
635 static int nrf5_ll_flash_write(struct nrf5_info *chip, uint32_t offset, const uint8_t *buffer, uint32_t bytes)
636 {
637         struct target *target = chip->target;
638         uint32_t buffer_size = 8192;
639         struct working_area *write_algorithm;
640         struct working_area *source;
641         uint32_t address = NRF5_FLASH_BASE + offset;
642         struct reg_param reg_params[4];
643         struct armv7m_algorithm armv7m_info;
644         int retval = ERROR_OK;
645
646
647         LOG_DEBUG("Writing buffer to flash offset=0x%"PRIx32" bytes=0x%"PRIx32, offset, bytes);
648         assert(bytes % 4 == 0);
649
650         /* allocate working area with flash programming code */
651         if (target_alloc_working_area(target, sizeof(nrf5_flash_write_code),
652                         &write_algorithm) != ERROR_OK) {
653                 LOG_WARNING("no working area available, falling back to slow memory writes");
654
655                 for (; bytes > 0; bytes -= 4) {
656                         retval = target_write_memory(chip->target, offset, 4, 1, buffer);
657                         if (retval != ERROR_OK)
658                                 return retval;
659
660                         retval = nrf5_wait_for_nvmc(chip);
661                         if (retval != ERROR_OK)
662                                 return retval;
663
664                         offset += 4;
665                         buffer += 4;
666                 }
667
668                 return ERROR_OK;
669         }
670
671         LOG_WARNING("using fast async flash loader. This is currently supported");
672         LOG_WARNING("only with ST-Link and CMSIS-DAP. If you have issues, add");
673         LOG_WARNING("\"set WORKAREASIZE 0\" before sourcing nrf51.cfg/nrf52.cfg to disable it");
674
675         retval = target_write_buffer(target, write_algorithm->address,
676                                 sizeof(nrf5_flash_write_code),
677                                 nrf5_flash_write_code);
678         if (retval != ERROR_OK)
679                 return retval;
680
681         /* memory buffer */
682         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
683                 buffer_size /= 2;
684                 buffer_size &= ~3UL; /* Make sure it's 4 byte aligned */
685                 if (buffer_size <= 256) {
686                         /* free working area, write algorithm already allocated */
687                         target_free_working_area(target, write_algorithm);
688
689                         LOG_WARNING("No large enough working area available, can't do block memory writes");
690                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
691                 }
692         }
693
694         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
695         armv7m_info.core_mode = ARM_MODE_THREAD;
696
697         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* byte count */
698         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* buffer start */
699         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* buffer end */
700         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN_OUT); /* target address */
701
702         buf_set_u32(reg_params[0].value, 0, 32, bytes);
703         buf_set_u32(reg_params[1].value, 0, 32, source->address);
704         buf_set_u32(reg_params[2].value, 0, 32, source->address + source->size);
705         buf_set_u32(reg_params[3].value, 0, 32, address);
706
707         retval = target_run_flash_async_algorithm(target, buffer, bytes/4, 4,
708                         0, NULL,
709                         4, reg_params,
710                         source->address, source->size,
711                         write_algorithm->address, 0,
712                         &armv7m_info);
713
714         target_free_working_area(target, source);
715         target_free_working_area(target, write_algorithm);
716
717         destroy_reg_param(&reg_params[0]);
718         destroy_reg_param(&reg_params[1]);
719         destroy_reg_param(&reg_params[2]);
720         destroy_reg_param(&reg_params[3]);
721
722         return retval;
723 }
724
725 /* Check and erase flash sectors in specified range then start a low level page write.
726    start/end must be sector aligned.
727 */
728 static int nrf5_write_pages(struct flash_bank *bank, uint32_t start, uint32_t end, const uint8_t *buffer)
729 {
730         int res = ERROR_FAIL;
731         struct nrf5_info *chip = bank->driver_priv;
732
733         assert(start % chip->code_page_size == 0);
734         assert(end % chip->code_page_size == 0);
735
736         res = nrf5_nvmc_write_enable(chip);
737         if (res != ERROR_OK)
738                 goto error;
739
740         res = nrf5_ll_flash_write(chip, start, buffer, (end - start));
741         if (res != ERROR_OK)
742                 goto error;
743
744         return nrf5_nvmc_read_only(chip);
745
746 error:
747         nrf5_nvmc_read_only(chip);
748         LOG_ERROR("Failed to write to nrf5 flash");
749         return res;
750 }
751
752 static int nrf5_erase(struct flash_bank *bank, int first, int last)
753 {
754         int res;
755         struct nrf5_info *chip;
756
757         res = nrf5_get_probed_chip_if_halted(bank, &chip);
758         if (res != ERROR_OK)
759                 return res;
760
761         /* For each sector to be erased */
762         for (int s = first; s <= last && res == ERROR_OK; s++)
763                 res = nrf5_erase_page(bank, chip, &bank->sectors[s]);
764
765         return res;
766 }
767
768 static int nrf5_code_flash_write(struct flash_bank *bank,
769                                   struct nrf5_info *chip,
770                                   const uint8_t *buffer, uint32_t offset, uint32_t count)
771 {
772
773         int res;
774         /* Need to perform reads to fill any gaps we need to preserve in the first page,
775            before the start of buffer, or in the last page, after the end of buffer */
776         uint32_t first_page = offset/chip->code_page_size;
777         uint32_t last_page = DIV_ROUND_UP(offset+count, chip->code_page_size);
778
779         uint32_t first_page_offset = first_page * chip->code_page_size;
780         uint32_t last_page_offset = last_page * chip->code_page_size;
781
782         LOG_DEBUG("Padding write from 0x%08"PRIx32"-0x%08"PRIx32" as 0x%08"PRIx32"-0x%08"PRIx32,
783                 offset, offset+count, first_page_offset, last_page_offset);
784
785         uint32_t page_cnt = last_page - first_page;
786         uint8_t buffer_to_flash[page_cnt*chip->code_page_size];
787
788         /* Fill in any space between start of first page and start of buffer */
789         uint32_t pre = offset - first_page_offset;
790         if (pre > 0) {
791                 res = target_read_memory(bank->target,
792                                         first_page_offset,
793                                         1,
794                                         pre,
795                                         buffer_to_flash);
796                 if (res != ERROR_OK)
797                         return res;
798         }
799
800         /* Fill in main contents of buffer */
801         memcpy(buffer_to_flash+pre, buffer, count);
802
803         /* Fill in any space between end of buffer and end of last page */
804         uint32_t post = last_page_offset - (offset+count);
805         if (post > 0) {
806                 /* Retrieve the full row contents from Flash */
807                 res = target_read_memory(bank->target,
808                                         offset + count,
809                                         1,
810                                         post,
811                                         buffer_to_flash+pre+count);
812                 if (res != ERROR_OK)
813                         return res;
814         }
815
816         return nrf5_write_pages(bank, first_page_offset, last_page_offset, buffer_to_flash);
817 }
818
819 static int nrf5_uicr_flash_write(struct flash_bank *bank,
820                                   struct nrf5_info *chip,
821                                   const uint8_t *buffer, uint32_t offset, uint32_t count)
822 {
823         int res;
824         uint8_t uicr[NRF5_UICR_SIZE];
825         struct flash_sector *sector = &bank->sectors[0];
826
827         if ((offset + count) > NRF5_UICR_SIZE)
828                 return ERROR_FAIL;
829
830         res = target_read_memory(bank->target,
831                                  NRF5_UICR_BASE,
832                                  1,
833                                  NRF5_UICR_SIZE,
834                                  uicr);
835
836         if (res != ERROR_OK)
837                 return res;
838
839         res = nrf5_erase_page(bank, chip, sector);
840         if (res != ERROR_OK)
841                 return res;
842
843         res = nrf5_nvmc_write_enable(chip);
844         if (res != ERROR_OK)
845                 return res;
846
847         memcpy(&uicr[offset], buffer, count);
848
849         res = nrf5_ll_flash_write(chip, NRF5_UICR_BASE, uicr, NRF5_UICR_SIZE);
850         if (res != ERROR_OK) {
851                 nrf5_nvmc_read_only(chip);
852                 return res;
853         }
854
855         return nrf5_nvmc_read_only(chip);
856 }
857
858
859 static int nrf5_write(struct flash_bank *bank, const uint8_t *buffer,
860                        uint32_t offset, uint32_t count)
861 {
862         int res;
863         struct nrf5_info *chip;
864
865         res = nrf5_get_probed_chip_if_halted(bank, &chip);
866         if (res != ERROR_OK)
867                 return res;
868
869         return chip->bank[bank->bank_number].write(bank, chip, buffer, offset, count);
870 }
871
872
873 FLASH_BANK_COMMAND_HANDLER(nrf5_flash_bank_command)
874 {
875         static struct nrf5_info *chip;
876
877         switch (bank->base) {
878         case NRF5_FLASH_BASE:
879                 bank->bank_number = 0;
880                 break;
881         case NRF5_UICR_BASE:
882                 bank->bank_number = 1;
883                 break;
884         default:
885                 LOG_ERROR("Invalid bank address 0x%08" PRIx32, bank->base);
886                 return ERROR_FAIL;
887         }
888
889         if (!chip) {
890                 /* Create a new chip */
891                 chip = calloc(1, sizeof(*chip));
892                 if (!chip)
893                         return ERROR_FAIL;
894
895                 chip->target = bank->target;
896         }
897
898         switch (bank->base) {
899         case NRF5_FLASH_BASE:
900                 chip->bank[bank->bank_number].write = nrf5_code_flash_write;
901                 break;
902         case NRF5_UICR_BASE:
903                 chip->bank[bank->bank_number].write = nrf5_uicr_flash_write;
904                 break;
905         }
906
907         chip->bank[bank->bank_number].probed = false;
908         bank->driver_priv = chip;
909
910         return ERROR_OK;
911 }
912
913 COMMAND_HANDLER(nrf5_handle_mass_erase_command)
914 {
915         int res;
916         struct flash_bank *bank = NULL;
917         struct target *target = get_current_target(CMD_CTX);
918
919         res = get_flash_bank_by_addr(target, NRF5_FLASH_BASE, true, &bank);
920         if (res != ERROR_OK)
921                 return res;
922
923         assert(bank != NULL);
924
925         struct nrf5_info *chip;
926
927         res = nrf5_get_probed_chip_if_halted(bank, &chip);
928         if (res != ERROR_OK)
929                 return res;
930
931         uint32_t ppfc;
932
933         res = target_read_u32(target, NRF5_FICR_PPFC,
934                               &ppfc);
935         if (res != ERROR_OK) {
936                 LOG_ERROR("Couldn't read PPFC register");
937                 return res;
938         }
939
940         if ((ppfc & 0xFF) == 0x00) {
941                 LOG_ERROR("Code region 0 size was pre-programmed at the factory, "
942                           "mass erase command won't work.");
943                 return ERROR_FAIL;
944         }
945
946         res = nrf5_erase_all(chip);
947         if (res != ERROR_OK) {
948                 LOG_ERROR("Failed to erase the chip");
949                 nrf5_protect_check(bank);
950                 return res;
951         }
952
953         res = nrf5_protect_check(bank);
954         if (res != ERROR_OK) {
955                 LOG_ERROR("Failed to check chip's write protection");
956                 return res;
957         }
958
959         res = get_flash_bank_by_addr(target, NRF5_UICR_BASE, true, &bank);
960         if (res != ERROR_OK)
961                 return res;
962
963         return ERROR_OK;
964 }
965
966 static int nrf5_info(struct flash_bank *bank, char *buf, int buf_size)
967 {
968         int res;
969
970         struct nrf5_info *chip;
971
972         res = nrf5_get_probed_chip_if_halted(bank, &chip);
973         if (res != ERROR_OK)
974                 return res;
975
976         static struct {
977                 const uint32_t address;
978                 uint32_t value;
979         } ficr[] = {
980                 { .address = NRF5_FICR_CODEPAGESIZE     },
981                 { .address = NRF5_FICR_CODESIZE },
982                 { .address = NRF5_FICR_CLENR0           },
983                 { .address = NRF5_FICR_PPFC             },
984                 { .address = NRF5_FICR_NUMRAMBLOCK      },
985                 { .address = NRF5_FICR_SIZERAMBLOCK0    },
986                 { .address = NRF5_FICR_SIZERAMBLOCK1    },
987                 { .address = NRF5_FICR_SIZERAMBLOCK2    },
988                 { .address = NRF5_FICR_SIZERAMBLOCK3    },
989                 { .address = NRF5_FICR_CONFIGID },
990                 { .address = NRF5_FICR_DEVICEID0        },
991                 { .address = NRF5_FICR_DEVICEID1        },
992                 { .address = NRF5_FICR_ER0              },
993                 { .address = NRF5_FICR_ER1              },
994                 { .address = NRF5_FICR_ER2              },
995                 { .address = NRF5_FICR_ER3              },
996                 { .address = NRF5_FICR_IR0              },
997                 { .address = NRF5_FICR_IR1              },
998                 { .address = NRF5_FICR_IR2              },
999                 { .address = NRF5_FICR_IR3              },
1000                 { .address = NRF5_FICR_DEVICEADDRTYPE   },
1001                 { .address = NRF5_FICR_DEVICEADDR0      },
1002                 { .address = NRF5_FICR_DEVICEADDR1      },
1003                 { .address = NRF5_FICR_OVERRIDEN        },
1004                 { .address = NRF5_FICR_NRF_1MBIT0       },
1005                 { .address = NRF5_FICR_NRF_1MBIT1       },
1006                 { .address = NRF5_FICR_NRF_1MBIT2       },
1007                 { .address = NRF5_FICR_NRF_1MBIT3       },
1008                 { .address = NRF5_FICR_NRF_1MBIT4       },
1009                 { .address = NRF5_FICR_BLE_1MBIT0       },
1010                 { .address = NRF5_FICR_BLE_1MBIT1       },
1011                 { .address = NRF5_FICR_BLE_1MBIT2       },
1012                 { .address = NRF5_FICR_BLE_1MBIT3       },
1013                 { .address = NRF5_FICR_BLE_1MBIT4       },
1014         }, uicr[] = {
1015                 { .address = NRF5_UICR_CLENR0,          },
1016                 { .address = NRF5_UICR_RBPCONF          },
1017                 { .address = NRF5_UICR_XTALFREQ },
1018                 { .address = NRF5_UICR_FWID             },
1019         };
1020
1021         for (size_t i = 0; i < ARRAY_SIZE(ficr); i++) {
1022                 res = target_read_u32(chip->target, ficr[i].address,
1023                                       &ficr[i].value);
1024                 if (res != ERROR_OK) {
1025                         LOG_ERROR("Couldn't read %" PRIx32, ficr[i].address);
1026                         return res;
1027                 }
1028         }
1029
1030         for (size_t i = 0; i < ARRAY_SIZE(uicr); i++) {
1031                 res = target_read_u32(chip->target, uicr[i].address,
1032                                       &uicr[i].value);
1033                 if (res != ERROR_OK) {
1034                         LOG_ERROR("Couldn't read %" PRIx32, uicr[i].address);
1035                         return res;
1036                 }
1037         }
1038
1039         snprintf(buf, buf_size,
1040                  "\n[factory information control block]\n\n"
1041                  "code page size: %"PRIu32"B\n"
1042                  "code memory size: %"PRIu32"kB\n"
1043                  "code region 0 size: %"PRIu32"kB\n"
1044                  "pre-programmed code: %s\n"
1045                  "number of ram blocks: %"PRIu32"\n"
1046                  "ram block 0 size: %"PRIu32"B\n"
1047                  "ram block 1 size: %"PRIu32"B\n"
1048                  "ram block 2 size: %"PRIu32"B\n"
1049                  "ram block 3 size: %"PRIu32 "B\n"
1050                  "config id: %" PRIx32 "\n"
1051                  "device id: 0x%"PRIx32"%08"PRIx32"\n"
1052                  "encryption root: 0x%08"PRIx32"%08"PRIx32"%08"PRIx32"%08"PRIx32"\n"
1053                  "identity root: 0x%08"PRIx32"%08"PRIx32"%08"PRIx32"%08"PRIx32"\n"
1054                  "device address type: 0x%"PRIx32"\n"
1055                  "device address: 0x%"PRIx32"%08"PRIx32"\n"
1056                  "override enable: %"PRIx32"\n"
1057                  "NRF_1MBIT values: %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32"\n"
1058                  "BLE_1MBIT values: %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32"\n"
1059                  "\n[user information control block]\n\n"
1060                  "code region 0 size: %"PRIu32"kB\n"
1061                  "read back protection configuration: %"PRIx32"\n"
1062                  "reset value for XTALFREQ: %"PRIx32"\n"
1063                  "firmware id: 0x%04"PRIx32,
1064                  ficr[0].value,
1065                  (ficr[1].value * ficr[0].value) / 1024,
1066                  (ficr[2].value == 0xFFFFFFFF) ? 0 : ficr[2].value / 1024,
1067                  ((ficr[3].value & 0xFF) == 0x00) ? "present" : "not present",
1068                  ficr[4].value,
1069                  ficr[5].value,
1070                  (ficr[6].value == 0xFFFFFFFF) ? 0 : ficr[6].value,
1071                  (ficr[7].value == 0xFFFFFFFF) ? 0 : ficr[7].value,
1072                  (ficr[8].value == 0xFFFFFFFF) ? 0 : ficr[8].value,
1073                  ficr[9].value,
1074                  ficr[10].value, ficr[11].value,
1075                  ficr[12].value, ficr[13].value, ficr[14].value, ficr[15].value,
1076                  ficr[16].value, ficr[17].value, ficr[18].value, ficr[19].value,
1077                  ficr[20].value,
1078                  ficr[21].value, ficr[22].value,
1079                  ficr[23].value,
1080                  ficr[24].value, ficr[25].value, ficr[26].value, ficr[27].value, ficr[28].value,
1081                  ficr[29].value, ficr[30].value, ficr[31].value, ficr[32].value, ficr[33].value,
1082                  (uicr[0].value == 0xFFFFFFFF) ? 0 : uicr[0].value / 1024,
1083                  uicr[1].value & 0xFFFF,
1084                  uicr[2].value & 0xFF,
1085                  uicr[3].value & 0xFFFF);
1086
1087         return ERROR_OK;
1088 }
1089
1090 static const struct command_registration nrf5_exec_command_handlers[] = {
1091         {
1092                 .name           = "mass_erase",
1093                 .handler        = nrf5_handle_mass_erase_command,
1094                 .mode           = COMMAND_EXEC,
1095                 .help           = "Erase all flash contents of the chip.",
1096         },
1097         COMMAND_REGISTRATION_DONE
1098 };
1099
1100 static const struct command_registration nrf5_command_handlers[] = {
1101         {
1102                 .name   = "nrf5",
1103                 .mode   = COMMAND_ANY,
1104                 .help   = "nrf5 flash command group",
1105                 .usage  = "",
1106                 .chain  = nrf5_exec_command_handlers,
1107         },
1108         {
1109                 .name   = "nrf51",
1110                 .mode   = COMMAND_ANY,
1111                 .help   = "nrf51 flash command group",
1112                 .usage  = "",
1113                 .chain  = nrf5_exec_command_handlers,
1114         },
1115         COMMAND_REGISTRATION_DONE
1116 };
1117
1118 struct flash_driver nrf5_flash = {
1119         .name                   = "nrf5",
1120         .commands               = nrf5_command_handlers,
1121         .flash_bank_command     = nrf5_flash_bank_command,
1122         .info                   = nrf5_info,
1123         .erase                  = nrf5_erase,
1124         .protect                = nrf5_protect,
1125         .write                  = nrf5_write,
1126         .read                   = default_flash_read,
1127         .probe                  = nrf5_probe,
1128         .auto_probe             = nrf5_auto_probe,
1129         .erase_check            = default_flash_blank_check,
1130         .protect_check          = nrf5_protect_check,
1131 };
1132
1133 /* We need to retain the flash-driver name as well as the commands
1134  * for backwards compatability */
1135 struct flash_driver nrf51_flash = {
1136         .name                   = "nrf51",
1137         .commands               = nrf5_command_handlers,
1138         .flash_bank_command     = nrf5_flash_bank_command,
1139         .info                   = nrf5_info,
1140         .erase                  = nrf5_erase,
1141         .protect                = nrf5_protect,
1142         .write                  = nrf5_write,
1143         .read                   = default_flash_read,
1144         .probe                  = nrf5_probe,
1145         .auto_probe             = nrf5_auto_probe,
1146         .erase_check            = default_flash_blank_check,
1147         .protect_check          = nrf5_protect_check,
1148 };