9d2565b0100ec540dc1595c7417db1a70d5be74f
[fw/openocd] / src / flash / nor / nrf5.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 /***************************************************************************
4  *   Copyright (C) 2013 Synapse Product Development                        *
5  *   Andrey Smirnov <andrew.smironv@gmail.com>                             *
6  *   Angus Gratton <gus@projectgus.com>                                    *
7  *   Erdem U. Altunyurt <spamjunkeater@gmail.com>                          *
8  ***************************************************************************/
9
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
13
14 #include "imp.h"
15 #include <helper/binarybuffer.h>
16 #include <target/algorithm.h>
17 #include <target/armv7m.h>
18 #include <helper/types.h>
19 #include <helper/time_support.h>
20
21 /* Both those values are constant across the current spectrum ofr nRF5 devices */
22 #define WATCHDOG_REFRESH_REGISTER       0x40010600
23 #define WATCHDOG_REFRESH_VALUE          0x6e524635
24
25 enum {
26         NRF5_FLASH_BASE = 0x00000000,
27 };
28
29 enum nrf5_ficr_registers {
30         NRF5_FICR_BASE = 0x10000000, /* Factory Information Configuration Registers */
31
32 #define NRF5_FICR_REG(offset) (NRF5_FICR_BASE + offset)
33
34         NRF5_FICR_CODEPAGESIZE          = NRF5_FICR_REG(0x010),
35         NRF5_FICR_CODESIZE              = NRF5_FICR_REG(0x014),
36
37         NRF51_FICR_CLENR0               = NRF5_FICR_REG(0x028),
38         NRF51_FICR_PPFC                 = NRF5_FICR_REG(0x02C),
39         NRF51_FICR_NUMRAMBLOCK          = NRF5_FICR_REG(0x034),
40         NRF51_FICR_SIZERAMBLOCK0        = NRF5_FICR_REG(0x038),
41         NRF51_FICR_SIZERAMBLOCK1        = NRF5_FICR_REG(0x03C),
42         NRF51_FICR_SIZERAMBLOCK2        = NRF5_FICR_REG(0x040),
43         NRF51_FICR_SIZERAMBLOCK3        = NRF5_FICR_REG(0x044),
44
45         NRF5_FICR_CONFIGID              = NRF5_FICR_REG(0x05C),
46         NRF5_FICR_DEVICEID0             = NRF5_FICR_REG(0x060),
47         NRF5_FICR_DEVICEID1             = NRF5_FICR_REG(0x064),
48         NRF5_FICR_ER0                   = NRF5_FICR_REG(0x080),
49         NRF5_FICR_ER1                   = NRF5_FICR_REG(0x084),
50         NRF5_FICR_ER2                   = NRF5_FICR_REG(0x088),
51         NRF5_FICR_ER3                   = NRF5_FICR_REG(0x08C),
52         NRF5_FICR_IR0                   = NRF5_FICR_REG(0x090),
53         NRF5_FICR_IR1                   = NRF5_FICR_REG(0x094),
54         NRF5_FICR_IR2                   = NRF5_FICR_REG(0x098),
55         NRF5_FICR_IR3                   = NRF5_FICR_REG(0x09C),
56         NRF5_FICR_DEVICEADDRTYPE        = NRF5_FICR_REG(0x0A0),
57         NRF5_FICR_DEVICEADDR0           = NRF5_FICR_REG(0x0A4),
58         NRF5_FICR_DEVICEADDR1           = NRF5_FICR_REG(0x0A8),
59
60         NRF51_FICR_OVERRIDEN            = NRF5_FICR_REG(0x0AC),
61         NRF51_FICR_NRF_1MBIT0           = NRF5_FICR_REG(0x0B0),
62         NRF51_FICR_NRF_1MBIT1           = NRF5_FICR_REG(0x0B4),
63         NRF51_FICR_NRF_1MBIT2           = NRF5_FICR_REG(0x0B8),
64         NRF51_FICR_NRF_1MBIT3           = NRF5_FICR_REG(0x0BC),
65         NRF51_FICR_NRF_1MBIT4           = NRF5_FICR_REG(0x0C0),
66         NRF51_FICR_BLE_1MBIT0           = NRF5_FICR_REG(0x0EC),
67         NRF51_FICR_BLE_1MBIT1           = NRF5_FICR_REG(0x0F0),
68         NRF51_FICR_BLE_1MBIT2           = NRF5_FICR_REG(0x0F4),
69         NRF51_FICR_BLE_1MBIT3           = NRF5_FICR_REG(0x0F8),
70         NRF51_FICR_BLE_1MBIT4           = NRF5_FICR_REG(0x0FC),
71
72         /* Following registers are available on nRF52 and on nRF51 since rev 3 */
73         NRF5_FICR_INFO_PART                     = NRF5_FICR_REG(0x100),
74         NRF5_FICR_INFO_VARIANT          = NRF5_FICR_REG(0x104),
75         NRF5_FICR_INFO_PACKAGE          = NRF5_FICR_REG(0x108),
76         NRF5_FICR_INFO_RAM                      = NRF5_FICR_REG(0x10C),
77         NRF5_FICR_INFO_FLASH            = NRF5_FICR_REG(0x110),
78 };
79
80 enum nrf5_uicr_registers {
81         NRF5_UICR_BASE = 0x10001000, /* User Information
82                                        * Configuration Registers */
83
84 #define NRF5_UICR_REG(offset) (NRF5_UICR_BASE + offset)
85
86         NRF51_UICR_CLENR0       = NRF5_UICR_REG(0x000),
87         NRF51_UICR_RBPCONF      = NRF5_UICR_REG(0x004),
88         NRF51_UICR_XTALFREQ     = NRF5_UICR_REG(0x008),
89         NRF51_UICR_FWID         = NRF5_UICR_REG(0x010),
90 };
91
92 enum nrf5_nvmc_registers {
93         NRF5_NVMC_BASE = 0x4001E000, /* Non-Volatile Memory
94                                        * Controller Registers */
95
96 #define NRF5_NVMC_REG(offset) (NRF5_NVMC_BASE + offset)
97
98         NRF5_NVMC_READY = NRF5_NVMC_REG(0x400),
99         NRF5_NVMC_CONFIG        = NRF5_NVMC_REG(0x504),
100         NRF5_NVMC_ERASEPAGE     = NRF5_NVMC_REG(0x508),
101         NRF5_NVMC_ERASEALL      = NRF5_NVMC_REG(0x50C),
102         NRF5_NVMC_ERASEUICR     = NRF5_NVMC_REG(0x514),
103
104         NRF5_BPROT_BASE = 0x40000000,
105 };
106
107 enum nrf5_nvmc_config_bits {
108         NRF5_NVMC_CONFIG_REN = 0x00,
109         NRF5_NVMC_CONFIG_WEN = 0x01,
110         NRF5_NVMC_CONFIG_EEN = 0x02,
111
112 };
113
114 struct nrf52_ficr_info {
115         uint32_t part;
116         uint32_t variant;
117         uint32_t package;
118         uint32_t ram;
119         uint32_t flash;
120 };
121
122 enum nrf5_features {
123         NRF5_FEATURE_SERIES_51  = 1 << 0,
124         NRF5_FEATURE_SERIES_52  = 1 << 1,
125         NRF5_FEATURE_BPROT              = 1 << 2,
126         NRF5_FEATURE_ACL_PROT   = 1 << 3,
127 };
128
129 struct nrf5_device_spec {
130         uint16_t hwid;
131         const char *part;
132         const char *variant;
133         const char *build_code;
134         unsigned int flash_size_kb;
135         enum nrf5_features features;
136 };
137
138 struct nrf5_info {
139         unsigned int refcount;
140
141         struct nrf5_bank {
142                 struct nrf5_info *chip;
143                 bool probed;
144         } bank[2];
145         struct target *target;
146
147         /* chip identification stored in nrf5_probe() for use in nrf5_info() */
148         bool ficr_info_valid;
149         struct nrf52_ficr_info ficr_info;
150         const struct nrf5_device_spec *spec;
151         uint16_t hwid;
152         enum nrf5_features features;
153         unsigned int flash_size_kb;
154         unsigned int ram_size_kb;
155 };
156
157 #define NRF51_DEVICE_DEF(id, pt, var, bcode, fsize) \
158 {                                                   \
159 .hwid          = (id),                              \
160 .part          = pt,                                \
161 .variant       = var,                               \
162 .build_code    = bcode,                             \
163 .flash_size_kb = (fsize),                           \
164 .features      = NRF5_FEATURE_SERIES_51,            \
165 }
166
167 #define NRF5_DEVICE_DEF(id, pt, var, bcode, fsize, features) \
168 {                                                   \
169 .hwid          = (id),                              \
170 .part          = pt,                                \
171 .variant       = var,                               \
172 .build_code    = bcode,                             \
173 .flash_size_kb = (fsize),                           \
174 .features      = features,                          \
175 }
176
177 /* The known devices table below is derived from the "nRF5x series
178  * compatibility matrix" documents, which can be found in the "DocLib" of
179  * nordic:
180  *
181  * https://www.nordicsemi.com/DocLib/Content/Comp_Matrix/nRF51/latest/COMP/nrf51/nRF51422_ic_revision_overview
182  * https://www.nordicsemi.com/DocLib/Content/Comp_Matrix/nRF51/latest/COMP/nrf51/nRF51822_ic_revision_overview
183  * https://www.nordicsemi.com/DocLib/Content/Comp_Matrix/nRF51/latest/COMP/nrf51/nRF51824_ic_revision_overview
184  * https://www.nordicsemi.com/DocLib/Content/Comp_Matrix/nRF52810/latest/COMP/nrf52810/nRF52810_ic_revision_overview
185  * https://www.nordicsemi.com/DocLib/Content/Comp_Matrix/nRF52832/latest/COMP/nrf52832/ic_revision_overview
186  * https://www.nordicsemi.com/DocLib/Content/Comp_Matrix/nRF52840/latest/COMP/nrf52840/nRF52840_ic_revision_overview
187  *
188  * Up to date with Matrix v2.0, plus some additional HWIDs.
189  *
190  * The additional HWIDs apply where the build code in the matrix is
191  * shown as Gx0, Bx0, etc. In these cases the HWID in the matrix is
192  * for x==0, x!=0 means different (unspecified) HWIDs.
193  */
194 static const struct nrf5_device_spec nrf5_known_devices_table[] = {
195         /* nRF51822 Devices (IC rev 1). */
196         NRF51_DEVICE_DEF(0x001D, "51822", "QFAA", "CA/C0", 256),
197         NRF51_DEVICE_DEF(0x0026, "51822", "QFAB", "AA",    128),
198         NRF51_DEVICE_DEF(0x0027, "51822", "QFAB", "A0",    128),
199         NRF51_DEVICE_DEF(0x0020, "51822", "CEAA", "BA",    256),
200         NRF51_DEVICE_DEF(0x002F, "51822", "CEAA", "B0",    256),
201
202         /* Some early nRF51-DK (PCA10028) & nRF51-Dongle (PCA10031) boards
203            with built-in jlink seem to use engineering samples not listed
204            in the nRF51 Series Compatibility Matrix V1.0. */
205         NRF51_DEVICE_DEF(0x0071, "51822", "QFAC", "AB",    256),
206
207         /* nRF51822 Devices (IC rev 2). */
208         NRF51_DEVICE_DEF(0x002A, "51822", "QFAA", "FA0",   256),
209         NRF51_DEVICE_DEF(0x0044, "51822", "QFAA", "GC0",   256),
210         NRF51_DEVICE_DEF(0x003C, "51822", "QFAA", "G0",    256),
211         NRF51_DEVICE_DEF(0x0057, "51822", "QFAA", "G2",    256),
212         NRF51_DEVICE_DEF(0x0058, "51822", "QFAA", "G3",    256),
213         NRF51_DEVICE_DEF(0x004C, "51822", "QFAB", "B0",    128),
214         NRF51_DEVICE_DEF(0x0040, "51822", "CEAA", "CA0",   256),
215         NRF51_DEVICE_DEF(0x0047, "51822", "CEAA", "DA0",   256),
216         NRF51_DEVICE_DEF(0x004D, "51822", "CEAA", "D00",   256),
217
218         /* nRF51822 Devices (IC rev 3). */
219         NRF51_DEVICE_DEF(0x0072, "51822", "QFAA", "H0",    256),
220         NRF51_DEVICE_DEF(0x00D1, "51822", "QFAA", "H2",    256),
221         NRF51_DEVICE_DEF(0x007B, "51822", "QFAB", "C0",    128),
222         NRF51_DEVICE_DEF(0x0083, "51822", "QFAC", "A0",    256),
223         NRF51_DEVICE_DEF(0x0084, "51822", "QFAC", "A1",    256),
224         NRF51_DEVICE_DEF(0x007D, "51822", "CDAB", "A0",    128),
225         NRF51_DEVICE_DEF(0x0079, "51822", "CEAA", "E0",    256),
226         NRF51_DEVICE_DEF(0x0087, "51822", "CFAC", "A0",    256),
227         NRF51_DEVICE_DEF(0x008F, "51822", "QFAA", "H1",    256),
228
229         /* nRF51422 Devices (IC rev 1). */
230         NRF51_DEVICE_DEF(0x001E, "51422", "QFAA", "CA",    256),
231         NRF51_DEVICE_DEF(0x0024, "51422", "QFAA", "C0",    256),
232         NRF51_DEVICE_DEF(0x0031, "51422", "CEAA", "A0A",   256),
233
234         /* nRF51422 Devices (IC rev 2). */
235         NRF51_DEVICE_DEF(0x002D, "51422", "QFAA", "DAA",   256),
236         NRF51_DEVICE_DEF(0x002E, "51422", "QFAA", "E0",    256),
237         NRF51_DEVICE_DEF(0x0061, "51422", "QFAB", "A00",   128),
238         NRF51_DEVICE_DEF(0x0050, "51422", "CEAA", "B0",    256),
239
240         /* nRF51422 Devices (IC rev 3). */
241         NRF51_DEVICE_DEF(0x0073, "51422", "QFAA", "F0",    256),
242         NRF51_DEVICE_DEF(0x007C, "51422", "QFAB", "B0",    128),
243         NRF51_DEVICE_DEF(0x0085, "51422", "QFAC", "A0",    256),
244         NRF51_DEVICE_DEF(0x0086, "51422", "QFAC", "A1",    256),
245         NRF51_DEVICE_DEF(0x007E, "51422", "CDAB", "A0",    128),
246         NRF51_DEVICE_DEF(0x007A, "51422", "CEAA", "C0",    256),
247         NRF51_DEVICE_DEF(0x0088, "51422", "CFAC", "A0",    256),
248
249         /* The driver fully autodetects nRF52 series devices by FICR INFO,
250          * no need for nRF52xxx HWIDs in this table */
251 #if 0
252         /* nRF52810 Devices */
253         NRF5_DEVICE_DEF(0x0142, "52810", "QFAA", "B0",    192,  NRF5_FEATURE_SERIES_52 | NRF5_FEATURE_BPROT),
254         NRF5_DEVICE_DEF(0x0143, "52810", "QCAA", "C0",    192,  NRF5_FEATURE_SERIES_52 | NRF5_FEATURE_BPROT),
255
256         /* nRF52832 Devices */
257         NRF5_DEVICE_DEF(0x00C7, "52832", "QFAA", "B0",    512,  NRF5_FEATURE_SERIES_52 | NRF5_FEATURE_BPROT),
258         NRF5_DEVICE_DEF(0x0139, "52832", "QFAA", "E0",    512,  NRF5_FEATURE_SERIES_52 | NRF5_FEATURE_BPROT),
259         NRF5_DEVICE_DEF(0x00E3, "52832", "CIAA", "B0",    512,  NRF5_FEATURE_SERIES_52 | NRF5_FEATURE_BPROT),
260
261         /* nRF52840 Devices */
262         NRF5_DEVICE_DEF(0x0150, "52840", "QIAA", "C0",    1024, NRF5_FEATURE_SERIES_52 | NRF5_FEATURE_ACL_PROT),
263 #endif
264 };
265
266 struct nrf5_device_package {
267         uint32_t package;
268         const char *code;
269 };
270
271 /* Newer devices have FICR INFO.PACKAGE.
272  * This table converts its value to two character code */
273 static const struct nrf5_device_package nrf5_packages_table[] = {
274         { 0x2000, "QF" },
275         { 0x2001, "CH" },
276         { 0x2002, "CI" },
277         { 0x2005, "CK" },
278 };
279
280 const struct flash_driver nrf5_flash, nrf51_flash;
281
282 static bool nrf5_bank_is_probed(const struct flash_bank *bank)
283 {
284         struct nrf5_bank *nbank = bank->driver_priv;
285
286         assert(nbank);
287
288         return nbank->probed;
289 }
290 static int nrf5_probe(struct flash_bank *bank);
291
292 static int nrf5_get_probed_chip_if_halted(struct flash_bank *bank, struct nrf5_info **chip)
293 {
294         if (bank->target->state != TARGET_HALTED) {
295                 LOG_ERROR("Target not halted");
296                 return ERROR_TARGET_NOT_HALTED;
297         }
298
299         struct nrf5_bank *nbank = bank->driver_priv;
300         *chip = nbank->chip;
301
302         if (nrf5_bank_is_probed(bank))
303                 return ERROR_OK;
304
305         return nrf5_probe(bank);
306 }
307
308 static int nrf5_wait_for_nvmc(struct nrf5_info *chip)
309 {
310         uint32_t ready;
311         int res;
312         int timeout_ms = 340;
313         int64_t ts_start = timeval_ms();
314
315         do {
316                 res = target_read_u32(chip->target, NRF5_NVMC_READY, &ready);
317                 if (res != ERROR_OK) {
318                         LOG_ERROR("Error waiting NVMC_READY: generic flash write/erase error (check protection etc...)");
319                         return res;
320                 }
321
322                 if (ready == 0x00000001)
323                         return ERROR_OK;
324
325                 keep_alive();
326
327         } while ((timeval_ms()-ts_start) < timeout_ms);
328
329         LOG_DEBUG("Timed out waiting for NVMC_READY");
330         return ERROR_FLASH_BUSY;
331 }
332
333 static int nrf5_nvmc_erase_enable(struct nrf5_info *chip)
334 {
335         int res;
336         res = target_write_u32(chip->target,
337                                NRF5_NVMC_CONFIG,
338                                NRF5_NVMC_CONFIG_EEN);
339
340         if (res != ERROR_OK) {
341                 LOG_ERROR("Failed to enable erase operation");
342                 return res;
343         }
344
345         /*
346           According to NVMC examples in Nordic SDK busy status must be
347           checked after writing to NVMC_CONFIG
348          */
349         res = nrf5_wait_for_nvmc(chip);
350         if (res != ERROR_OK)
351                 LOG_ERROR("Erase enable did not complete");
352
353         return res;
354 }
355
356 static int nrf5_nvmc_write_enable(struct nrf5_info *chip)
357 {
358         int res;
359         res = target_write_u32(chip->target,
360                                NRF5_NVMC_CONFIG,
361                                NRF5_NVMC_CONFIG_WEN);
362
363         if (res != ERROR_OK) {
364                 LOG_ERROR("Failed to enable write operation");
365                 return res;
366         }
367
368         /*
369           According to NVMC examples in Nordic SDK busy status must be
370           checked after writing to NVMC_CONFIG
371          */
372         res = nrf5_wait_for_nvmc(chip);
373         if (res != ERROR_OK)
374                 LOG_ERROR("Write enable did not complete");
375
376         return res;
377 }
378
379 static int nrf5_nvmc_read_only(struct nrf5_info *chip)
380 {
381         int res;
382         res = target_write_u32(chip->target,
383                                NRF5_NVMC_CONFIG,
384                                NRF5_NVMC_CONFIG_REN);
385
386         if (res != ERROR_OK) {
387                 LOG_ERROR("Failed to enable read-only operation");
388                 return res;
389         }
390         /*
391           According to NVMC examples in Nordic SDK busy status must be
392           checked after writing to NVMC_CONFIG
393          */
394         res = nrf5_wait_for_nvmc(chip);
395         if (res != ERROR_OK)
396                 LOG_ERROR("Read only enable did not complete");
397
398         return res;
399 }
400
401 static int nrf5_nvmc_generic_erase(struct nrf5_info *chip,
402                                uint32_t erase_register, uint32_t erase_value)
403 {
404         int res;
405
406         res = nrf5_nvmc_erase_enable(chip);
407         if (res != ERROR_OK)
408                 goto error;
409
410         res = target_write_u32(chip->target,
411                                erase_register,
412                                erase_value);
413         if (res != ERROR_OK)
414                 goto set_read_only;
415
416         res = nrf5_wait_for_nvmc(chip);
417         if (res != ERROR_OK)
418                 goto set_read_only;
419
420         return nrf5_nvmc_read_only(chip);
421
422 set_read_only:
423         nrf5_nvmc_read_only(chip);
424 error:
425         LOG_ERROR("Failed to erase reg: 0x%08"PRIx32" val: 0x%08"PRIx32,
426                   erase_register, erase_value);
427         return ERROR_FAIL;
428 }
429
430 static int nrf5_protect_check_clenr0(struct flash_bank *bank)
431 {
432         int res;
433         uint32_t clenr0;
434         struct nrf5_bank *nbank = bank->driver_priv;
435         struct nrf5_info *chip = nbank->chip;
436
437         assert(chip);
438
439         res = target_read_u32(chip->target, NRF51_FICR_CLENR0,
440                               &clenr0);
441         if (res != ERROR_OK) {
442                 LOG_ERROR("Couldn't read code region 0 size[FICR]");
443                 return res;
444         }
445
446         if (clenr0 == 0xFFFFFFFF) {
447                 res = target_read_u32(chip->target, NRF51_UICR_CLENR0,
448                                       &clenr0);
449                 if (res != ERROR_OK) {
450                         LOG_ERROR("Couldn't read code region 0 size[UICR]");
451                         return res;
452                 }
453         }
454
455         for (unsigned int i = 0; i < bank->num_sectors; i++)
456                 bank->sectors[i].is_protected =
457                         clenr0 != 0xFFFFFFFF && bank->sectors[i].offset < clenr0;
458
459         return ERROR_OK;
460 }
461
462 static int nrf5_protect_check_bprot(struct flash_bank *bank)
463 {
464         struct nrf5_bank *nbank = bank->driver_priv;
465         struct nrf5_info *chip = nbank->chip;
466
467         assert(chip);
468
469         static uint32_t nrf5_bprot_offsets[4] = { 0x600, 0x604, 0x610, 0x614 };
470         uint32_t bprot_reg = 0;
471         int res;
472
473         for (unsigned int i = 0; i < bank->num_sectors; i++) {
474                 unsigned int bit = i % 32;
475                 if (bit == 0) {
476                         unsigned int n_reg = i / 32;
477                         if (n_reg >= ARRAY_SIZE(nrf5_bprot_offsets))
478                                 break;
479
480                         res = target_read_u32(chip->target, NRF5_BPROT_BASE + nrf5_bprot_offsets[n_reg], &bprot_reg);
481                         if (res != ERROR_OK)
482                                 return res;
483                 }
484                 bank->sectors[i].is_protected = (bprot_reg & (1 << bit)) ? 1 : 0;
485         }
486         return ERROR_OK;
487 }
488
489 static int nrf5_protect_check(struct flash_bank *bank)
490 {
491         /* UICR cannot be write protected so just return early */
492         if (bank->base == NRF5_UICR_BASE)
493                 return ERROR_OK;
494
495         struct nrf5_bank *nbank = bank->driver_priv;
496         struct nrf5_info *chip = nbank->chip;
497
498         assert(chip);
499
500         if (chip->features & NRF5_FEATURE_BPROT)
501                 return nrf5_protect_check_bprot(bank);
502
503         if (chip->features & NRF5_FEATURE_SERIES_51)
504                 return nrf5_protect_check_clenr0(bank);
505
506         LOG_WARNING("Flash protection of this nRF device is not supported");
507         return ERROR_FLASH_OPER_UNSUPPORTED;
508 }
509
510 static int nrf5_protect_clenr0(struct flash_bank *bank, int set, unsigned int first,
511                 unsigned int last)
512 {
513         int res;
514         uint32_t clenr0, ppfc;
515         struct nrf5_bank *nbank = bank->driver_priv;
516         struct nrf5_info *chip = nbank->chip;
517
518         if (first != 0) {
519                 LOG_ERROR("Code region 0 must start at the beginning of the bank");
520                 return ERROR_FAIL;
521         }
522
523         res = target_read_u32(chip->target, NRF51_FICR_PPFC,
524                               &ppfc);
525         if (res != ERROR_OK) {
526                 LOG_ERROR("Couldn't read PPFC register");
527                 return res;
528         }
529
530         if ((ppfc & 0xFF) == 0x00) {
531                 LOG_ERROR("Code region 0 size was pre-programmed at the factory, can't change flash protection settings");
532                 return ERROR_FAIL;
533         }
534
535         res = target_read_u32(chip->target, NRF51_UICR_CLENR0,
536                               &clenr0);
537         if (res != ERROR_OK) {
538                 LOG_ERROR("Couldn't read code region 0 size from UICR");
539                 return res;
540         }
541
542         if (!set || clenr0 != 0xFFFFFFFF) {
543                 LOG_ERROR("You need to perform chip erase before changing the protection settings");
544                 return ERROR_FAIL;
545         }
546
547         res = nrf5_nvmc_write_enable(chip);
548         if (res != ERROR_OK)
549                 goto error;
550
551         clenr0 = bank->sectors[last].offset + bank->sectors[last].size;
552         res = target_write_u32(chip->target, NRF51_UICR_CLENR0, clenr0);
553
554         int res2 = nrf5_wait_for_nvmc(chip);
555
556         if (res == ERROR_OK)
557                 res = res2;
558
559         if (res == ERROR_OK)
560                 LOG_INFO("A reset or power cycle is required for the new protection settings to take effect.");
561         else
562                 LOG_ERROR("Couldn't write code region 0 size to UICR");
563
564 error:
565         nrf5_nvmc_read_only(chip);
566
567         return res;
568 }
569
570 static int nrf5_protect(struct flash_bank *bank, int set, unsigned int first,
571                 unsigned int last)
572 {
573         int res;
574         struct nrf5_info *chip;
575
576         /* UICR cannot be write protected so just bail out early */
577         if (bank->base == NRF5_UICR_BASE) {
578                 LOG_ERROR("UICR page does not support protection");
579                 return ERROR_FLASH_OPER_UNSUPPORTED;
580         }
581
582         res = nrf5_get_probed_chip_if_halted(bank, &chip);
583         if (res != ERROR_OK)
584                 return res;
585
586         if (chip->features & NRF5_FEATURE_SERIES_51)
587                 return nrf5_protect_clenr0(bank, set, first, last);
588
589         LOG_ERROR("Flash protection setting is not supported on this nRF5 device");
590         return ERROR_FLASH_OPER_UNSUPPORTED;
591 }
592
593 static bool nrf5_info_variant_to_str(uint32_t variant, char *bf)
594 {
595         uint8_t b[4];
596
597         h_u32_to_be(b, variant);
598         if (isalnum(b[0]) && isalnum(b[1]) && isalnum(b[2]) && isalnum(b[3])) {
599                 memcpy(bf, b, 4);
600                 bf[4] = 0;
601                 return true;
602         }
603
604         strcpy(bf, "xxxx");
605         return false;
606 }
607
608 static const char *nrf5_decode_info_package(uint32_t package)
609 {
610         for (size_t i = 0; i < ARRAY_SIZE(nrf5_packages_table); i++) {
611                 if (nrf5_packages_table[i].package == package)
612                         return nrf5_packages_table[i].code;
613         }
614         return "xx";
615 }
616
617 static int get_nrf5_chip_type_str(const struct nrf5_info *chip, char *buf, unsigned int buf_size)
618 {
619         int res;
620         if (chip->spec) {
621                 res = snprintf(buf, buf_size, "nRF%s-%s(build code: %s)",
622                                 chip->spec->part, chip->spec->variant, chip->spec->build_code);
623         } else if (chip->ficr_info_valid) {
624                 char variant[5];
625                 nrf5_info_variant_to_str(chip->ficr_info.variant, variant);
626                 res = snprintf(buf, buf_size, "nRF%" PRIx32 "-%s%.2s(build code: %s)",
627                                 chip->ficr_info.part,
628                                 nrf5_decode_info_package(chip->ficr_info.package),
629                                 variant, &variant[2]);
630         } else {
631                 res = snprintf(buf, buf_size, "nRF51xxx (HWID 0x%04" PRIx16 ")", chip->hwid);
632         }
633
634         /* safety: */
635         if (res <= 0 || (unsigned int)res >= buf_size) {
636                 LOG_ERROR("BUG: buffer problem in %s", __func__);
637                 return ERROR_FAIL;
638         }
639         return ERROR_OK;
640 }
641
642 static int nrf5_info(struct flash_bank *bank, struct command_invocation *cmd)
643 {
644         struct nrf5_bank *nbank = bank->driver_priv;
645         struct nrf5_info *chip = nbank->chip;
646
647         char chip_type_str[256];
648         if (get_nrf5_chip_type_str(chip, chip_type_str, sizeof(chip_type_str)) != ERROR_OK)
649                 return ERROR_FAIL;
650
651         command_print_sameline(cmd, "%s %ukB Flash, %ukB RAM",
652                         chip_type_str, chip->flash_size_kb, chip->ram_size_kb);
653         return ERROR_OK;
654 }
655
656 static int nrf5_read_ficr_info(struct nrf5_info *chip)
657 {
658         int res;
659         struct target *target = chip->target;
660
661         chip->ficr_info_valid = false;
662
663         res = target_read_u32(target, NRF5_FICR_INFO_PART, &chip->ficr_info.part);
664         if (res != ERROR_OK) {
665                 LOG_DEBUG("Couldn't read FICR INFO.PART register");
666                 return res;
667         }
668
669         uint32_t series = chip->ficr_info.part & 0xfffff000;
670         switch (series) {
671         case 0x51000:
672                 chip->features = NRF5_FEATURE_SERIES_51;
673                 break;
674
675         case 0x52000:
676                 chip->features = NRF5_FEATURE_SERIES_52;
677
678                 switch (chip->ficr_info.part) {
679                 case 0x52810:
680                 case 0x52832:
681                         chip->features |= NRF5_FEATURE_BPROT;
682                         break;
683
684                 case 0x52840:
685                         chip->features |= NRF5_FEATURE_ACL_PROT;
686                         break;
687                 }
688                 break;
689
690         default:
691                 LOG_DEBUG("FICR INFO likely not implemented. Invalid PART value 0x%08"
692                                 PRIx32, chip->ficr_info.part);
693                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
694         }
695
696         /* Now we know the device has FICR INFO filled by something relevant:
697          * Although it is not documented, the tested nRF51 rev 3 devices
698          * have FICR INFO.PART, RAM and FLASH of the same format as nRF52.
699          * VARIANT and PACKAGE coding is unknown for a nRF51 device.
700          * nRF52 devices have FICR INFO documented and always filled. */
701
702         res = target_read_u32(target, NRF5_FICR_INFO_VARIANT, &chip->ficr_info.variant);
703         if (res != ERROR_OK)
704                 return res;
705
706         res = target_read_u32(target, NRF5_FICR_INFO_PACKAGE, &chip->ficr_info.package);
707         if (res != ERROR_OK)
708                 return res;
709
710         res = target_read_u32(target, NRF5_FICR_INFO_RAM, &chip->ficr_info.ram);
711         if (res != ERROR_OK)
712                 return res;
713
714         res = target_read_u32(target, NRF5_FICR_INFO_FLASH, &chip->ficr_info.flash);
715         if (res != ERROR_OK)
716                 return res;
717
718         chip->ficr_info_valid = true;
719         return ERROR_OK;
720 }
721
722 static int nrf5_get_ram_size(struct target *target, uint32_t *ram_size)
723 {
724         int res;
725
726         *ram_size = 0;
727
728         uint32_t numramblock;
729         res = target_read_u32(target, NRF51_FICR_NUMRAMBLOCK, &numramblock);
730         if (res != ERROR_OK) {
731                 LOG_DEBUG("Couldn't read FICR NUMRAMBLOCK register");
732                 return res;
733         }
734
735         if (numramblock < 1 || numramblock > 4) {
736                 LOG_DEBUG("FICR NUMRAMBLOCK strange value %" PRIx32, numramblock);
737                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
738         }
739
740         for (unsigned int i = 0; i < numramblock; i++) {
741                 uint32_t sizeramblock;
742                 res = target_read_u32(target, NRF51_FICR_SIZERAMBLOCK0 + sizeof(uint32_t)*i, &sizeramblock);
743                 if (res != ERROR_OK) {
744                         LOG_DEBUG("Couldn't read FICR NUMRAMBLOCK register");
745                         return res;
746                 }
747                 if (sizeramblock < 1024 || sizeramblock > 65536)
748                         LOG_DEBUG("FICR SIZERAMBLOCK strange value %" PRIx32, sizeramblock);
749                 else
750                         *ram_size += sizeramblock;
751         }
752         return res;
753 }
754
755 static int nrf5_probe(struct flash_bank *bank)
756 {
757         int res;
758         struct nrf5_bank *nbank = bank->driver_priv;
759         struct nrf5_info *chip = nbank->chip;
760         struct target *target = chip->target;
761
762         uint32_t configid;
763         res = target_read_u32(target, NRF5_FICR_CONFIGID, &configid);
764         if (res != ERROR_OK) {
765                 LOG_ERROR("Couldn't read CONFIGID register");
766                 return res;
767         }
768
769         /* HWID is stored in the lower two bytes of the CONFIGID register */
770         chip->hwid = configid & 0xFFFF;
771
772         /* guess a nRF51 series if the device has no FICR INFO and we don't know HWID */
773         chip->features = NRF5_FEATURE_SERIES_51;
774
775         /* Don't bail out on error for the case that some old engineering
776          * sample has FICR INFO registers unreadable. We can proceed anyway. */
777         (void)nrf5_read_ficr_info(chip);
778
779         chip->spec = NULL;
780         for (size_t i = 0; i < ARRAY_SIZE(nrf5_known_devices_table); i++) {
781                 if (chip->hwid == nrf5_known_devices_table[i].hwid) {
782                         chip->spec = &nrf5_known_devices_table[i];
783                         chip->features = chip->spec->features;
784                         break;
785                 }
786         }
787
788         if (chip->spec && chip->ficr_info_valid) {
789                 /* check if HWID table gives the same part as FICR INFO */
790                 if (chip->ficr_info.part != strtoul(chip->spec->part, NULL, 16))
791                         LOG_WARNING("HWID 0x%04" PRIx32 " mismatch: FICR INFO.PART %"
792                                                 PRIx32, chip->hwid, chip->ficr_info.part);
793         }
794
795         if (chip->ficr_info_valid) {
796                 chip->ram_size_kb = chip->ficr_info.ram;
797         } else {
798                 uint32_t ram_size;
799                 nrf5_get_ram_size(target, &ram_size);
800                 chip->ram_size_kb = ram_size / 1024;
801         }
802
803         /* The value stored in NRF5_FICR_CODEPAGESIZE is the number of bytes in one page of FLASH. */
804         uint32_t flash_page_size;
805         res = target_read_u32(chip->target, NRF5_FICR_CODEPAGESIZE,
806                                 &flash_page_size);
807         if (res != ERROR_OK) {
808                 LOG_ERROR("Couldn't read code page size");
809                 return res;
810         }
811
812         /* Note the register name is misleading,
813          * NRF5_FICR_CODESIZE is the number of pages in flash memory, not the number of bytes! */
814         uint32_t num_sectors;
815         res = target_read_u32(chip->target, NRF5_FICR_CODESIZE, &num_sectors);
816         if (res != ERROR_OK) {
817                 LOG_ERROR("Couldn't read code memory size");
818                 return res;
819         }
820
821         chip->flash_size_kb = num_sectors * flash_page_size / 1024;
822
823         if (!chip->bank[0].probed && !chip->bank[1].probed) {
824                 char chip_type_str[256];
825                 if (get_nrf5_chip_type_str(chip, chip_type_str, sizeof(chip_type_str)) != ERROR_OK)
826                         return ERROR_FAIL;
827                 const bool device_is_unknown = (!chip->spec && !chip->ficr_info_valid);
828                 LOG_INFO("%s%s %ukB Flash, %ukB RAM",
829                                 device_is_unknown ? "Unknown device: " : "",
830                                 chip_type_str,
831                                 chip->flash_size_kb,
832                                 chip->ram_size_kb);
833         }
834
835         free(bank->sectors);
836
837         if (bank->base == NRF5_FLASH_BASE) {
838                 /* Sanity check */
839                 if (chip->spec && chip->flash_size_kb != chip->spec->flash_size_kb)
840                         LOG_WARNING("Chip's reported Flash capacity does not match expected one");
841                 if (chip->ficr_info_valid && chip->flash_size_kb != chip->ficr_info.flash)
842                         LOG_WARNING("Chip's reported Flash capacity does not match FICR INFO.FLASH");
843
844                 bank->num_sectors = num_sectors;
845                 bank->size = num_sectors * flash_page_size;
846
847                 bank->sectors = alloc_block_array(0, flash_page_size, num_sectors);
848                 if (!bank->sectors)
849                         return ERROR_FAIL;
850
851                 chip->bank[0].probed = true;
852
853         } else {
854                 bank->num_sectors = 1;
855                 bank->size = flash_page_size;
856
857                 bank->sectors = alloc_block_array(0, flash_page_size, num_sectors);
858                 if (!bank->sectors)
859                         return ERROR_FAIL;
860
861                 bank->sectors[0].is_protected = 0;
862
863                 chip->bank[1].probed = true;
864         }
865
866         return ERROR_OK;
867 }
868
869 static int nrf5_auto_probe(struct flash_bank *bank)
870 {
871         if (nrf5_bank_is_probed(bank))
872                 return ERROR_OK;
873
874         return nrf5_probe(bank);
875 }
876
877 static int nrf5_erase_all(struct nrf5_info *chip)
878 {
879         LOG_DEBUG("Erasing all non-volatile memory");
880         return nrf5_nvmc_generic_erase(chip,
881                                         NRF5_NVMC_ERASEALL,
882                                         0x00000001);
883 }
884
885 static int nrf5_erase_page(struct flash_bank *bank,
886                                                         struct nrf5_info *chip,
887                                                         struct flash_sector *sector)
888 {
889         int res;
890
891         LOG_DEBUG("Erasing page at 0x%"PRIx32, sector->offset);
892
893         if (bank->base == NRF5_UICR_BASE) {
894                 if (chip->features & NRF5_FEATURE_SERIES_51) {
895                         uint32_t ppfc;
896                         res = target_read_u32(chip->target, NRF51_FICR_PPFC,
897                                       &ppfc);
898                         if (res != ERROR_OK) {
899                                 LOG_ERROR("Couldn't read PPFC register");
900                                 return res;
901                         }
902
903                         if ((ppfc & 0xFF) == 0xFF) {
904                                 /* We can't erase the UICR.  Double-check to
905                                    see if it's already erased before complaining. */
906                                 default_flash_blank_check(bank);
907                                 if (sector->is_erased == 1)
908                                         return ERROR_OK;
909
910                                 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");
911                                 return ERROR_FAIL;
912                         }
913                 }
914
915                 res = nrf5_nvmc_generic_erase(chip,
916                                                NRF5_NVMC_ERASEUICR,
917                                                0x00000001);
918
919
920         } else {
921                 res = nrf5_nvmc_generic_erase(chip,
922                                                NRF5_NVMC_ERASEPAGE,
923                                                sector->offset);
924         }
925
926         return res;
927 }
928
929 /* Start a low level flash write for the specified region */
930 static int nrf5_ll_flash_write(struct nrf5_info *chip, uint32_t address, const uint8_t *buffer, uint32_t bytes)
931 {
932         struct target *target = chip->target;
933         uint32_t buffer_size = 8192;
934         struct working_area *write_algorithm;
935         struct working_area *source;
936         struct reg_param reg_params[6];
937         struct armv7m_algorithm armv7m_info;
938         int retval = ERROR_OK;
939
940         static const uint8_t nrf5_flash_write_code[] = {
941 #include "../../../contrib/loaders/flash/nrf5/nrf5.inc"
942         };
943
944         LOG_DEBUG("Writing buffer to flash address=0x%"PRIx32" bytes=0x%"PRIx32, address, bytes);
945         assert(bytes % 4 == 0);
946
947         /* allocate working area with flash programming code */
948         if (target_alloc_working_area(target, sizeof(nrf5_flash_write_code),
949                         &write_algorithm) != ERROR_OK) {
950                 LOG_WARNING("no working area available, falling back to slow memory writes");
951
952                 for (; bytes > 0; bytes -= 4) {
953                         retval = target_write_memory(target, address, 4, 1, buffer);
954                         if (retval != ERROR_OK)
955                                 return retval;
956
957                         retval = nrf5_wait_for_nvmc(chip);
958                         if (retval != ERROR_OK)
959                                 return retval;
960
961                         address += 4;
962                         buffer += 4;
963                 }
964
965                 return ERROR_OK;
966         }
967
968         retval = target_write_buffer(target, write_algorithm->address,
969                                 sizeof(nrf5_flash_write_code),
970                                 nrf5_flash_write_code);
971         if (retval != ERROR_OK)
972                 return retval;
973
974         /* memory buffer */
975         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
976                 buffer_size /= 2;
977                 buffer_size &= ~3UL; /* Make sure it's 4 byte aligned */
978                 if (buffer_size <= 256) {
979                         /* free working area, write algorithm already allocated */
980                         target_free_working_area(target, write_algorithm);
981
982                         LOG_WARNING("No large enough working area available, can't do block memory writes");
983                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
984                 }
985         }
986
987         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
988         armv7m_info.core_mode = ARM_MODE_THREAD;
989
990         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* byte count */
991         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);    /* buffer start */
992         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);    /* buffer end */
993         init_reg_param(&reg_params[3], "r3", 32, PARAM_IN_OUT); /* target address */
994         init_reg_param(&reg_params[4], "r6", 32, PARAM_OUT);    /* watchdog refresh value */
995         init_reg_param(&reg_params[5], "r7", 32, PARAM_OUT);    /* watchdog refresh register address */
996
997         buf_set_u32(reg_params[0].value, 0, 32, bytes);
998         buf_set_u32(reg_params[1].value, 0, 32, source->address);
999         buf_set_u32(reg_params[2].value, 0, 32, source->address + source->size);
1000         buf_set_u32(reg_params[3].value, 0, 32, address);
1001         buf_set_u32(reg_params[4].value, 0, 32, WATCHDOG_REFRESH_VALUE);
1002         buf_set_u32(reg_params[5].value, 0, 32, WATCHDOG_REFRESH_REGISTER);
1003
1004         retval = target_run_flash_async_algorithm(target, buffer, bytes/4, 4,
1005                         0, NULL,
1006                         ARRAY_SIZE(reg_params), reg_params,
1007                         source->address, source->size,
1008                         write_algorithm->address, write_algorithm->address + sizeof(nrf5_flash_write_code) - 2,
1009                         &armv7m_info);
1010
1011         target_free_working_area(target, source);
1012         target_free_working_area(target, write_algorithm);
1013
1014         destroy_reg_param(&reg_params[0]);
1015         destroy_reg_param(&reg_params[1]);
1016         destroy_reg_param(&reg_params[2]);
1017         destroy_reg_param(&reg_params[3]);
1018         destroy_reg_param(&reg_params[4]);
1019         destroy_reg_param(&reg_params[5]);
1020
1021         return retval;
1022 }
1023
1024 static int nrf5_write(struct flash_bank *bank, const uint8_t *buffer,
1025                                         uint32_t offset, uint32_t count)
1026 {
1027         struct nrf5_info *chip;
1028
1029         int res = nrf5_get_probed_chip_if_halted(bank, &chip);
1030         if (res != ERROR_OK)
1031                 return res;
1032
1033         assert(offset % 4 == 0);
1034         assert(count % 4 == 0);
1035
1036         /* UICR CLENR0 based protection used on nRF51 is somewhat clumsy:
1037          * RM reads: Code running from code region 1 will not be able to write
1038          * to code region 0.
1039          * Unfortunately the flash loader running from RAM can write to both
1040          * code regions without any hint the protection is violated.
1041          *
1042          * Update protection state and check if any flash sector to be written
1043          * is protected. */
1044         if (chip->features & NRF5_FEATURE_SERIES_51) {
1045
1046                 res = nrf5_protect_check_clenr0(bank);
1047                 if (res != ERROR_OK)
1048                         return res;
1049
1050                 for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
1051                         struct flash_sector *bs = &bank->sectors[sector];
1052
1053                         /* Start offset in or before this sector? */
1054                         /* End offset in or behind this sector? */
1055                         if ((offset < (bs->offset + bs->size))
1056                                         && ((offset + count - 1) >= bs->offset)
1057                                         && bs->is_protected == 1) {
1058                                 LOG_ERROR("Write refused, sector %d is protected", sector);
1059                                 return ERROR_FLASH_PROTECTED;
1060                         }
1061                 }
1062         }
1063
1064         res = nrf5_nvmc_write_enable(chip);
1065         if (res != ERROR_OK)
1066                 goto error;
1067
1068         res = nrf5_ll_flash_write(chip, bank->base + offset, buffer, count);
1069         if (res != ERROR_OK)
1070                 goto error;
1071
1072         return nrf5_nvmc_read_only(chip);
1073
1074 error:
1075         nrf5_nvmc_read_only(chip);
1076         LOG_ERROR("Failed to write to nrf5 flash");
1077         return res;
1078 }
1079
1080 static int nrf5_erase(struct flash_bank *bank, unsigned int first,
1081                 unsigned int last)
1082 {
1083         int res;
1084         struct nrf5_info *chip;
1085
1086         res = nrf5_get_probed_chip_if_halted(bank, &chip);
1087         if (res != ERROR_OK)
1088                 return res;
1089
1090         /* UICR CLENR0 based protection used on nRF51 prevents erase
1091          * absolutely silently. NVMC has no flag to indicate the protection
1092          * was violated.
1093          *
1094          * Update protection state and check if any flash sector to be erased
1095          * is protected. */
1096         if (chip->features & NRF5_FEATURE_SERIES_51) {
1097
1098                 res = nrf5_protect_check_clenr0(bank);
1099                 if (res != ERROR_OK)
1100                         return res;
1101         }
1102
1103         /* For each sector to be erased */
1104         for (unsigned int s = first; s <= last && res == ERROR_OK; s++) {
1105
1106                 if (chip->features & NRF5_FEATURE_SERIES_51
1107                                 && bank->sectors[s].is_protected == 1) {
1108                         LOG_ERROR("Flash sector %d is protected", s);
1109                         return ERROR_FLASH_PROTECTED;
1110                 }
1111
1112                 res = nrf5_erase_page(bank, chip, &bank->sectors[s]);
1113                 if (res != ERROR_OK) {
1114                         LOG_ERROR("Error erasing sector %d", s);
1115                         return res;
1116                 }
1117         }
1118
1119         return ERROR_OK;
1120 }
1121
1122 static void nrf5_free_driver_priv(struct flash_bank *bank)
1123 {
1124         struct nrf5_bank *nbank = bank->driver_priv;
1125         struct nrf5_info *chip = nbank->chip;
1126         if (!chip)
1127                 return;
1128
1129         chip->refcount--;
1130         if (chip->refcount == 0) {
1131                 free(chip);
1132                 bank->driver_priv = NULL;
1133         }
1134 }
1135
1136 static struct nrf5_info *nrf5_get_chip(struct target *target)
1137 {
1138         struct flash_bank *bank_iter;
1139
1140         /* iterate over nrf5 banks of same target */
1141         for (bank_iter = flash_bank_list(); bank_iter; bank_iter = bank_iter->next) {
1142                 if (bank_iter->driver != &nrf5_flash && bank_iter->driver != &nrf51_flash)
1143                         continue;
1144
1145                 if (bank_iter->target != target)
1146                         continue;
1147
1148                 struct nrf5_bank *nbank = bank_iter->driver_priv;
1149                 if (!nbank)
1150                         continue;
1151
1152                 if (nbank->chip)
1153                         return nbank->chip;
1154         }
1155         return NULL;
1156 }
1157
1158 FLASH_BANK_COMMAND_HANDLER(nrf5_flash_bank_command)
1159 {
1160         struct nrf5_info *chip;
1161         struct nrf5_bank *nbank = NULL;
1162
1163         switch (bank->base) {
1164         case NRF5_FLASH_BASE:
1165         case NRF5_UICR_BASE:
1166                 break;
1167         default:
1168                 LOG_ERROR("Invalid bank address " TARGET_ADDR_FMT, bank->base);
1169                 return ERROR_FAIL;
1170         }
1171
1172         chip = nrf5_get_chip(bank->target);
1173         if (!chip) {
1174                 /* Create a new chip */
1175                 chip = calloc(1, sizeof(*chip));
1176                 if (!chip)
1177                         return ERROR_FAIL;
1178
1179                 chip->target = bank->target;
1180         }
1181
1182         switch (bank->base) {
1183         case NRF5_FLASH_BASE:
1184                 nbank = &chip->bank[0];
1185                 break;
1186         case NRF5_UICR_BASE:
1187                 nbank = &chip->bank[1];
1188                 break;
1189         }
1190         assert(nbank);
1191
1192         chip->refcount++;
1193         nbank->chip = chip;
1194         nbank->probed = false;
1195         bank->driver_priv = nbank;
1196         bank->write_start_alignment = bank->write_end_alignment = 4;
1197
1198         return ERROR_OK;
1199 }
1200
1201 COMMAND_HANDLER(nrf5_handle_mass_erase_command)
1202 {
1203         int res;
1204         struct flash_bank *bank = NULL;
1205         struct target *target = get_current_target(CMD_CTX);
1206
1207         res = get_flash_bank_by_addr(target, NRF5_FLASH_BASE, true, &bank);
1208         if (res != ERROR_OK)
1209                 return res;
1210
1211         assert(bank);
1212
1213         struct nrf5_info *chip;
1214
1215         res = nrf5_get_probed_chip_if_halted(bank, &chip);
1216         if (res != ERROR_OK)
1217                 return res;
1218
1219         if (chip->features & NRF5_FEATURE_SERIES_51) {
1220                 uint32_t ppfc;
1221                 res = target_read_u32(target, NRF51_FICR_PPFC,
1222                               &ppfc);
1223                 if (res != ERROR_OK) {
1224                         LOG_ERROR("Couldn't read PPFC register");
1225                         return res;
1226                 }
1227
1228                 if ((ppfc & 0xFF) == 0x00) {
1229                         LOG_ERROR("Code region 0 size was pre-programmed at the factory, "
1230                                   "mass erase command won't work.");
1231                         return ERROR_FAIL;
1232                 }
1233         }
1234
1235         res = nrf5_erase_all(chip);
1236         if (res == ERROR_OK) {
1237                 LOG_INFO("Mass erase completed.");
1238                 if (chip->features & NRF5_FEATURE_SERIES_51)
1239                         LOG_INFO("A reset or power cycle is required if the flash was protected before.");
1240
1241         } else {
1242                 LOG_ERROR("Failed to erase the chip");
1243         }
1244
1245         return res;
1246 }
1247
1248 COMMAND_HANDLER(nrf5_handle_info_command)
1249 {
1250         int res;
1251         struct flash_bank *bank = NULL;
1252         struct target *target = get_current_target(CMD_CTX);
1253
1254         res = get_flash_bank_by_addr(target, NRF5_FLASH_BASE, true, &bank);
1255         if (res != ERROR_OK)
1256                 return res;
1257
1258         assert(bank);
1259
1260         struct nrf5_info *chip;
1261
1262         res = nrf5_get_probed_chip_if_halted(bank, &chip);
1263         if (res != ERROR_OK)
1264                 return res;
1265
1266         static struct {
1267                 const uint32_t address;
1268                 uint32_t value;
1269         } ficr[] = {
1270                 { .address = NRF5_FICR_CODEPAGESIZE     },
1271                 { .address = NRF5_FICR_CODESIZE },
1272                 { .address = NRF51_FICR_CLENR0          },
1273                 { .address = NRF51_FICR_PPFC            },
1274                 { .address = NRF51_FICR_NUMRAMBLOCK     },
1275                 { .address = NRF51_FICR_SIZERAMBLOCK0   },
1276                 { .address = NRF51_FICR_SIZERAMBLOCK1   },
1277                 { .address = NRF51_FICR_SIZERAMBLOCK2   },
1278                 { .address = NRF51_FICR_SIZERAMBLOCK3   },
1279                 { .address = NRF5_FICR_CONFIGID },
1280                 { .address = NRF5_FICR_DEVICEID0        },
1281                 { .address = NRF5_FICR_DEVICEID1        },
1282                 { .address = NRF5_FICR_ER0              },
1283                 { .address = NRF5_FICR_ER1              },
1284                 { .address = NRF5_FICR_ER2              },
1285                 { .address = NRF5_FICR_ER3              },
1286                 { .address = NRF5_FICR_IR0              },
1287                 { .address = NRF5_FICR_IR1              },
1288                 { .address = NRF5_FICR_IR2              },
1289                 { .address = NRF5_FICR_IR3              },
1290                 { .address = NRF5_FICR_DEVICEADDRTYPE   },
1291                 { .address = NRF5_FICR_DEVICEADDR0      },
1292                 { .address = NRF5_FICR_DEVICEADDR1      },
1293                 { .address = NRF51_FICR_OVERRIDEN       },
1294                 { .address = NRF51_FICR_NRF_1MBIT0      },
1295                 { .address = NRF51_FICR_NRF_1MBIT1      },
1296                 { .address = NRF51_FICR_NRF_1MBIT2      },
1297                 { .address = NRF51_FICR_NRF_1MBIT3      },
1298                 { .address = NRF51_FICR_NRF_1MBIT4      },
1299                 { .address = NRF51_FICR_BLE_1MBIT0      },
1300                 { .address = NRF51_FICR_BLE_1MBIT1      },
1301                 { .address = NRF51_FICR_BLE_1MBIT2      },
1302                 { .address = NRF51_FICR_BLE_1MBIT3      },
1303                 { .address = NRF51_FICR_BLE_1MBIT4      },
1304         }, uicr[] = {
1305                 { .address = NRF51_UICR_CLENR0,         },
1306                 { .address = NRF51_UICR_RBPCONF         },
1307                 { .address = NRF51_UICR_XTALFREQ        },
1308                 { .address = NRF51_UICR_FWID            },
1309         };
1310
1311         for (size_t i = 0; i < ARRAY_SIZE(ficr); i++) {
1312                 res = target_read_u32(chip->target, ficr[i].address,
1313                                       &ficr[i].value);
1314                 if (res != ERROR_OK) {
1315                         LOG_ERROR("Couldn't read %" PRIx32, ficr[i].address);
1316                         return res;
1317                 }
1318         }
1319
1320         for (size_t i = 0; i < ARRAY_SIZE(uicr); i++) {
1321                 res = target_read_u32(chip->target, uicr[i].address,
1322                                       &uicr[i].value);
1323                 if (res != ERROR_OK) {
1324                         LOG_ERROR("Couldn't read %" PRIx32, uicr[i].address);
1325                         return res;
1326                 }
1327         }
1328
1329         command_print(CMD,
1330                  "\n[factory information control block]\n\n"
1331                  "code page size: %"PRIu32"B\n"
1332                  "code memory size: %"PRIu32"kB\n"
1333                  "code region 0 size: %"PRIu32"kB\n"
1334                  "pre-programmed code: %s\n"
1335                  "number of ram blocks: %"PRIu32"\n"
1336                  "ram block 0 size: %"PRIu32"B\n"
1337                  "ram block 1 size: %"PRIu32"B\n"
1338                  "ram block 2 size: %"PRIu32"B\n"
1339                  "ram block 3 size: %"PRIu32 "B\n"
1340                  "config id: %" PRIx32 "\n"
1341                  "device id: 0x%"PRIx32"%08"PRIx32"\n"
1342                  "encryption root: 0x%08"PRIx32"%08"PRIx32"%08"PRIx32"%08"PRIx32"\n"
1343                  "identity root: 0x%08"PRIx32"%08"PRIx32"%08"PRIx32"%08"PRIx32"\n"
1344                  "device address type: 0x%"PRIx32"\n"
1345                  "device address: 0x%"PRIx32"%08"PRIx32"\n"
1346                  "override enable: %"PRIx32"\n"
1347                  "NRF_1MBIT values: %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32"\n"
1348                  "BLE_1MBIT values: %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32" %"PRIx32"\n"
1349                  "\n[user information control block]\n\n"
1350                  "code region 0 size: %"PRIu32"kB\n"
1351                  "read back protection configuration: %"PRIx32"\n"
1352                  "reset value for XTALFREQ: %"PRIx32"\n"
1353                  "firmware id: 0x%04"PRIx32,
1354                  ficr[0].value,
1355                  (ficr[1].value * ficr[0].value) / 1024,
1356                  (ficr[2].value == 0xFFFFFFFF) ? 0 : ficr[2].value / 1024,
1357                  ((ficr[3].value & 0xFF) == 0x00) ? "present" : "not present",
1358                  ficr[4].value,
1359                  ficr[5].value,
1360                  (ficr[6].value == 0xFFFFFFFF) ? 0 : ficr[6].value,
1361                  (ficr[7].value == 0xFFFFFFFF) ? 0 : ficr[7].value,
1362                  (ficr[8].value == 0xFFFFFFFF) ? 0 : ficr[8].value,
1363                  ficr[9].value,
1364                  ficr[10].value, ficr[11].value,
1365                  ficr[12].value, ficr[13].value, ficr[14].value, ficr[15].value,
1366                  ficr[16].value, ficr[17].value, ficr[18].value, ficr[19].value,
1367                  ficr[20].value,
1368                  ficr[21].value, ficr[22].value,
1369                  ficr[23].value,
1370                  ficr[24].value, ficr[25].value, ficr[26].value, ficr[27].value, ficr[28].value,
1371                  ficr[29].value, ficr[30].value, ficr[31].value, ficr[32].value, ficr[33].value,
1372                  (uicr[0].value == 0xFFFFFFFF) ? 0 : uicr[0].value / 1024,
1373                  uicr[1].value & 0xFFFF,
1374                  uicr[2].value & 0xFF,
1375                  uicr[3].value & 0xFFFF);
1376
1377         return ERROR_OK;
1378 }
1379
1380 static const struct command_registration nrf5_exec_command_handlers[] = {
1381         {
1382                 .name           = "mass_erase",
1383                 .handler        = nrf5_handle_mass_erase_command,
1384                 .mode           = COMMAND_EXEC,
1385                 .help           = "Erase all flash contents of the chip.",
1386                 .usage          = "",
1387         },
1388         {
1389                 .name           = "info",
1390                 .handler        = nrf5_handle_info_command,
1391                 .mode           = COMMAND_EXEC,
1392                 .help           = "Show FICR and UICR info.",
1393                 .usage          = "",
1394         },
1395         COMMAND_REGISTRATION_DONE
1396 };
1397
1398 static const struct command_registration nrf5_command_handlers[] = {
1399         {
1400                 .name   = "nrf5",
1401                 .mode   = COMMAND_ANY,
1402                 .help   = "nrf5 flash command group",
1403                 .usage  = "",
1404                 .chain  = nrf5_exec_command_handlers,
1405         },
1406         {
1407                 .name   = "nrf51",
1408                 .mode   = COMMAND_ANY,
1409                 .help   = "nrf51 flash command group",
1410                 .usage  = "",
1411                 .chain  = nrf5_exec_command_handlers,
1412         },
1413         COMMAND_REGISTRATION_DONE
1414 };
1415
1416 const struct flash_driver nrf5_flash = {
1417         .name                   = "nrf5",
1418         .commands               = nrf5_command_handlers,
1419         .flash_bank_command     = nrf5_flash_bank_command,
1420         .info                   = nrf5_info,
1421         .erase                  = nrf5_erase,
1422         .protect                = nrf5_protect,
1423         .write                  = nrf5_write,
1424         .read                   = default_flash_read,
1425         .probe                  = nrf5_probe,
1426         .auto_probe             = nrf5_auto_probe,
1427         .erase_check            = default_flash_blank_check,
1428         .protect_check          = nrf5_protect_check,
1429         .free_driver_priv       = nrf5_free_driver_priv,
1430 };
1431
1432 /* We need to retain the flash-driver name as well as the commands
1433  * for backwards compatibility */
1434 const struct flash_driver nrf51_flash = {
1435         .name                   = "nrf51",
1436         .commands               = nrf5_command_handlers,
1437         .flash_bank_command     = nrf5_flash_bank_command,
1438         .info                   = nrf5_info,
1439         .erase                  = nrf5_erase,
1440         .protect                = nrf5_protect,
1441         .write                  = nrf5_write,
1442         .read                   = default_flash_read,
1443         .probe                  = nrf5_probe,
1444         .auto_probe             = nrf5_auto_probe,
1445         .erase_check            = default_flash_blank_check,
1446         .protect_check          = nrf5_protect_check,
1447         .free_driver_priv       = nrf5_free_driver_priv,
1448 };