add support for Atmel SAMD NOR Flash
[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
27 #define SAMD_NUM_SECTORS        16
28
29 #define SAMD_FLASH                      0x00000000      /* physical Flash memory */
30 #define SAMD_DSU                        0x41002000      /* Device Service Unit */
31 #define SAMD_NVMCTRL            0x41004000      /* Non-volatile memory controller */
32
33 #define SAMD_DSU_DID            0x18            /* Device ID register */
34
35 #define SAMD_NVMCTRL_CTRLA              0x00    /* NVM control A register */
36 #define SAMD_NVMCTRL_CTRLB              0x04    /* NVM control B register */
37 #define SAMD_NVMCTRL_PARAM              0x08    /* NVM parameters register */
38 #define SAMD_NVMCTRL_INTFLAG    0x18    /* NVM Interupt Flag Status & Clear */
39 #define SAMD_NVMCTRL_STATUS             0x18    /* NVM status register */
40 #define SAMD_NVMCTRL_ADDR               0x1C    /* NVM address register */
41 #define SAMD_NVMCTRL_LOCK               0x20    /* NVM Lock section register */
42
43 #define SAMD_CMDEX_KEY          0xA5UL
44 #define SAMD_NVM_CMD(n)         ((SAMD_CMDEX_KEY << 8) | (n & 0x7F))
45
46 /* NVMCTRL commands.  See Table 20-4 in 42129F–SAM–10/2013 */
47 #define SAMD_NVM_CMD_ER         0x02            /* Erase Row */
48 #define SAMD_NVM_CMD_WP         0x04            /* Write Page */
49 #define SAMD_NVM_CMD_EAR        0x05            /* Erase Auxilary Row */
50 #define SAMD_NVM_CMD_WAP        0x06            /* Write Auxilary Page */
51 #define SAMD_NVM_CMD_LR         0x40            /* Lock Region */
52 #define SAMD_NVM_CMD_UR         0x41            /* Unlock Region */
53 #define SAMD_NVM_CMD_SPRM       0x42            /* Set Power Reduction Mode */
54 #define SAMD_NVM_CMD_CPRM       0x43            /* Clear Power Reduction Mode */
55 #define SAMD_NVM_CMD_PBC        0x44            /* Page Buffer Clear */
56 #define SAMD_NVM_CMD_SSB        0x45            /* Set Security Bit */
57 #define SAMD_NVM_CMD_INVALL     0x46            /* Invalidate all caches */
58
59 /* Known identifiers */
60 #define SAMD_PROCESSOR_M0       0x01
61 #define SAMD_FAMILY_D           0x00
62 #define SAMD_SERIES_20          0x00
63
64 struct samd_part {
65         uint8_t id;
66         const char *name;
67         uint32_t flash_kb;
68         uint32_t ram_kb;
69 };
70
71 /* Known SAMD20 parts. See Table 12-8 in 42129F–SAM–10/2013 */
72 static struct samd_part samd20_parts[] = {
73         { 0x0, "SAMD20J18A", 256, 32 },
74         { 0x1, "SAMD20J17A", 128, 16 },
75         { 0x2, "SAMD20J16A", 64, 8 },
76         { 0x3, "SAMD20J15A", 32, 4 },
77         { 0x4, "SAMD20J14A", 16, 2 },
78         { 0x5, "SAMD20G18A", 256, 32 },
79         { 0x6, "SAMD20G17A", 128, 16 },
80         { 0x7, "SAMD20G16A", 64, 8 },
81         { 0x8, "SAMD20G15A", 32, 4 },
82         { 0x9, "SAMD20G14A", 16, 2 },
83         { 0xB, "SAMD20E17A", 128, 16 },
84         { 0xC, "SAMD20E16A", 64, 8 },
85         { 0xD, "SAMD20E15A", 32, 4 },
86         { 0xE, "SAMD20E14A", 16, 2 },
87 };
88
89 /* Each family of parts contains a parts table in the DEVSEL field of DID.  The
90  * processor ID, family ID, and series ID are used to determine which exact
91  * family this is and then we can use the corresponding table. */
92 struct samd_family {
93         uint8_t processor;
94         uint8_t family;
95         uint8_t series;
96         struct samd_part *parts;
97         size_t num_parts;
98 };
99
100 /* Known SAMD families */
101 static struct samd_family samd_families[] = {
102         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_20,
103                 samd20_parts, ARRAY_SIZE(samd20_parts) },
104 };
105
106 struct samd_info {
107         uint32_t page_size;
108         int num_pages;
109         int sector_size;
110
111         bool probed;
112         struct target *target;
113         struct samd_info *next;
114 };
115
116 static struct samd_info *samd_chips;
117
118 static struct samd_part *samd_find_part(uint32_t id)
119 {
120         uint8_t processor = (id >> 28);
121         uint8_t family = (id >> 24) & 0x0F;
122         uint8_t series = (id >> 16) & 0xFF;
123         uint8_t devsel = id & 0xFF;
124
125         for (unsigned i = 0; i < ARRAY_SIZE(samd_families); i++) {
126                 if (samd_families[i].processor == processor &&
127                         samd_families[i].series == series &&
128                         samd_families[i].family == family) {
129                         for (unsigned j = 0; j < samd_families[i].num_parts; j++) {
130                                 if (samd_families[i].parts[j].id == devsel)
131                                         return &samd_families[i].parts[j];
132                         }
133                 }
134         }
135
136         return NULL;
137 }
138
139 static int samd_protect_check(struct flash_bank *bank)
140 {
141         int res;
142         uint16_t lock;
143
144         res = target_read_u16(bank->target,
145                         SAMD_NVMCTRL + SAMD_NVMCTRL_LOCK, &lock);
146         if (res != ERROR_OK)
147                 return res;
148
149         /* Lock bits are active-low */
150         for (int i = 0; i < bank->num_sectors; i++)
151                 bank->sectors[i].is_protected = !(lock & (1<<i));
152
153         return ERROR_OK;
154 }
155
156 static int samd_probe(struct flash_bank *bank)
157 {
158         uint32_t id, param;
159         int res;
160         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
161         struct samd_part *part;
162
163         if (chip->probed)
164                 return ERROR_OK;
165
166         res = target_read_u32(bank->target, SAMD_DSU + SAMD_DSU_DID, &id);
167         if (res != ERROR_OK) {
168                 LOG_ERROR("Couldn't read Device ID register");
169                 return res;
170         }
171
172         part = samd_find_part(id);
173         if (part == NULL) {
174                 LOG_ERROR("Couldn't find part correspoding to DID %08" PRIx32, id);
175                 return ERROR_FAIL;
176         }
177
178         res = target_read_u32(bank->target,
179                         SAMD_NVMCTRL + SAMD_NVMCTRL_PARAM, &param);
180         if (res != ERROR_OK) {
181                 LOG_ERROR("Couldn't read NVM Parameters register");
182                 return res;
183         }
184
185         bank->size = part->flash_kb * 1024;
186
187         chip->sector_size = bank->size / SAMD_NUM_SECTORS;
188
189         /* The PSZ field (bits 18:16) indicate the page size bytes as 2^(3+n) so
190          * 0 is 8KB and 7 is 1024KB. */
191         chip->page_size = (8 << ((param >> 16) & 0x7));
192         /* The NVMP field (bits 15:0) indicates the total number of pages */
193         chip->num_pages = param & 0xFFFF;
194
195         /* Sanity check: the total flash size in the DSU should match the page size
196          * multiplied by the number of pages. */
197         if (bank->size != chip->num_pages * chip->page_size) {
198                 LOG_WARNING("SAMD: bank size doesn't match NVM parameters. "
199                                 "Identified %uKB Flash but NVMCTRL reports %u %uB pages",
200                                 part->flash_kb, chip->num_pages, chip->page_size);
201         }
202
203         /* Allocate the sector table */
204         bank->num_sectors = SAMD_NUM_SECTORS;
205         bank->sectors = calloc(bank->num_sectors, sizeof((bank->sectors)[0]));
206         if (!bank->sectors)
207                 return ERROR_FAIL;
208
209         /* Fill out the sector information: all SAMD sectors are the same size and
210          * there is always a fixed number of them. */
211         for (int i = 0; i < bank->num_sectors; i++) {
212                 bank->sectors[i].size = chip->sector_size;
213                 bank->sectors[i].offset = i * chip->sector_size;
214                 /* mark as unknown */
215                 bank->sectors[i].is_erased = -1;
216                 bank->sectors[i].is_protected = -1;
217         }
218
219         samd_protect_check(bank);
220
221         /* Done */
222         chip->probed = true;
223
224         LOG_INFO("SAMD MCU: %s (%uKB Flash, %uKB RAM)", part->name,
225                         part->flash_kb, part->ram_kb);
226
227         return ERROR_OK;
228 }
229
230 static int samd_protect(struct flash_bank *bank, int set, int first, int last)
231 {
232         int res;
233         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
234
235         for (int s = first; s <= last; s++) {
236                 /* Load an address that is within this sector (we use offset 0) */
237                 res = target_write_u32(bank->target, SAMD_NVMCTRL + SAMD_NVMCTRL_ADDR,
238                                 s * chip->sector_size);
239                 if (res != ERROR_OK)
240                         return res;
241
242                 /* Tell the controller to lock that sector */
243                 res = target_write_u16(bank->target,
244                                 SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLA,
245                                 SAMD_NVM_CMD(SAMD_NVM_CMD_LR));
246                 if (res != ERROR_OK)
247                         return res;
248         }
249
250         samd_protect_check(bank);
251
252         return ERROR_OK;
253 }
254
255 static bool samd_check_error(struct flash_bank *bank)
256 {
257         int ret;
258         bool error;
259         uint16_t status;
260
261         ret = target_read_u16(bank->target,
262                         SAMD_NVMCTRL + SAMD_NVMCTRL_STATUS, &status);
263         if (ret != ERROR_OK) {
264                 LOG_ERROR("Can't read NVM status");
265                 return true;
266         }
267
268         if (status & 0x001C) {
269                 if (status & (1 << 4)) /* NVME */
270                         LOG_ERROR("SAMD: NVM Error");
271                 if (status & (1 << 3)) /* LOCKE */
272                         LOG_ERROR("SAMD: NVM lock error");
273                 if (status & (1 << 2)) /* PROGE */
274                         LOG_ERROR("SAMD: NVM programming error");
275
276                 error = true;
277         } else {
278                 error = false;
279         }
280
281         /* Clear the error conditions by writing a one to them */
282         ret = target_write_u16(bank->target,
283                         SAMD_NVMCTRL + SAMD_NVMCTRL_STATUS, status);
284         if (ret != ERROR_OK)
285                 LOG_ERROR("Can't clear NVM error conditions");
286
287         return error;
288 }
289
290 static int samd_erase_row(struct flash_bank *bank, uint32_t address)
291 {
292         int res;
293         bool error = false;
294
295         /* Set an address contained in the row to be erased */
296         res = target_write_u32(bank->target,
297                         SAMD_NVMCTRL + SAMD_NVMCTRL_ADDR, address >> 1);
298         if (res == ERROR_OK) {
299                 /* Issue the Erase Row command to erase that row */
300                 res = target_write_u16(bank->target,
301                                 SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLA,
302                                 SAMD_NVM_CMD(SAMD_NVM_CMD_ER));
303
304                 /* Check (and clear) error conditions */
305                 error = samd_check_error(bank);
306         }
307
308         if (res != ERROR_OK || error)  {
309                 LOG_ERROR("Failed to erase row containing %08X" PRIx32, address);
310                 return ERROR_FAIL;
311         }
312
313         return ERROR_OK;
314 }
315
316 static int samd_erase(struct flash_bank *bank, int first, int last)
317 {
318         int res;
319         int rows_in_sector;
320         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
321
322         if (bank->target->state != TARGET_HALTED) {
323                 LOG_ERROR("Target not halted");
324
325                 return ERROR_TARGET_NOT_HALTED;
326         }
327
328         if (!chip->probed) {
329                 if (samd_probe(bank) != ERROR_OK)
330                         return ERROR_FLASH_BANK_NOT_PROBED;
331         }
332
333         /* Make sure the sectors make sense. */
334         if (first >= bank->num_sectors || last >= bank->num_sectors) {
335                 LOG_ERROR("Erase range %d - %d not valid (%d sectors total)",
336                                 first, last, bank->num_sectors);
337                 return ERROR_FAIL;
338         }
339
340         /* The SAMD NVM has row erase granularity.  There are four pages in a row
341          * and the number of rows in a sector depends on the sector size, which in
342          * turn depends on the Flash capacity as there is a fixed number of
343          * sectors. */
344         rows_in_sector = chip->sector_size / (chip->page_size * 4);
345
346         /* For each sector to be erased */
347         for (int s = first; s <= last; s++) {
348                 /* For each row in that sector */
349                 for (int r = s * rows_in_sector; r < (s + 1) * rows_in_sector; r++) {
350                         res = samd_erase_row(bank, r * chip->page_size * 4);
351                         if (res != ERROR_OK) {
352                                 LOG_ERROR("SAMD: failed to erase sector %d", s);
353                                 return res;
354                         }
355                 }
356
357                 bank->sectors[s].is_erased = 1;
358         }
359
360         return ERROR_OK;
361 }
362
363 /* Write an entire row (four pages) from host buffer 'buf' to row-aligned
364  * 'address' in the Flash. */
365 static int samd_write_row(struct flash_bank *bank, uint32_t address,
366                 uint8_t *buf)
367 {
368         int res;
369         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
370
371         /* Erase the row that we'll be writing to */
372         res = samd_erase_row(bank, address);
373         if (res != ERROR_OK)
374                 return res;
375
376         /* Now write the pages in this row. */
377         for (unsigned int i = 0; i < 4; i++) {
378                 bool error;
379
380                 /* Write the page contents to the target's page buffer.  A page write
381                  * is issued automatically once the last location is written in the
382                  * page buffer (ie: a complete page has been written out). */
383                 res = target_write_memory(bank->target, address, 4,
384                                 chip->page_size / 4, buf);
385                 if (res != ERROR_OK) {
386                         LOG_ERROR("%s: %d", __func__, __LINE__);
387                         return res;
388                 }
389
390                 error = samd_check_error(bank);
391                 if (error)
392                         return ERROR_FAIL;
393
394                 /* Next page */
395                 address += chip->page_size;
396                 buf += chip->page_size;
397         }
398
399         return res;
400 }
401
402 /* Write partial contents into row-aligned 'address' on the Flash from host
403  * buffer 'buf' by writing 'nb' of 'buf' at 'row_offset' into the Flash row. */
404 static int samd_write_row_partial(struct flash_bank *bank, uint32_t address,
405                 uint8_t *buf, uint32_t row_offset, uint32_t nb)
406 {
407         int res;
408         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
409         uint32_t row_size = chip->page_size * 4;
410         uint8_t *rb = malloc(row_size);
411         if (!rb)
412                 return ERROR_FAIL;
413
414         assert(row_offset + nb < row_size);
415         assert((address % row_size) == 0);
416
417         /* Retrieve the full row contents from Flash */
418         res = target_read_memory(bank->target, address, 4, row_size / 4, rb);
419         if (res != ERROR_OK) {
420                 free(rb);
421                 return res;
422         }
423
424         /* Insert our partial row over the data from Flash */
425         memcpy(rb + (row_offset % row_size), buf, nb);
426
427         /* Write the row back out */
428         res = samd_write_row(bank, address, rb);
429         free(rb);
430
431         return res;
432 }
433
434 static int samd_write(struct flash_bank *bank, uint8_t *buffer,
435                 uint32_t offset, uint32_t count)
436 {
437         int res;
438         uint32_t address;
439         uint32_t nb = 0;
440         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
441         uint32_t row_size = chip->page_size * 4;
442
443         if (bank->target->state != TARGET_HALTED) {
444                 LOG_ERROR("Target not halted");
445
446                 return ERROR_TARGET_NOT_HALTED;
447         }
448
449         if (!chip->probed) {
450                 if (samd_probe(bank) != ERROR_OK)
451                         return ERROR_FLASH_BANK_NOT_PROBED;
452         }
453
454         if (offset % row_size) {
455                 /* We're starting at an unaligned offset so we'll write a partial row
456                  * comprising that offset and up to the end of that row. */
457                 nb = row_size - (offset % row_size);
458                 if (nb > count)
459                         nb = count;
460         } else if (count < row_size) {
461                 /* We're writing an aligned but partial row. */
462                 nb = count;
463         }
464
465         address = (offset / row_size) * row_size + bank->base;
466
467         if (nb > 0) {
468                 res = samd_write_row_partial(bank, address, buffer,
469                                 offset % row_size, nb);
470                 if (res != ERROR_OK)
471                         return res;
472
473                 /* We're done with the row contents */
474                 count -= nb;
475                 offset += nb;
476                 buffer += row_size;
477         }
478
479         /* There's at least one aligned row to write out. */
480         if (count >= row_size) {
481                 int nr = count / row_size + ((count % row_size) ? 1 : 0);
482                 unsigned int r = 0;
483
484                 for (unsigned int i = address / row_size;
485                                 (i < (address / row_size) + nr) && count > 0; i++) {
486                         address = (i * row_size) + bank->base;
487
488                         if (count >= row_size) {
489                                 res = samd_write_row(bank, address, buffer + (r * row_size));
490                                 /* Advance one row */
491                                 offset += row_size;
492                                 count -= row_size;
493                         } else {
494                                 res = samd_write_row_partial(bank, address,
495                                                 buffer + (r * row_size), 0, count);
496                                 /* We're done after this. */
497                                 offset += count;
498                                 count = 0;
499                         }
500
501                         r++;
502
503                         if (res != ERROR_OK)
504                                 return res;
505                 }
506         }
507
508         return ERROR_OK;
509 }
510
511 FLASH_BANK_COMMAND_HANDLER(samd_flash_bank_command)
512 {
513         struct samd_info *chip = samd_chips;
514
515         while (chip) {
516                 if (chip->target == bank->target)
517                         break;
518                 chip = chip->next;
519         }
520
521         if (!chip) {
522                 /* Create a new chip */
523                 chip = calloc(1, sizeof(*chip));
524                 if (!chip)
525                         return ERROR_FAIL;
526
527                 chip->target = bank->target;
528                 chip->probed = false;
529
530                 bank->driver_priv = chip;
531
532                 /* Insert it into the chips list (at head) */
533                 chip->next = samd_chips;
534                 samd_chips = chip;
535         }
536
537         if (bank->base != SAMD_FLASH) {
538                 LOG_ERROR("Address 0x%08" PRIx32 " invalid bank address (try 0x%08" PRIx32
539                                 "[at91samd series] )",
540                                 bank->base, SAMD_FLASH);
541                 return ERROR_FAIL;
542         }
543
544         return ERROR_OK;
545 }
546
547 COMMAND_HANDLER(samd_handle_info_command)
548 {
549         return ERROR_OK;
550 }
551
552 static const struct command_registration at91samd_exec_command_handlers[] = {
553         {
554                 .name = "info",
555                 .handler = samd_handle_info_command,
556                 .mode = COMMAND_EXEC,
557                 .help = "Print information about the current at91samd chip"
558                         "and its flash configuration.",
559         },
560         COMMAND_REGISTRATION_DONE
561 };
562
563 static const struct command_registration at91samd_command_handlers[] = {
564         {
565                 .name = "at91samd",
566                 .mode = COMMAND_ANY,
567                 .help = "at91samd flash command group",
568                 .usage = "",
569                 .chain = at91samd_exec_command_handlers,
570         },
571         COMMAND_REGISTRATION_DONE
572 };
573
574 struct flash_driver at91samd_flash = {
575         .name = "at91samd",
576         .commands = at91samd_command_handlers,
577         .flash_bank_command = samd_flash_bank_command,
578         .erase = samd_erase,
579         .protect = samd_protect,
580         .write = samd_write,
581         .read = default_flash_read,
582         .probe = samd_probe,
583         .auto_probe = samd_probe,
584         .erase_check = default_flash_blank_check,
585         .protect_check = samd_protect_check,
586 };