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