at91samd: handle reset run/halt in DSU
[fw/openocd] / src / flash / nor / at91samd.c
1 /***************************************************************************
2  *   Copyright (C) 2013 by Andrey Yurovsky                                 *
3  *   Andrey Yurovsky <yurovsky@gmail.com>                                  *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
19  ***************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include "imp.h"
26 #include "helper/binarybuffer.h"
27
28 #include <target/cortex_m.h>
29
30 #define SAMD_NUM_SECTORS        16
31 #define SAMD_PAGE_SIZE_MAX      1024
32
33 #define SAMD_FLASH                      ((uint32_t)0x00000000)  /* physical Flash memory */
34 #define SAMD_USER_ROW           ((uint32_t)0x00804000)  /* User Row of Flash */
35 #define SAMD_PAC1                       0x41000000      /* Peripheral Access Control 1 */
36 #define SAMD_DSU                        0x41002000      /* Device Service Unit */
37 #define SAMD_NVMCTRL            0x41004000      /* Non-volatile memory controller */
38
39 #define SAMD_DSU_STATUSA        1               /* DSU status register */
40 #define SAMD_DSU_DID            0x18            /* Device ID register */
41
42 #define SAMD_NVMCTRL_CTRLA              0x00    /* NVM control A register */
43 #define SAMD_NVMCTRL_CTRLB              0x04    /* NVM control B register */
44 #define SAMD_NVMCTRL_PARAM              0x08    /* NVM parameters register */
45 #define SAMD_NVMCTRL_INTFLAG    0x18    /* NVM Interupt Flag Status & Clear */
46 #define SAMD_NVMCTRL_STATUS             0x18    /* NVM status register */
47 #define SAMD_NVMCTRL_ADDR               0x1C    /* NVM address register */
48 #define SAMD_NVMCTRL_LOCK               0x20    /* NVM Lock section register */
49
50 #define SAMD_CMDEX_KEY          0xA5UL
51 #define SAMD_NVM_CMD(n)         ((SAMD_CMDEX_KEY << 8) | (n & 0x7F))
52
53 /* NVMCTRL commands.  See Table 20-4 in 42129F–SAM–10/2013 */
54 #define SAMD_NVM_CMD_ER         0x02            /* Erase Row */
55 #define SAMD_NVM_CMD_WP         0x04            /* Write Page */
56 #define SAMD_NVM_CMD_EAR        0x05            /* Erase Auxilary Row */
57 #define SAMD_NVM_CMD_WAP        0x06            /* Write Auxilary Page */
58 #define SAMD_NVM_CMD_LR         0x40            /* Lock Region */
59 #define SAMD_NVM_CMD_UR         0x41            /* Unlock Region */
60 #define SAMD_NVM_CMD_SPRM       0x42            /* Set Power Reduction Mode */
61 #define SAMD_NVM_CMD_CPRM       0x43            /* Clear Power Reduction Mode */
62 #define SAMD_NVM_CMD_PBC        0x44            /* Page Buffer Clear */
63 #define SAMD_NVM_CMD_SSB        0x45            /* Set Security Bit */
64 #define SAMD_NVM_CMD_INVALL     0x46            /* Invalidate all caches */
65
66 /* Known identifiers */
67 #define SAMD_PROCESSOR_M0       0x01
68 #define SAMD_FAMILY_D           0x00
69 #define SAMD_FAMILY_L           0x01
70 #define SAMD_FAMILY_C           0x02
71 #define SAMD_SERIES_20          0x00
72 #define SAMD_SERIES_21          0x01
73 #define SAMD_SERIES_10          0x02
74 #define SAMD_SERIES_11          0x03
75
76 struct samd_part {
77         uint8_t id;
78         const char *name;
79         uint32_t flash_kb;
80         uint32_t ram_kb;
81 };
82
83 /* Known SAMD10 parts */
84 static const struct samd_part samd10_parts[] = {
85         { 0x0, "SAMD10D14AMU", 16, 4 },
86         { 0x1, "SAMD10D13AMU", 8, 4 },
87         { 0x2, "SAMD10D12AMU", 4, 4 },
88         { 0x3, "SAMD10D14ASU", 16, 4 },
89         { 0x4, "SAMD10D13ASU", 8, 4 },
90         { 0x5, "SAMD10D12ASU", 4, 4 },
91         { 0x6, "SAMD10C14A", 16, 4 },
92         { 0x7, "SAMD10C13A", 8, 4 },
93         { 0x8, "SAMD10C12A", 4, 4 },
94 };
95
96 /* Known SAMD11 parts */
97 static const struct samd_part samd11_parts[] = {
98         { 0x0, "SAMD11D14AMU", 16, 4 },
99         { 0x1, "SAMD11D13AMU", 8, 4 },
100         { 0x2, "SAMD11D12AMU", 4, 4 },
101         { 0x3, "SAMD11D14ASU", 16, 4 },
102         { 0x4, "SAMD11D13ASU", 8, 4 },
103         { 0x5, "SAMD11D12ASU", 4, 4 },
104         { 0x6, "SAMD11C14A", 16, 4 },
105         { 0x7, "SAMD11C13A", 8, 4 },
106         { 0x8, "SAMD11C12A", 4, 4 },
107 };
108
109 /* Known SAMD20 parts. See Table 12-8 in 42129F–SAM–10/2013 */
110 static const struct samd_part samd20_parts[] = {
111         { 0x0, "SAMD20J18A", 256, 32 },
112         { 0x1, "SAMD20J17A", 128, 16 },
113         { 0x2, "SAMD20J16A", 64, 8 },
114         { 0x3, "SAMD20J15A", 32, 4 },
115         { 0x4, "SAMD20J14A", 16, 2 },
116         { 0x5, "SAMD20G18A", 256, 32 },
117         { 0x6, "SAMD20G17A", 128, 16 },
118         { 0x7, "SAMD20G16A", 64, 8 },
119         { 0x8, "SAMD20G15A", 32, 4 },
120         { 0x9, "SAMD20G14A", 16, 2 },
121         { 0xA, "SAMD20E18A", 256, 32 },
122         { 0xB, "SAMD20E17A", 128, 16 },
123         { 0xC, "SAMD20E16A", 64, 8 },
124         { 0xD, "SAMD20E15A", 32, 4 },
125         { 0xE, "SAMD20E14A", 16, 2 },
126 };
127
128 /* Known SAMD21 parts. */
129 static const struct samd_part samd21_parts[] = {
130         { 0x0, "SAMD21J18A", 256, 32 },
131         { 0x1, "SAMD21J17A", 128, 16 },
132         { 0x2, "SAMD21J16A", 64, 8 },
133         { 0x3, "SAMD21J15A", 32, 4 },
134         { 0x4, "SAMD21J14A", 16, 2 },
135         { 0x5, "SAMD21G18A", 256, 32 },
136         { 0x6, "SAMD21G17A", 128, 16 },
137         { 0x7, "SAMD21G16A", 64, 8 },
138         { 0x8, "SAMD21G15A", 32, 4 },
139         { 0x9, "SAMD21G14A", 16, 2 },
140         { 0xA, "SAMD21E18A", 256, 32 },
141         { 0xB, "SAMD21E17A", 128, 16 },
142         { 0xC, "SAMD21E16A", 64, 8 },
143         { 0xD, "SAMD21E15A", 32, 4 },
144         { 0xE, "SAMD21E14A", 16, 2 },
145 };
146
147 /* Known SAMR21 parts. */
148 static const struct samd_part samr21_parts[] = {
149         { 0x19, "SAMR21G18A", 256, 32 },
150         { 0x1A, "SAMR21G17A", 128, 32 },
151         { 0x1B, "SAMR21G16A",  64, 32 },
152         { 0x1C, "SAMR21E18A", 256, 32 },
153         { 0x1D, "SAMR21E17A", 128, 32 },
154         { 0x1E, "SAMR21E16A",  64, 32 },
155 };
156
157 /* Known SAML21 parts. */
158 static const struct samd_part saml21_parts[] = {
159         { 0x00, "SAML21J18A", 256, 32 },
160         { 0x01, "SAML21J17A", 128, 16 },
161         { 0x02, "SAML21J16A", 64, 8 },
162         { 0x05, "SAML21G18A", 256, 32 },
163         { 0x06, "SAML21G17A", 128, 16 },
164         { 0x07, "SAML21G16A", 64, 8 },
165         { 0x0A, "SAML21E18A", 256, 32 },
166         { 0x0B, "SAML21E17A", 128, 16 },
167         { 0x0C, "SAML21E16A", 64, 8 },
168         { 0x0D, "SAML21E15A", 32, 4 },
169 };
170
171 /* Known SAMC20 parts. */
172 static const struct samd_part samc20_parts[] = {
173         { 0x00, "SAMC20J18A", 256, 32 },
174         { 0x01, "SAMC20J17A", 128, 16 },
175         { 0x02, "SAMC20J16A", 64, 8 },
176         { 0x03, "SAMC20J15A", 32, 4 },
177         { 0x05, "SAMC20G18A", 256, 32 },
178         { 0x06, "SAMC20G17A", 128, 16 },
179         { 0x07, "SAMC20G16A", 64, 8 },
180         { 0x08, "SAMC20G15A", 32, 4 },
181         { 0x0A, "SAMC20E18A", 256, 32 },
182         { 0x0B, "SAMC20E17A", 128, 16 },
183         { 0x0C, "SAMC20E16A", 64, 8 },
184         { 0x0D, "SAMC20E15A", 32, 4 },
185 };
186
187 /* Known SAMC21 parts. */
188 static const struct samd_part samc21_parts[] = {
189         { 0x00, "SAMC21J18A", 256, 32 },
190         { 0x01, "SAMC21J17A", 128, 16 },
191         { 0x02, "SAMC21J16A", 64, 8 },
192         { 0x03, "SAMC21J15A", 32, 4 },
193         { 0x05, "SAMC21G18A", 256, 32 },
194         { 0x06, "SAMC21G17A", 128, 16 },
195         { 0x07, "SAMC21G16A", 64, 8 },
196         { 0x08, "SAMC21G15A", 32, 4 },
197         { 0x0A, "SAMC21E18A", 256, 32 },
198         { 0x0B, "SAMC21E17A", 128, 16 },
199         { 0x0C, "SAMC21E16A", 64, 8 },
200         { 0x0D, "SAMC21E15A", 32, 4 },
201 };
202
203 /* Each family of parts contains a parts table in the DEVSEL field of DID.  The
204  * processor ID, family ID, and series ID are used to determine which exact
205  * family this is and then we can use the corresponding table. */
206 struct samd_family {
207         uint8_t processor;
208         uint8_t family;
209         uint8_t series;
210         const struct samd_part *parts;
211         size_t num_parts;
212 };
213
214 /* Known SAMD families */
215 static const struct samd_family samd_families[] = {
216         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_20,
217                 samd20_parts, ARRAY_SIZE(samd20_parts) },
218         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_21,
219                 samd21_parts, ARRAY_SIZE(samd21_parts) },
220         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_21,
221                 samr21_parts, ARRAY_SIZE(samr21_parts) },
222         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_10,
223                 samd10_parts, ARRAY_SIZE(samd10_parts) },
224         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_11,
225                 samd11_parts, ARRAY_SIZE(samd11_parts) },
226         { SAMD_PROCESSOR_M0, SAMD_FAMILY_L, SAMD_SERIES_21,
227                 saml21_parts, ARRAY_SIZE(saml21_parts) },
228         { SAMD_PROCESSOR_M0, SAMD_FAMILY_C, SAMD_SERIES_20,
229                 samc20_parts, ARRAY_SIZE(samc20_parts) },
230         { SAMD_PROCESSOR_M0, SAMD_FAMILY_C, SAMD_SERIES_21,
231                 samc21_parts, ARRAY_SIZE(samc21_parts) },
232 };
233
234 struct samd_info {
235         uint32_t page_size;
236         int num_pages;
237         int sector_size;
238
239         bool probed;
240         struct target *target;
241         struct samd_info *next;
242 };
243
244 static struct samd_info *samd_chips;
245
246 static const struct samd_part *samd_find_part(uint32_t id)
247 {
248         uint8_t processor = (id >> 28);
249         uint8_t family = (id >> 23) & 0x1F;
250         uint8_t series = (id >> 16) & 0x3F;
251         uint8_t devsel = id & 0xFF;
252
253         for (unsigned i = 0; i < ARRAY_SIZE(samd_families); i++) {
254                 if (samd_families[i].processor == processor &&
255                         samd_families[i].series == series &&
256                         samd_families[i].family == family) {
257                         for (unsigned j = 0; j < samd_families[i].num_parts; j++) {
258                                 if (samd_families[i].parts[j].id == devsel)
259                                         return &samd_families[i].parts[j];
260                         }
261                 }
262         }
263
264         return NULL;
265 }
266
267 static int samd_protect_check(struct flash_bank *bank)
268 {
269         int res;
270         uint16_t lock;
271
272         res = target_read_u16(bank->target,
273                         SAMD_NVMCTRL + SAMD_NVMCTRL_LOCK, &lock);
274         if (res != ERROR_OK)
275                 return res;
276
277         /* Lock bits are active-low */
278         for (int i = 0; i < bank->num_sectors; i++)
279                 bank->sectors[i].is_protected = !(lock & (1<<i));
280
281         return ERROR_OK;
282 }
283
284 static int samd_get_flash_page_info(struct target *target,
285                 uint32_t *sizep, int *nump)
286 {
287         int res;
288         uint32_t param;
289
290         res = target_read_u32(target, SAMD_NVMCTRL + SAMD_NVMCTRL_PARAM, &param);
291         if (res == ERROR_OK) {
292                 /* The PSZ field (bits 18:16) indicate the page size bytes as 2^(3+n)
293                  * so 0 is 8KB and 7 is 1024KB. */
294                 if (sizep)
295                         *sizep = (8 << ((param >> 16) & 0x7));
296                 /* The NVMP field (bits 15:0) indicates the total number of pages */
297                 if (nump)
298                         *nump = param & 0xFFFF;
299         } else {
300                 LOG_ERROR("Couldn't read NVM Parameters register");
301         }
302
303         return res;
304 }
305
306 static int samd_probe(struct flash_bank *bank)
307 {
308         uint32_t id;
309         int res;
310         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
311         const struct samd_part *part;
312
313         if (chip->probed)
314                 return ERROR_OK;
315
316         res = target_read_u32(bank->target, SAMD_DSU + SAMD_DSU_DID, &id);
317         if (res != ERROR_OK) {
318                 LOG_ERROR("Couldn't read Device ID register");
319                 return res;
320         }
321
322         part = samd_find_part(id);
323         if (part == NULL) {
324                 LOG_ERROR("Couldn't find part correspoding to DID %08" PRIx32, id);
325                 return ERROR_FAIL;
326         }
327
328         bank->size = part->flash_kb * 1024;
329
330         chip->sector_size = bank->size / SAMD_NUM_SECTORS;
331
332         res = samd_get_flash_page_info(bank->target, &chip->page_size,
333                         &chip->num_pages);
334         if (res != ERROR_OK) {
335                 LOG_ERROR("Couldn't determine Flash page size");
336                 return res;
337         }
338
339         /* Sanity check: the total flash size in the DSU should match the page size
340          * multiplied by the number of pages. */
341         if (bank->size != chip->num_pages * chip->page_size) {
342                 LOG_WARNING("SAMD: bank size doesn't match NVM parameters. "
343                                 "Identified %" PRIu32 "KB Flash but NVMCTRL reports %u %" PRIu32 "B pages",
344                                 part->flash_kb, chip->num_pages, chip->page_size);
345         }
346
347         /* Allocate the sector table */
348         bank->num_sectors = SAMD_NUM_SECTORS;
349         bank->sectors = calloc(bank->num_sectors, sizeof((bank->sectors)[0]));
350         if (!bank->sectors)
351                 return ERROR_FAIL;
352
353         /* Fill out the sector information: all SAMD sectors are the same size and
354          * there is always a fixed number of them. */
355         for (int i = 0; i < bank->num_sectors; i++) {
356                 bank->sectors[i].size = chip->sector_size;
357                 bank->sectors[i].offset = i * chip->sector_size;
358                 /* mark as unknown */
359                 bank->sectors[i].is_erased = -1;
360                 bank->sectors[i].is_protected = -1;
361         }
362
363         samd_protect_check(bank);
364
365         /* Done */
366         chip->probed = true;
367
368         LOG_INFO("SAMD MCU: %s (%" PRIu32 "KB Flash, %" PRIu32 "KB RAM)", part->name,
369                         part->flash_kb, part->ram_kb);
370
371         return ERROR_OK;
372 }
373
374 static bool samd_check_error(struct target *target)
375 {
376         int ret;
377         bool error;
378         uint16_t status;
379
380         ret = target_read_u16(target,
381                         SAMD_NVMCTRL + SAMD_NVMCTRL_STATUS, &status);
382         if (ret != ERROR_OK) {
383                 LOG_ERROR("Can't read NVM status");
384                 return true;
385         }
386
387         if (status & 0x001C) {
388                 if (status & (1 << 4)) /* NVME */
389                         LOG_ERROR("SAMD: NVM Error");
390                 if (status & (1 << 3)) /* LOCKE */
391                         LOG_ERROR("SAMD: NVM lock error");
392                 if (status & (1 << 2)) /* PROGE */
393                         LOG_ERROR("SAMD: NVM programming error");
394
395                 error = true;
396         } else {
397                 error = false;
398         }
399
400         /* Clear the error conditions by writing a one to them */
401         ret = target_write_u16(target,
402                         SAMD_NVMCTRL + SAMD_NVMCTRL_STATUS, status);
403         if (ret != ERROR_OK)
404                 LOG_ERROR("Can't clear NVM error conditions");
405
406         return error;
407 }
408
409 static int samd_issue_nvmctrl_command(struct target *target, uint16_t cmd)
410 {
411         if (target->state != TARGET_HALTED) {
412                 LOG_ERROR("Target not halted");
413                 return ERROR_TARGET_NOT_HALTED;
414         }
415
416         /* Read current configuration. */
417         uint16_t tmp = 0;
418         int res = target_read_u16(target, SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLB,
419                         &tmp);
420         if (res != ERROR_OK)
421                 return res;
422
423         /* Set cache disable. */
424         res = target_write_u16(target, SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLB,
425                         tmp | (1<<18));
426         if (res != ERROR_OK)
427                 return res;
428
429         /* Issue the NVM command */
430         int res_cmd = target_write_u16(target,
431                         SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLA, SAMD_NVM_CMD(cmd));
432
433         /* Try to restore configuration, regardless of NVM command write
434          * status. */
435         res = target_write_u16(target, SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLB, tmp);
436
437         if (res_cmd != ERROR_OK)
438                 return res_cmd;
439
440         if (res != ERROR_OK)
441                 return res;
442
443         /* Check to see if the NVM command resulted in an error condition. */
444         if (samd_check_error(target))
445                 return ERROR_FAIL;
446
447         return ERROR_OK;
448 }
449
450 static int samd_erase_row(struct target *target, uint32_t address)
451 {
452         int res;
453
454         /* Set an address contained in the row to be erased */
455         res = target_write_u32(target,
456                         SAMD_NVMCTRL + SAMD_NVMCTRL_ADDR, address >> 1);
457
458         /* Issue the Erase Row command to erase that row. */
459         if (res == ERROR_OK)
460                 res = samd_issue_nvmctrl_command(target,
461                                 address == SAMD_USER_ROW ? SAMD_NVM_CMD_EAR : SAMD_NVM_CMD_ER);
462
463         if (res != ERROR_OK)  {
464                 LOG_ERROR("Failed to erase row containing %08" PRIx32, address);
465                 return ERROR_FAIL;
466         }
467
468         return ERROR_OK;
469 }
470
471 static bool is_user_row_reserved_bit(uint8_t bit)
472 {
473         /* See Table 9-3 in the SAMD20 datasheet for more information. */
474         switch (bit) {
475                 /* Reserved bits */
476                 case 3:
477                 case 7:
478                 /* Voltage regulator internal configuration with default value of 0x70,
479                  * may not be changed. */
480                 case 17 ... 24:
481                 /* 41 is voltage regulator internal configuration and must not be
482                  * changed.  42 through 47 are reserved. */
483                 case 41 ... 47:
484                         return true;
485                 default:
486                         break;
487         }
488
489         return false;
490 }
491
492 /* Modify the contents of the User Row in Flash.  These are described in Table
493  * 9-3 of the SAMD20 datasheet.  The User Row itself has a size of one page
494  * and contains a combination of "fuses" and calibration data in bits 24:17.
495  * We therefore try not to erase the row's contents unless we absolutely have
496  * to and we don't permit modifying reserved bits. */
497 static int samd_modify_user_row(struct target *target, uint32_t value,
498                 uint8_t startb, uint8_t endb)
499 {
500         int res;
501
502         if (is_user_row_reserved_bit(startb) || is_user_row_reserved_bit(endb)) {
503                 LOG_ERROR("Can't modify bits in the requested range");
504                 return ERROR_FAIL;
505         }
506
507         /* Retrieve the MCU's page size, in bytes. This is also the size of the
508          * entire User Row. */
509         uint32_t page_size;
510         res = samd_get_flash_page_info(target, &page_size, NULL);
511         if (res != ERROR_OK) {
512                 LOG_ERROR("Couldn't determine Flash page size");
513                 return res;
514         }
515
516         /* Make sure the size is sane before we allocate. */
517         assert(page_size > 0 && page_size <= SAMD_PAGE_SIZE_MAX);
518
519         /* Make sure we're within the single page that comprises the User Row. */
520         if (startb >= (page_size * 8) || endb >= (page_size * 8)) {
521                 LOG_ERROR("Can't modify bits outside the User Row page range");
522                 return ERROR_FAIL;
523         }
524
525         uint8_t *buf = malloc(page_size);
526         if (!buf)
527                 return ERROR_FAIL;
528
529         /* Read the user row (comprising one page) by half-words. */
530         res = target_read_memory(target, SAMD_USER_ROW, 2, page_size / 2, buf);
531         if (res != ERROR_OK)
532                 goto out_user_row;
533
534         /* We will need to erase before writing if the new value needs a '1' in any
535          * position for which the current value had a '0'.  Otherwise we can avoid
536          * erasing. */
537         uint32_t cur = buf_get_u32(buf, startb, endb - startb + 1);
538         if ((~cur) & value) {
539                 res = samd_erase_row(target, SAMD_USER_ROW);
540                 if (res != ERROR_OK) {
541                         LOG_ERROR("Couldn't erase user row");
542                         goto out_user_row;
543                 }
544         }
545
546         /* Modify */
547         buf_set_u32(buf, startb, endb - startb + 1, value);
548
549         /* Write the page buffer back out to the target.  A Flash write will be
550          * triggered automatically. */
551         res = target_write_memory(target, SAMD_USER_ROW, 4, page_size / 4, buf);
552         if (res != ERROR_OK)
553                 goto out_user_row;
554
555         if (samd_check_error(target)) {
556                 res = ERROR_FAIL;
557                 goto out_user_row;
558         }
559
560         /* Success */
561         res = ERROR_OK;
562
563 out_user_row:
564         free(buf);
565
566         return res;
567 }
568
569 static int samd_protect(struct flash_bank *bank, int set, int first, int last)
570 {
571         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
572
573         /* We can issue lock/unlock region commands with the target running but
574          * the settings won't persist unless we're able to modify the LOCK regions
575          * and that requires the target to be halted. */
576         if (bank->target->state != TARGET_HALTED) {
577                 LOG_ERROR("Target not halted");
578                 return ERROR_TARGET_NOT_HALTED;
579         }
580
581         int res = ERROR_OK;
582
583         for (int s = first; s <= last; s++) {
584                 if (set != bank->sectors[s].is_protected) {
585                         /* Load an address that is within this sector (we use offset 0) */
586                         res = target_write_u32(bank->target,
587                                                         SAMD_NVMCTRL + SAMD_NVMCTRL_ADDR,
588                                                         ((s * chip->sector_size) >> 1));
589                         if (res != ERROR_OK)
590                                 goto exit;
591
592                         /* Tell the controller to lock that sector */
593                         res = samd_issue_nvmctrl_command(bank->target,
594                                         set ? SAMD_NVM_CMD_LR : SAMD_NVM_CMD_UR);
595                         if (res != ERROR_OK)
596                                 goto exit;
597                 }
598         }
599
600         /* We've now applied our changes, however they will be undone by the next
601          * reset unless we also apply them to the LOCK bits in the User Page.  The
602          * LOCK bits start at bit 48, correspoding to Sector 0 and end with bit 63,
603          * corresponding to Sector 15.  A '1' means unlocked and a '0' means
604          * locked.  See Table 9-3 in the SAMD20 datasheet for more details. */
605
606         res = samd_modify_user_row(bank->target, set ? 0x0000 : 0xFFFF,
607                         48 + first, 48 + last);
608         if (res != ERROR_OK)
609                 LOG_WARNING("SAMD: protect settings were not made persistent!");
610
611         res = ERROR_OK;
612
613 exit:
614         samd_protect_check(bank);
615
616         return res;
617 }
618
619 static int samd_erase(struct flash_bank *bank, int first, int last)
620 {
621         int res;
622         int rows_in_sector;
623         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
624
625         if (bank->target->state != TARGET_HALTED) {
626                 LOG_ERROR("Target not halted");
627
628                 return ERROR_TARGET_NOT_HALTED;
629         }
630
631         if (!chip->probed) {
632                 if (samd_probe(bank) != ERROR_OK)
633                         return ERROR_FLASH_BANK_NOT_PROBED;
634         }
635
636         /* The SAMD NVM has row erase granularity.  There are four pages in a row
637          * and the number of rows in a sector depends on the sector size, which in
638          * turn depends on the Flash capacity as there is a fixed number of
639          * sectors. */
640         rows_in_sector = chip->sector_size / (chip->page_size * 4);
641
642         /* For each sector to be erased */
643         for (int s = first; s <= last; s++) {
644                 if (bank->sectors[s].is_protected) {
645                         LOG_ERROR("SAMD: failed to erase sector %d. That sector is write-protected", s);
646                         return ERROR_FLASH_OPERATION_FAILED;
647                 }
648
649                 if (bank->sectors[s].is_erased != 1) {
650                         /* For each row in that sector */
651                         for (int r = s * rows_in_sector; r < (s + 1) * rows_in_sector; r++) {
652                                 res = samd_erase_row(bank->target, r * chip->page_size * 4);
653                                 if (res != ERROR_OK) {
654                                         LOG_ERROR("SAMD: failed to erase sector %d", s);
655                                         return res;
656                                 }
657                         }
658
659                         bank->sectors[s].is_erased = 1;
660                 }
661         }
662
663         return ERROR_OK;
664 }
665
666 static struct flash_sector *samd_find_sector_by_address(struct flash_bank *bank, uint32_t address)
667 {
668         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
669
670         for (int i = 0; i < bank->num_sectors; i++) {
671                 if (bank->sectors[i].offset <= address &&
672                     address < bank->sectors[i].offset + chip->sector_size)
673                         return &bank->sectors[i];
674         }
675         return NULL;
676 }
677
678 /* Write an entire row (four pages) from host buffer 'buf' to row-aligned
679  * 'address' in the Flash. */
680 static int samd_write_row(struct flash_bank *bank, uint32_t address,
681                 const uint8_t *buf)
682 {
683         int res;
684         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
685
686         struct flash_sector *sector = samd_find_sector_by_address(bank, address);
687
688         if (!sector) {
689                 LOG_ERROR("Can't find sector corresponding to address 0x%08" PRIx32, address);
690                 return ERROR_FLASH_OPERATION_FAILED;
691         }
692
693         if (sector->is_protected) {
694                 LOG_ERROR("Trying to write to a protected sector at 0x%08" PRIx32, address);
695                 return ERROR_FLASH_OPERATION_FAILED;
696         }
697
698         /* Erase the row that we'll be writing to */
699         res = samd_erase_row(bank->target, address);
700         if (res != ERROR_OK)
701                 return res;
702
703         /* Now write the pages in this row. */
704         for (unsigned int i = 0; i < 4; i++) {
705                 bool error;
706
707                 /* Write the page contents to the target's page buffer.  A page write
708                  * is issued automatically once the last location is written in the
709                  * page buffer (ie: a complete page has been written out). */
710                 res = target_write_memory(bank->target, address, 4,
711                                 chip->page_size / 4, buf);
712                 if (res != ERROR_OK) {
713                         LOG_ERROR("%s: %d", __func__, __LINE__);
714                         return res;
715                 }
716
717                 /* Access through AHB is stalled while flash is being programmed */
718                 usleep(200);
719
720                 error = samd_check_error(bank->target);
721                 if (error)
722                         return ERROR_FAIL;
723
724                 /* Next page */
725                 address += chip->page_size;
726                 buf += chip->page_size;
727         }
728
729         sector->is_erased = 0;
730
731         return res;
732 }
733
734 /* Write partial contents into row-aligned 'address' on the Flash from host
735  * buffer 'buf' by writing 'nb' of 'buf' at 'row_offset' into the Flash row. */
736 static int samd_write_row_partial(struct flash_bank *bank, uint32_t address,
737                 const uint8_t *buf, uint32_t row_offset, uint32_t nb)
738 {
739         int res;
740         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
741         uint32_t row_size = chip->page_size * 4;
742         uint8_t *rb = malloc(row_size);
743         if (!rb)
744                 return ERROR_FAIL;
745
746         assert(row_offset + nb < row_size);
747         assert((address % row_size) == 0);
748
749         /* Retrieve the full row contents from Flash */
750         res = target_read_memory(bank->target, address, 4, row_size / 4, rb);
751         if (res != ERROR_OK) {
752                 free(rb);
753                 return res;
754         }
755
756         /* Insert our partial row over the data from Flash */
757         memcpy(rb + (row_offset % row_size), buf, nb);
758
759         /* Write the row back out */
760         res = samd_write_row(bank, address, rb);
761         free(rb);
762
763         return res;
764 }
765
766 static int samd_write(struct flash_bank *bank, const uint8_t *buffer,
767                 uint32_t offset, uint32_t count)
768 {
769         int res;
770         uint32_t address;
771         uint32_t nb = 0;
772         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
773         uint32_t row_size = chip->page_size * 4;
774
775         if (bank->target->state != TARGET_HALTED) {
776                 LOG_ERROR("Target not halted");
777
778                 return ERROR_TARGET_NOT_HALTED;
779         }
780
781         if (!chip->probed) {
782                 if (samd_probe(bank) != ERROR_OK)
783                         return ERROR_FLASH_BANK_NOT_PROBED;
784         }
785
786         if (offset % row_size) {
787                 /* We're starting at an unaligned offset so we'll write a partial row
788                  * comprising that offset and up to the end of that row. */
789                 nb = row_size - (offset % row_size);
790                 if (nb > count)
791                         nb = count;
792         } else if (count < row_size) {
793                 /* We're writing an aligned but partial row. */
794                 nb = count;
795         }
796
797         address = (offset / row_size) * row_size + bank->base;
798
799         if (nb > 0) {
800                 res = samd_write_row_partial(bank, address, buffer,
801                                 offset % row_size, nb);
802                 if (res != ERROR_OK)
803                         return res;
804
805                 /* We're done with the row contents */
806                 count -= nb;
807                 offset += nb;
808                 buffer += row_size;
809         }
810
811         /* There's at least one aligned row to write out. */
812         if (count >= row_size) {
813                 int nr = count / row_size + ((count % row_size) ? 1 : 0);
814                 unsigned int r = 0;
815
816                 for (unsigned int i = address / row_size;
817                                 (i < (address / row_size) + nr) && count > 0; i++) {
818                         address = (i * row_size) + bank->base;
819
820                         if (count >= row_size) {
821                                 res = samd_write_row(bank, address, buffer + (r * row_size));
822                                 /* Advance one row */
823                                 offset += row_size;
824                                 count -= row_size;
825                         } else {
826                                 res = samd_write_row_partial(bank, address,
827                                                 buffer + (r * row_size), 0, count);
828                                 /* We're done after this. */
829                                 offset += count;
830                                 count = 0;
831                         }
832
833                         r++;
834
835                         if (res != ERROR_OK)
836                                 return res;
837                 }
838         }
839
840         return ERROR_OK;
841 }
842
843 FLASH_BANK_COMMAND_HANDLER(samd_flash_bank_command)
844 {
845         struct samd_info *chip = samd_chips;
846
847         while (chip) {
848                 if (chip->target == bank->target)
849                         break;
850                 chip = chip->next;
851         }
852
853         if (!chip) {
854                 /* Create a new chip */
855                 chip = calloc(1, sizeof(*chip));
856                 if (!chip)
857                         return ERROR_FAIL;
858
859                 chip->target = bank->target;
860                 chip->probed = false;
861
862                 bank->driver_priv = chip;
863
864                 /* Insert it into the chips list (at head) */
865                 chip->next = samd_chips;
866                 samd_chips = chip;
867         }
868
869         if (bank->base != SAMD_FLASH) {
870                 LOG_ERROR("Address 0x%08" PRIx32 " invalid bank address (try 0x%08" PRIx32
871                                 "[at91samd series] )",
872                                 bank->base, SAMD_FLASH);
873                 return ERROR_FAIL;
874         }
875
876         return ERROR_OK;
877 }
878
879 COMMAND_HANDLER(samd_handle_info_command)
880 {
881         return ERROR_OK;
882 }
883
884 COMMAND_HANDLER(samd_handle_chip_erase_command)
885 {
886         struct target *target = get_current_target(CMD_CTX);
887
888         if (target) {
889                 /* Enable access to the DSU by disabling the write protect bit */
890                 target_write_u32(target, SAMD_PAC1, (1<<1));
891                 /* Tell the DSU to perform a full chip erase.  It takes about 240ms to
892                  * perform the erase. */
893                 target_write_u8(target, SAMD_DSU, (1<<4));
894
895                 command_print(CMD_CTX, "chip erased");
896         }
897
898         return ERROR_OK;
899 }
900
901 COMMAND_HANDLER(samd_handle_set_security_command)
902 {
903         int res = ERROR_OK;
904         struct target *target = get_current_target(CMD_CTX);
905
906         if (CMD_ARGC < 1 || (CMD_ARGC >= 1 && (strcmp(CMD_ARGV[0], "enable")))) {
907                 command_print(CMD_CTX, "supply the \"enable\" argument to proceed.");
908                 return ERROR_COMMAND_SYNTAX_ERROR;
909         }
910
911         if (target) {
912                 if (target->state != TARGET_HALTED) {
913                         LOG_ERROR("Target not halted");
914                         return ERROR_TARGET_NOT_HALTED;
915                 }
916
917                 res = samd_issue_nvmctrl_command(target, SAMD_NVM_CMD_SSB);
918
919                 /* Check (and clear) error conditions */
920                 if (res == ERROR_OK)
921                         command_print(CMD_CTX, "chip secured on next power-cycle");
922                 else
923                         command_print(CMD_CTX, "failed to secure chip");
924         }
925
926         return res;
927 }
928
929 COMMAND_HANDLER(samd_handle_eeprom_command)
930 {
931         int res = ERROR_OK;
932         struct target *target = get_current_target(CMD_CTX);
933
934         if (target) {
935                 if (target->state != TARGET_HALTED) {
936                         LOG_ERROR("Target not halted");
937                         return ERROR_TARGET_NOT_HALTED;
938                 }
939
940                 if (CMD_ARGC >= 1) {
941                         int val = atoi(CMD_ARGV[0]);
942                         uint32_t code;
943
944                         if (val == 0)
945                                 code = 7;
946                         else {
947                                 /* Try to match size in bytes with corresponding size code */
948                                 for (code = 0; code <= 6; code++) {
949                                         if (val == (2 << (13 - code)))
950                                                 break;
951                                 }
952
953                                 if (code > 6) {
954                                         command_print(CMD_CTX, "Invalid EEPROM size.  Please see "
955                                                         "datasheet for a list valid sizes.");
956                                         return ERROR_COMMAND_SYNTAX_ERROR;
957                                 }
958                         }
959
960                         res = samd_modify_user_row(target, code, 4, 6);
961                 } else {
962                         uint16_t val;
963                         res = target_read_u16(target, SAMD_USER_ROW, &val);
964                         if (res == ERROR_OK) {
965                                 uint32_t size = ((val >> 4) & 0x7); /* grab size code */
966
967                                 if (size == 0x7)
968                                         command_print(CMD_CTX, "EEPROM is disabled");
969                                 else {
970                                         /* Otherwise, 6 is 256B, 0 is 16KB */
971                                         command_print(CMD_CTX, "EEPROM size is %u bytes",
972                                                         (2 << (13 - size)));
973                                 }
974                         }
975                 }
976         }
977
978         return res;
979 }
980
981 COMMAND_HANDLER(samd_handle_bootloader_command)
982 {
983         int res = ERROR_OK;
984         struct target *target = get_current_target(CMD_CTX);
985
986         if (target) {
987                 if (target->state != TARGET_HALTED) {
988                         LOG_ERROR("Target not halted");
989                         return ERROR_TARGET_NOT_HALTED;
990                 }
991
992                 /* Retrieve the MCU's page size, in bytes. */
993                 uint32_t page_size;
994                 res = samd_get_flash_page_info(target, &page_size, NULL);
995                 if (res != ERROR_OK) {
996                         LOG_ERROR("Couldn't determine Flash page size");
997                         return res;
998                 }
999
1000                 if (CMD_ARGC >= 1) {
1001                         int val = atoi(CMD_ARGV[0]);
1002                         uint32_t code;
1003
1004                         if (val == 0)
1005                                 code = 7;
1006                         else {
1007                                 /* Try to match size in bytes with corresponding size code */
1008                                 for (code = 0; code <= 6; code++) {
1009                                         if ((unsigned int)val == (2UL << (8UL - code)) * page_size)
1010                                                 break;
1011                                 }
1012
1013                                 if (code > 6) {
1014                                         command_print(CMD_CTX, "Invalid bootloader size.  Please "
1015                                                         "see datasheet for a list valid sizes.");
1016                                         return ERROR_COMMAND_SYNTAX_ERROR;
1017                                 }
1018
1019                         }
1020
1021                         res = samd_modify_user_row(target, code, 0, 2);
1022                 } else {
1023                         uint16_t val;
1024                         res = target_read_u16(target, SAMD_USER_ROW, &val);
1025                         if (res == ERROR_OK) {
1026                                 uint32_t size = (val & 0x7); /* grab size code */
1027                                 uint32_t nb;
1028
1029                                 if (size == 0x7)
1030                                         nb = 0;
1031                                 else
1032                                         nb = (2 << (8 - size)) * page_size;
1033
1034                                 /* There are 4 pages per row */
1035                                 command_print(CMD_CTX, "Bootloader size is %" PRIu32 " bytes (%" PRIu32 " rows)",
1036                                            nb, (uint32_t)(nb / (page_size * 4)));
1037                         }
1038                 }
1039         }
1040
1041         return res;
1042 }
1043
1044
1045
1046 COMMAND_HANDLER(samd_handle_reset_deassert)
1047 {
1048         struct target *target = get_current_target(CMD_CTX);
1049         struct armv7m_common *armv7m = target_to_armv7m(target);
1050         struct adiv5_dap *swjdp = armv7m->arm.dap;
1051         int retval = ERROR_OK;
1052         enum reset_types jtag_reset_config = jtag_get_reset_config();
1053
1054         /* In case of sysresetreq, debug retains state set in cortex_m_assert_reset()
1055          * so we just release reset held by DSU
1056          *
1057          * n_RESET (srst) clears the DP, so reenable debug and set vector catch here
1058          *
1059          * After vectreset DSU release is not needed however makes no harm
1060          */
1061         if (target->reset_halt && (jtag_reset_config & RESET_HAS_SRST)) {
1062                 retval = mem_ap_write_u32(swjdp, DCB_DHCSR, DBGKEY | C_HALT | C_DEBUGEN);
1063                 if (retval == ERROR_OK)
1064                         retval = mem_ap_write_u32(swjdp, DCB_DEMCR,
1065                                 TRCENA | VC_HARDERR | VC_BUSERR | VC_CORERESET);
1066                 /* do not return on error here, releasing DSU reset is more important */
1067         }
1068
1069         /* clear CPU Reset Phase Extension bit */
1070         int retval2 = target_write_u8(target, SAMD_DSU + SAMD_DSU_STATUSA, (1<<1));
1071         if (retval2 != ERROR_OK)
1072                 return retval2;
1073
1074         return retval;
1075 }
1076
1077 static const struct command_registration at91samd_exec_command_handlers[] = {
1078         {
1079                 .name = "dsu_reset_deassert",
1080                 .handler = samd_handle_reset_deassert,
1081                 .mode = COMMAND_EXEC,
1082                 .help = "deasert internal reset held by DSU"
1083         },
1084         {
1085                 .name = "info",
1086                 .handler = samd_handle_info_command,
1087                 .mode = COMMAND_EXEC,
1088                 .help = "Print information about the current at91samd chip"
1089                         "and its flash configuration.",
1090         },
1091         {
1092                 .name = "chip-erase",
1093                 .handler = samd_handle_chip_erase_command,
1094                 .mode = COMMAND_EXEC,
1095                 .help = "Erase the entire Flash by using the Chip"
1096                         "Erase feature in the Device Service Unit (DSU).",
1097         },
1098         {
1099                 .name = "set-security",
1100                 .handler = samd_handle_set_security_command,
1101                 .mode = COMMAND_EXEC,
1102                 .help = "Secure the chip's Flash by setting the Security Bit."
1103                         "This makes it impossible to read the Flash contents."
1104                         "The only way to undo this is to issue the chip-erase"
1105                         "command.",
1106         },
1107         {
1108                 .name = "eeprom",
1109                 .usage = "[size_in_bytes]",
1110                 .handler = samd_handle_eeprom_command,
1111                 .mode = COMMAND_EXEC,
1112                 .help = "Show or set the EEPROM size setting, stored in the User Row."
1113                         "Please see Table 20-3 of the SAMD20 datasheet for allowed values."
1114                         "Changes are stored immediately but take affect after the MCU is"
1115                         "reset.",
1116         },
1117         {
1118                 .name = "bootloader",
1119                 .usage = "[size_in_bytes]",
1120                 .handler = samd_handle_bootloader_command,
1121                 .mode = COMMAND_EXEC,
1122                 .help = "Show or set the bootloader size, stored in the User Row."
1123                         "Please see Table 20-2 of the SAMD20 datasheet for allowed values."
1124                         "Changes are stored immediately but take affect after the MCU is"
1125                         "reset.",
1126         },
1127         COMMAND_REGISTRATION_DONE
1128 };
1129
1130 static const struct command_registration at91samd_command_handlers[] = {
1131         {
1132                 .name = "at91samd",
1133                 .mode = COMMAND_ANY,
1134                 .help = "at91samd flash command group",
1135                 .usage = "",
1136                 .chain = at91samd_exec_command_handlers,
1137         },
1138         COMMAND_REGISTRATION_DONE
1139 };
1140
1141 struct flash_driver at91samd_flash = {
1142         .name = "at91samd",
1143         .commands = at91samd_command_handlers,
1144         .flash_bank_command = samd_flash_bank_command,
1145         .erase = samd_erase,
1146         .protect = samd_protect,
1147         .write = samd_write,
1148         .read = default_flash_read,
1149         .probe = samd_probe,
1150         .auto_probe = samd_probe,
1151         .erase_check = default_flash_blank_check,
1152         .protect_check = samd_protect_check,
1153 };