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