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