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