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