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