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