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