update files to correct FSF address
[openocd.git] / src / flash / nor / at91sam4.c
blob1ba39109efcd7cac3a10677ad95fa8d8aaf3bd7a
1 /***************************************************************************
2 * Copyright (C) 2009 by Duane Ellis *
3 * openocd@duaneellis.com *
4 * *
5 * Copyright (C) 2010 by Olaf Lüke (at91sam3s* support) *
6 * olaf@uni-paderborn.de *
7 * *
8 * Copyright (C) 2011 by Olivier Schonken, Jim Norris *
9 * (at91sam3x* & at91sam4 support)* *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS for A PARTICULAR PURPOSE. See the *
19 * GNU General public License for more details. *
20 * *
21 * You should have received a copy of the GNU General public License *
22 * along with this program; if not, write to the *
23 * Free Software Foundation, Inc., *
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
25 ****************************************************************************/
27 /* Some of the the lower level code was based on code supplied by
28 * ATMEL under this copyright. */
30 /* BEGIN ATMEL COPYRIGHT */
31 /* ----------------------------------------------------------------------------
32 * ATMEL Microcontroller Software Support
33 * ----------------------------------------------------------------------------
34 * Copyright (c) 2009, Atmel Corporation
36 * All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions are met:
41 * - Redistributions of source code must retain the above copyright notice,
42 * this list of conditions and the disclaimer below.
44 * Atmel's name may not be used to endorse or promote products derived from
45 * this software without specific prior written permission.
47 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
48 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
49 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
50 * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
51 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
52 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
53 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
54 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
55 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
56 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
57 * ----------------------------------------------------------------------------
59 /* END ATMEL COPYRIGHT */
61 #ifdef HAVE_CONFIG_H
62 #include "config.h"
63 #endif
65 #include "imp.h"
66 #include <helper/time_support.h>
68 #define REG_NAME_WIDTH (12)
70 /* at91sam4s series (has always one flash bank)*/
71 #define FLASH_BANK_BASE_S 0x00400000
73 /* at91sam4sd series (two one flash banks), first bank address */
74 #define FLASH_BANK0_BASE_SD FLASH_BANK_BASE_S
75 /* at91sam4sd16x, second bank address */
76 #define FLASH_BANK1_BASE_1024K_SD (FLASH_BANK0_BASE_SD+(1024*1024/2))
77 /* at91sam4sd32x, second bank address */
78 #define FLASH_BANK1_BASE_2048K_SD (FLASH_BANK0_BASE_SD+(2048*1024/2))
80 #define AT91C_EFC_FCMD_GETD (0x0) /* (EFC) Get Flash Descriptor */
81 #define AT91C_EFC_FCMD_WP (0x1) /* (EFC) Write Page */
82 #define AT91C_EFC_FCMD_WPL (0x2) /* (EFC) Write Page and Lock */
83 #define AT91C_EFC_FCMD_EWP (0x3) /* (EFC) Erase Page and Write Page */
84 #define AT91C_EFC_FCMD_EWPL (0x4) /* (EFC) Erase Page and Write Page then Lock */
85 #define AT91C_EFC_FCMD_EA (0x5) /* (EFC) Erase All */
86 /* cmd6 is not present in the at91sam4u4/2/1 data sheet table 19-2 */
87 /* #define AT91C_EFC_FCMD_EPL (0x6) // (EFC) Erase plane? */
88 #define AT91C_EFC_FCMD_EPA (0x7) /* (EFC) Erase pages */
89 #define AT91C_EFC_FCMD_SLB (0x8) /* (EFC) Set Lock Bit */
90 #define AT91C_EFC_FCMD_CLB (0x9) /* (EFC) Clear Lock Bit */
91 #define AT91C_EFC_FCMD_GLB (0xA) /* (EFC) Get Lock Bit */
92 #define AT91C_EFC_FCMD_SFB (0xB) /* (EFC) Set Fuse Bit */
93 #define AT91C_EFC_FCMD_CFB (0xC) /* (EFC) Clear Fuse Bit */
94 #define AT91C_EFC_FCMD_GFB (0xD) /* (EFC) Get Fuse Bit */
95 #define AT91C_EFC_FCMD_STUI (0xE) /* (EFC) Start Read Unique ID */
96 #define AT91C_EFC_FCMD_SPUI (0xF) /* (EFC) Stop Read Unique ID */
98 #define offset_EFC_FMR 0
99 #define offset_EFC_FCR 4
100 #define offset_EFC_FSR 8
101 #define offset_EFC_FRR 12
103 extern struct flash_driver at91sam4_flash;
105 static float _tomhz(uint32_t freq_hz)
107 float f;
109 f = ((float)(freq_hz)) / 1000000.0;
110 return f;
113 /* How the chip is configured. */
114 struct sam4_cfg {
115 uint32_t unique_id[4];
117 uint32_t slow_freq;
118 uint32_t rc_freq;
119 uint32_t mainosc_freq;
120 uint32_t plla_freq;
121 uint32_t mclk_freq;
122 uint32_t cpu_freq;
123 uint32_t fclk_freq;
124 uint32_t pclk0_freq;
125 uint32_t pclk1_freq;
126 uint32_t pclk2_freq;
129 #define SAM4_CHIPID_CIDR (0x400E0740)
130 uint32_t CHIPID_CIDR;
131 #define SAM4_CHIPID_EXID (0x400E0744)
132 uint32_t CHIPID_EXID;
134 #define SAM4_PMC_BASE (0x400E0400)
135 #define SAM4_PMC_SCSR (SAM4_PMC_BASE + 0x0008)
136 uint32_t PMC_SCSR;
137 #define SAM4_PMC_PCSR (SAM4_PMC_BASE + 0x0018)
138 uint32_t PMC_PCSR;
139 #define SAM4_CKGR_UCKR (SAM4_PMC_BASE + 0x001c)
140 uint32_t CKGR_UCKR;
141 #define SAM4_CKGR_MOR (SAM4_PMC_BASE + 0x0020)
142 uint32_t CKGR_MOR;
143 #define SAM4_CKGR_MCFR (SAM4_PMC_BASE + 0x0024)
144 uint32_t CKGR_MCFR;
145 #define SAM4_CKGR_PLLAR (SAM4_PMC_BASE + 0x0028)
146 uint32_t CKGR_PLLAR;
147 #define SAM4_PMC_MCKR (SAM4_PMC_BASE + 0x0030)
148 uint32_t PMC_MCKR;
149 #define SAM4_PMC_PCK0 (SAM4_PMC_BASE + 0x0040)
150 uint32_t PMC_PCK0;
151 #define SAM4_PMC_PCK1 (SAM4_PMC_BASE + 0x0044)
152 uint32_t PMC_PCK1;
153 #define SAM4_PMC_PCK2 (SAM4_PMC_BASE + 0x0048)
154 uint32_t PMC_PCK2;
155 #define SAM4_PMC_SR (SAM4_PMC_BASE + 0x0068)
156 uint32_t PMC_SR;
157 #define SAM4_PMC_IMR (SAM4_PMC_BASE + 0x006c)
158 uint32_t PMC_IMR;
159 #define SAM4_PMC_FSMR (SAM4_PMC_BASE + 0x0070)
160 uint32_t PMC_FSMR;
161 #define SAM4_PMC_FSPR (SAM4_PMC_BASE + 0x0074)
162 uint32_t PMC_FSPR;
165 struct sam4_bank_private {
166 int probed;
167 /* DANGER: THERE ARE DRAGONS HERE.. */
168 /* NOTE: If you add more 'ghost' pointers */
169 /* be aware that you must *manually* update */
170 /* these pointers in the function sam4_GetDetails() */
171 /* See the comment "Here there be dragons" */
173 /* so we can find the chip we belong to */
174 struct sam4_chip *pChip;
175 /* so we can find the original bank pointer */
176 struct flash_bank *pBank;
177 unsigned bank_number;
178 uint32_t controller_address;
179 uint32_t base_address;
180 uint32_t flash_wait_states;
181 bool present;
182 unsigned size_bytes;
183 unsigned nsectors;
184 unsigned sector_size;
185 unsigned page_size;
188 struct sam4_chip_details {
189 /* THERE ARE DRAGONS HERE.. */
190 /* note: If you add pointers here */
191 /* be careful about them as they */
192 /* may need to be updated inside */
193 /* the function: "sam4_GetDetails() */
194 /* which copy/overwrites the */
195 /* 'runtime' copy of this structure */
196 uint32_t chipid_cidr;
197 const char *name;
199 unsigned n_gpnvms;
200 #define SAM4_N_NVM_BITS 3
201 unsigned gpnvm[SAM4_N_NVM_BITS];
202 unsigned total_flash_size;
203 unsigned total_sram_size;
204 unsigned n_banks;
205 #define SAM4_MAX_FLASH_BANKS 2
206 /* these are "initialized" from the global const data */
207 struct sam4_bank_private bank[SAM4_MAX_FLASH_BANKS];
210 struct sam4_chip {
211 struct sam4_chip *next;
212 int probed;
214 /* this is "initialized" from the global const structure */
215 struct sam4_chip_details details;
216 struct target *target;
217 struct sam4_cfg cfg;
221 struct sam4_reg_list {
222 uint32_t address; size_t struct_offset; const char *name;
223 void (*explain_func)(struct sam4_chip *pInfo);
226 static struct sam4_chip *all_sam4_chips;
228 static struct sam4_chip *get_current_sam4(struct command_context *cmd_ctx)
230 struct target *t;
231 static struct sam4_chip *p;
233 t = get_current_target(cmd_ctx);
234 if (!t) {
235 command_print(cmd_ctx, "No current target?");
236 return NULL;
239 p = all_sam4_chips;
240 if (!p) {
241 /* this should not happen */
242 /* the command is not registered until the chip is created? */
243 command_print(cmd_ctx, "No SAM4 chips exist?");
244 return NULL;
247 while (p) {
248 if (p->target == t)
249 return p;
250 p = p->next;
252 command_print(cmd_ctx, "Cannot find SAM4 chip?");
253 return NULL;
256 /*The actual sector size of the SAM4S flash memory is 65536 bytes. 16 sectors for a 1024KB device*/
257 /*The lockregions are 8KB per lock region, with a 1024KB device having 128 lock regions. */
258 /*For the best results, nsectors are thus set to the amount of lock regions, and the sector_size*/
259 /*set to the lock region size. Page erases are used to erase 8KB sections when programming*/
261 /* these are used to *initialize* the "pChip->details" structure. */
262 static const struct sam4_chip_details all_sam4_details[] = {
263 /* Start at91sam4s* series */
264 /*atsam4s16c - LQFP100/BGA100*/
266 .chipid_cidr = 0x28AC0CE0,
267 .name = "at91sam4s16c",
268 .total_flash_size = 1024 * 1024,
269 .total_sram_size = 128 * 1024,
270 .n_gpnvms = 2,
271 .n_banks = 1,
273 /* .bank[0] = {*/
275 .probed = 0,
276 .pChip = NULL,
277 .pBank = NULL,
278 .bank_number = 0,
279 .base_address = FLASH_BANK_BASE_S,
280 .controller_address = 0x400e0a00,
281 .flash_wait_states = 6, /* workaround silicon bug */
282 .present = 1,
283 .size_bytes = 1024 * 1024,
284 .nsectors = 128,
285 .sector_size = 8192,
286 .page_size = 512,
288 /* .bank[1] = {*/
290 .present = 0,
291 .probed = 0,
292 .bank_number = 1,
297 /*atsam4s16b - LQFP64/QFN64*/
299 .chipid_cidr = 0x289C0CE0,
300 .name = "at91sam4s16b",
301 .total_flash_size = 1024 * 1024,
302 .total_sram_size = 128 * 1024,
303 .n_gpnvms = 2,
304 .n_banks = 1,
306 /* .bank[0] = {*/
308 .probed = 0,
309 .pChip = NULL,
310 .pBank = NULL,
311 .bank_number = 0,
312 .base_address = FLASH_BANK_BASE_S,
313 .controller_address = 0x400e0a00,
314 .flash_wait_states = 6, /* workaround silicon bug */
315 .present = 1,
316 .size_bytes = 1024 * 1024,
317 .nsectors = 128,
318 .sector_size = 8192,
319 .page_size = 512,
321 /* .bank[1] = {*/
323 .present = 0,
324 .probed = 0,
325 .bank_number = 1,
330 /*atsam4s16a - LQFP48/QFN48*/
332 .chipid_cidr = 0x288C0CE0,
333 .name = "at91sam4s16a",
334 .total_flash_size = 1024 * 1024,
335 .total_sram_size = 128 * 1024,
336 .n_gpnvms = 2,
337 .n_banks = 1,
339 /* .bank[0] = {*/
341 .probed = 0,
342 .pChip = NULL,
343 .pBank = NULL,
344 .bank_number = 0,
345 .base_address = FLASH_BANK_BASE_S,
346 .controller_address = 0x400e0a00,
347 .flash_wait_states = 6, /* workaround silicon bug */
348 .present = 1,
349 .size_bytes = 1024 * 1024,
350 .nsectors = 128,
351 .sector_size = 8192,
352 .page_size = 512,
354 /* .bank[1] = {*/
356 .present = 0,
357 .probed = 0,
358 .bank_number = 1,
363 /*atsam4s8c - LQFP100/BGA100*/
365 .chipid_cidr = 0x28AC0AE0,
366 .name = "at91sam4s8c",
367 .total_flash_size = 512 * 1024,
368 .total_sram_size = 128 * 1024,
369 .n_gpnvms = 2,
370 .n_banks = 1,
372 /* .bank[0] = {*/
374 .probed = 0,
375 .pChip = NULL,
376 .pBank = NULL,
377 .bank_number = 0,
378 .base_address = FLASH_BANK_BASE_S,
379 .controller_address = 0x400e0a00,
380 .flash_wait_states = 6, /* workaround silicon bug */
381 .present = 1,
382 .size_bytes = 512 * 1024,
383 .nsectors = 64,
384 .sector_size = 8192,
385 .page_size = 512,
387 /* .bank[1] = {*/
389 .present = 0,
390 .probed = 0,
391 .bank_number = 1,
396 /*atsam4s8b - LQFP64/BGA64*/
398 .chipid_cidr = 0x289C0AE0,
399 .name = "at91sam4s8b",
400 .total_flash_size = 512 * 1024,
401 .total_sram_size = 128 * 1024,
402 .n_gpnvms = 2,
403 .n_banks = 1,
405 /* .bank[0] = {*/
407 .probed = 0,
408 .pChip = NULL,
409 .pBank = NULL,
410 .bank_number = 0,
411 .base_address = FLASH_BANK_BASE_S,
412 .controller_address = 0x400e0a00,
413 .flash_wait_states = 6, /* workaround silicon bug */
414 .present = 1,
415 .size_bytes = 512 * 1024,
416 .nsectors = 64,
417 .sector_size = 8192,
418 .page_size = 512,
420 /* .bank[1] = {*/
422 .present = 0,
423 .probed = 0,
424 .bank_number = 1,
429 /*atsam4s8a - LQFP48/BGA48*/
431 .chipid_cidr = 0x288C0AE0,
432 .name = "at91sam4s8a",
433 .total_flash_size = 512 * 1024,
434 .total_sram_size = 128 * 1024,
435 .n_gpnvms = 2,
436 .n_banks = 1,
438 /* .bank[0] = {*/
440 .probed = 0,
441 .pChip = NULL,
442 .pBank = NULL,
443 .bank_number = 0,
444 .base_address = FLASH_BANK_BASE_S,
445 .controller_address = 0x400e0a00,
446 .flash_wait_states = 6, /* workaround silicon bug */
447 .present = 1,
448 .size_bytes = 512 * 1024,
449 .nsectors = 64,
450 .sector_size = 8192,
451 .page_size = 512,
453 /* .bank[1] = {*/
455 .present = 0,
456 .probed = 0,
457 .bank_number = 1,
463 /*at91sam4sd32c*/
465 .chipid_cidr = 0x29a70ee0,
466 .name = "at91sam4sd32c",
467 .total_flash_size = 2048 * 1024,
468 .total_sram_size = 160 * 1024,
469 .n_gpnvms = 3,
470 .n_banks = 2,
472 /* .bank[0] = { */
475 .probed = 0,
476 .pChip = NULL,
477 .pBank = NULL,
478 .bank_number = 0,
479 .base_address = FLASH_BANK0_BASE_SD,
480 .controller_address = 0x400e0a00,
481 .flash_wait_states = 6, /* workaround silicon bug */
482 .present = 1,
483 .size_bytes = 1024 * 1024,
484 .nsectors = 128,
485 .sector_size = 8192,
486 .page_size = 512,
489 /* .bank[1] = { */
491 .probed = 0,
492 .pChip = NULL,
493 .pBank = NULL,
494 .bank_number = 1,
495 .base_address = FLASH_BANK1_BASE_2048K_SD,
496 .controller_address = 0x400e0c00,
497 .flash_wait_states = 6, /* workaround silicon bug */
498 .present = 1,
499 .size_bytes = 1024 * 1024,
500 .nsectors = 128,
501 .sector_size = 8192,
502 .page_size = 512,
507 /* terminate */
509 .chipid_cidr = 0,
510 .name = NULL,
514 /* Globals above */
515 /***********************************************************************
516 **********************************************************************
517 **********************************************************************
518 **********************************************************************
519 **********************************************************************
520 **********************************************************************/
521 /* *ATMEL* style code - from the SAM4 driver code */
524 * Get the current status of the EEFC and
525 * the value of some status bits (LOCKE, PROGE).
526 * @param pPrivate - info about the bank
527 * @param v - result goes here
529 static int EFC_GetStatus(struct sam4_bank_private *pPrivate, uint32_t *v)
531 int r;
532 r = target_read_u32(pPrivate->pChip->target,
533 pPrivate->controller_address + offset_EFC_FSR,
535 LOG_DEBUG("Status: 0x%08x (lockerror: %d, cmderror: %d, ready: %d)",
536 (unsigned int)(*v),
537 ((unsigned int)((*v >> 2) & 1)),
538 ((unsigned int)((*v >> 1) & 1)),
539 ((unsigned int)((*v >> 0) & 1)));
541 return r;
545 * Get the result of the last executed command.
546 * @param pPrivate - info about the bank
547 * @param v - result goes here
549 static int EFC_GetResult(struct sam4_bank_private *pPrivate, uint32_t *v)
551 int r;
552 uint32_t rv;
553 r = target_read_u32(pPrivate->pChip->target,
554 pPrivate->controller_address + offset_EFC_FRR,
555 &rv);
556 if (v)
557 *v = rv;
558 LOG_DEBUG("Result: 0x%08x", ((unsigned int)(rv)));
559 return r;
562 static int EFC_StartCommand(struct sam4_bank_private *pPrivate,
563 unsigned command, unsigned argument)
565 uint32_t n, v;
566 int r;
567 int retry;
569 retry = 0;
570 do_retry:
572 /* Check command & argument */
573 switch (command) {
575 case AT91C_EFC_FCMD_WP:
576 case AT91C_EFC_FCMD_WPL:
577 case AT91C_EFC_FCMD_EWP:
578 case AT91C_EFC_FCMD_EWPL:
579 /* case AT91C_EFC_FCMD_EPL: */
580 case AT91C_EFC_FCMD_EPA:
581 case AT91C_EFC_FCMD_SLB:
582 case AT91C_EFC_FCMD_CLB:
583 n = (pPrivate->size_bytes / pPrivate->page_size);
584 if (argument >= n)
585 LOG_ERROR("*BUG*: Embedded flash has only %u pages", (unsigned)(n));
586 break;
588 case AT91C_EFC_FCMD_SFB:
589 case AT91C_EFC_FCMD_CFB:
590 if (argument >= pPrivate->pChip->details.n_gpnvms) {
591 LOG_ERROR("*BUG*: Embedded flash has only %d GPNVMs",
592 pPrivate->pChip->details.n_gpnvms);
594 break;
596 case AT91C_EFC_FCMD_GETD:
597 case AT91C_EFC_FCMD_EA:
598 case AT91C_EFC_FCMD_GLB:
599 case AT91C_EFC_FCMD_GFB:
600 case AT91C_EFC_FCMD_STUI:
601 case AT91C_EFC_FCMD_SPUI:
602 if (argument != 0)
603 LOG_ERROR("Argument is meaningless for cmd: %d", command);
604 break;
605 default:
606 LOG_ERROR("Unknown command %d", command);
607 break;
610 if (command == AT91C_EFC_FCMD_SPUI) {
611 /* this is a very special situation. */
612 /* Situation (1) - error/retry - see below */
613 /* And we are being called recursively */
614 /* Situation (2) - normal, finished reading unique id */
615 } else {
616 /* it should be "ready" */
617 EFC_GetStatus(pPrivate, &v);
618 if (v & 1) {
619 /* then it is ready */
620 /* we go on */
621 } else {
622 if (retry) {
623 /* we have done this before */
624 /* the controller is not responding. */
625 LOG_ERROR("flash controller(%d) is not ready! Error",
626 pPrivate->bank_number);
627 return ERROR_FAIL;
628 } else {
629 retry++;
630 LOG_ERROR("Flash controller(%d) is not ready, attempting reset",
631 pPrivate->bank_number);
632 /* we do that by issuing the *STOP* command */
633 EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0);
634 /* above is recursive, and further recursion is blocked by */
635 /* if (command == AT91C_EFC_FCMD_SPUI) above */
636 goto do_retry;
641 v = (0x5A << 24) | (argument << 8) | command;
642 LOG_DEBUG("Command: 0x%08x", ((unsigned int)(v)));
643 r = target_write_u32(pPrivate->pBank->target,
644 pPrivate->controller_address + offset_EFC_FCR, v);
645 if (r != ERROR_OK)
646 LOG_DEBUG("Error Write failed");
647 return r;
651 * Performs the given command and wait until its completion (or an error).
652 * @param pPrivate - info about the bank
653 * @param command - Command to perform.
654 * @param argument - Optional command argument.
655 * @param status - put command status bits here
657 static int EFC_PerformCommand(struct sam4_bank_private *pPrivate,
658 unsigned command,
659 unsigned argument,
660 uint32_t *status)
663 int r;
664 uint32_t v;
665 long long ms_now, ms_end;
667 /* default */
668 if (status)
669 *status = 0;
671 r = EFC_StartCommand(pPrivate, command, argument);
672 if (r != ERROR_OK)
673 return r;
675 ms_end = 10000 + timeval_ms();
677 do {
678 r = EFC_GetStatus(pPrivate, &v);
679 if (r != ERROR_OK)
680 return r;
681 ms_now = timeval_ms();
682 if (ms_now > ms_end) {
683 /* error */
684 LOG_ERROR("Command timeout");
685 return ERROR_FAIL;
687 } while ((v & 1) == 0);
689 /* error bits.. */
690 if (status)
691 *status = (v & 0x6);
692 return ERROR_OK;
697 * Read the unique ID.
698 * @param pPrivate - info about the bank
699 * The unique ID is stored in the 'pPrivate' structure.
701 static int FLASHD_ReadUniqueID(struct sam4_bank_private *pPrivate)
703 int r;
704 uint32_t v;
705 int x;
706 /* assume 0 */
707 pPrivate->pChip->cfg.unique_id[0] = 0;
708 pPrivate->pChip->cfg.unique_id[1] = 0;
709 pPrivate->pChip->cfg.unique_id[2] = 0;
710 pPrivate->pChip->cfg.unique_id[3] = 0;
712 LOG_DEBUG("Begin");
713 r = EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_STUI, 0);
714 if (r < 0)
715 return r;
717 for (x = 0; x < 4; x++) {
718 r = target_read_u32(pPrivate->pChip->target,
719 pPrivate->pBank->base + (x * 4),
720 &v);
721 if (r < 0)
722 return r;
723 pPrivate->pChip->cfg.unique_id[x] = v;
726 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0, NULL);
727 LOG_DEBUG("End: R=%d, id = 0x%08x, 0x%08x, 0x%08x, 0x%08x",
729 (unsigned int)(pPrivate->pChip->cfg.unique_id[0]),
730 (unsigned int)(pPrivate->pChip->cfg.unique_id[1]),
731 (unsigned int)(pPrivate->pChip->cfg.unique_id[2]),
732 (unsigned int)(pPrivate->pChip->cfg.unique_id[3]));
733 return r;
738 * Erases the entire flash.
739 * @param pPrivate - the info about the bank.
741 static int FLASHD_EraseEntireBank(struct sam4_bank_private *pPrivate)
743 LOG_DEBUG("Here");
744 return EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_EA, 0, NULL);
748 * Erases the entire flash.
749 * @param pPrivate - the info about the bank.
751 static int FLASHD_ErasePages(struct sam4_bank_private *pPrivate,
752 int firstPage,
753 int numPages,
754 uint32_t *status)
756 LOG_DEBUG("Here");
757 uint8_t erasePages;
758 switch (numPages) {
759 case 4:
760 erasePages = 0x00;
761 break;
762 case 8:
763 erasePages = 0x01;
764 break;
765 case 16:
766 erasePages = 0x02;
767 break;
768 case 32:
769 erasePages = 0x03;
770 break;
771 default:
772 erasePages = 0x00;
773 break;
776 /* AT91C_EFC_FCMD_EPA
777 * According to the datasheet FARG[15:2] defines the page from which
778 * the erase will start.This page must be modulo 4, 8, 16 or 32
779 * according to the number of pages to erase. FARG[1:0] defines the
780 * number of pages to be erased. Previously (firstpage << 2) was used
781 * to conform to this, seems it should not be shifted...
783 return EFC_PerformCommand(pPrivate,
784 /* send Erase Page */
785 AT91C_EFC_FCMD_EPA,
786 (firstPage) | erasePages,
787 status);
791 * Gets current GPNVM state.
792 * @param pPrivate - info about the bank.
793 * @param gpnvm - GPNVM bit index.
794 * @param puthere - result stored here.
796 /* ------------------------------------------------------------------------------ */
797 static int FLASHD_GetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm, unsigned *puthere)
799 uint32_t v;
800 int r;
802 LOG_DEBUG("Here");
803 if (pPrivate->bank_number != 0) {
804 LOG_ERROR("GPNVM only works with Bank0");
805 return ERROR_FAIL;
808 if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
809 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
810 gpnvm, pPrivate->pChip->details.n_gpnvms);
811 return ERROR_FAIL;
814 /* Get GPNVMs status */
815 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GFB, 0, NULL);
816 if (r != ERROR_OK) {
817 LOG_ERROR("Failed");
818 return r;
821 r = EFC_GetResult(pPrivate, &v);
823 if (puthere) {
824 /* Check if GPNVM is set */
825 /* get the bit and make it a 0/1 */
826 *puthere = (v >> gpnvm) & 1;
829 return r;
833 * Clears the selected GPNVM bit.
834 * @param pPrivate info about the bank
835 * @param gpnvm GPNVM index.
836 * @returns 0 if successful; otherwise returns an error code.
838 static int FLASHD_ClrGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
840 int r;
841 unsigned v;
843 LOG_DEBUG("Here");
844 if (pPrivate->bank_number != 0) {
845 LOG_ERROR("GPNVM only works with Bank0");
846 return ERROR_FAIL;
849 if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
850 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
851 gpnvm, pPrivate->pChip->details.n_gpnvms);
852 return ERROR_FAIL;
855 r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
856 if (r != ERROR_OK) {
857 LOG_DEBUG("Failed: %d", r);
858 return r;
860 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CFB, gpnvm, NULL);
861 LOG_DEBUG("End: %d", r);
862 return r;
866 * Sets the selected GPNVM bit.
867 * @param pPrivate info about the bank
868 * @param gpnvm GPNVM index.
870 static int FLASHD_SetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
872 int r;
873 unsigned v;
875 if (pPrivate->bank_number != 0) {
876 LOG_ERROR("GPNVM only works with Bank0");
877 return ERROR_FAIL;
880 if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
881 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
882 gpnvm, pPrivate->pChip->details.n_gpnvms);
883 return ERROR_FAIL;
886 r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
887 if (r != ERROR_OK)
888 return r;
889 if (v) {
890 /* already set */
891 r = ERROR_OK;
892 } else {
893 /* set it */
894 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SFB, gpnvm, NULL);
896 return r;
900 * Returns a bit field (at most 64) of locked regions within a page.
901 * @param pPrivate info about the bank
902 * @param v where to store locked bits
904 static int FLASHD_GetLockBits(struct sam4_bank_private *pPrivate, uint32_t *v)
906 int r;
907 LOG_DEBUG("Here");
908 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GLB, 0, NULL);
909 if (r == ERROR_OK) {
910 EFC_GetResult(pPrivate, v);
911 EFC_GetResult(pPrivate, v);
912 EFC_GetResult(pPrivate, v);
913 r = EFC_GetResult(pPrivate, v);
915 LOG_DEBUG("End: %d", r);
916 return r;
920 * Unlocks all the regions in the given address range.
921 * @param pPrivate info about the bank
922 * @param start_sector first sector to unlock
923 * @param end_sector last (inclusive) to unlock
926 static int FLASHD_Unlock(struct sam4_bank_private *pPrivate,
927 unsigned start_sector,
928 unsigned end_sector)
930 int r;
931 uint32_t status;
932 uint32_t pg;
933 uint32_t pages_per_sector;
935 pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
937 /* Unlock all pages */
938 while (start_sector <= end_sector) {
939 pg = start_sector * pages_per_sector;
941 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CLB, pg, &status);
942 if (r != ERROR_OK)
943 return r;
944 start_sector++;
947 return ERROR_OK;
951 * Locks regions
952 * @param pPrivate - info about the bank
953 * @param start_sector - first sector to lock
954 * @param end_sector - last sector (inclusive) to lock
956 static int FLASHD_Lock(struct sam4_bank_private *pPrivate,
957 unsigned start_sector,
958 unsigned end_sector)
960 uint32_t status;
961 uint32_t pg;
962 uint32_t pages_per_sector;
963 int r;
965 pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
967 /* Lock all pages */
968 while (start_sector <= end_sector) {
969 pg = start_sector * pages_per_sector;
971 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SLB, pg, &status);
972 if (r != ERROR_OK)
973 return r;
974 start_sector++;
976 return ERROR_OK;
979 /****** END SAM4 CODE ********/
981 /* begin helpful debug code */
982 /* print the fieldname, the field value, in dec & hex, and return field value */
983 static uint32_t sam4_reg_fieldname(struct sam4_chip *pChip,
984 const char *regname,
985 uint32_t value,
986 unsigned shift,
987 unsigned width)
989 uint32_t v;
990 int hwidth, dwidth;
993 /* extract the field */
994 v = value >> shift;
995 v = v & ((1 << width)-1);
996 if (width <= 16) {
997 hwidth = 4;
998 dwidth = 5;
999 } else {
1000 hwidth = 8;
1001 dwidth = 12;
1004 /* show the basics */
1005 LOG_USER_N("\t%*s: %*d [0x%0*x] ",
1006 REG_NAME_WIDTH, regname,
1007 dwidth, v,
1008 hwidth, v);
1009 return v;
1012 static const char _unknown[] = "unknown";
1013 static const char *const eproc_names[] = {
1014 _unknown, /* 0 */
1015 "arm946es", /* 1 */
1016 "arm7tdmi", /* 2 */
1017 "cortex-m3", /* 3 */
1018 "arm920t", /* 4 */
1019 "arm926ejs", /* 5 */
1020 "cortex-a5", /* 6 */
1021 "cortex-m4", /* 7 */
1022 _unknown, /* 8 */
1023 _unknown, /* 9 */
1024 _unknown, /* 10 */
1025 _unknown, /* 11 */
1026 _unknown, /* 12 */
1027 _unknown, /* 13 */
1028 _unknown, /* 14 */
1029 _unknown, /* 15 */
1032 #define nvpsize2 nvpsize /* these two tables are identical */
1033 static const char *const nvpsize[] = {
1034 "none", /* 0 */
1035 "8K bytes", /* 1 */
1036 "16K bytes", /* 2 */
1037 "32K bytes", /* 3 */
1038 _unknown, /* 4 */
1039 "64K bytes", /* 5 */
1040 _unknown, /* 6 */
1041 "128K bytes", /* 7 */
1042 _unknown, /* 8 */
1043 "256K bytes", /* 9 */
1044 "512K bytes", /* 10 */
1045 _unknown, /* 11 */
1046 "1024K bytes", /* 12 */
1047 _unknown, /* 13 */
1048 "2048K bytes", /* 14 */
1049 _unknown, /* 15 */
1052 static const char *const sramsize[] = {
1053 "48K Bytes", /* 0 */
1054 "1K Bytes", /* 1 */
1055 "2K Bytes", /* 2 */
1056 "6K Bytes", /* 3 */
1057 "112K Bytes", /* 4 */
1058 "4K Bytes", /* 5 */
1059 "80K Bytes", /* 6 */
1060 "160K Bytes", /* 7 */
1061 "8K Bytes", /* 8 */
1062 "16K Bytes", /* 9 */
1063 "32K Bytes", /* 10 */
1064 "64K Bytes", /* 11 */
1065 "128K Bytes", /* 12 */
1066 "256K Bytes", /* 13 */
1067 "96K Bytes", /* 14 */
1068 "512K Bytes", /* 15 */
1072 static const struct archnames { unsigned value; const char *name; } archnames[] = {
1073 { 0x19, "AT91SAM9xx Series" },
1074 { 0x29, "AT91SAM9XExx Series" },
1075 { 0x34, "AT91x34 Series" },
1076 { 0x37, "CAP7 Series" },
1077 { 0x39, "CAP9 Series" },
1078 { 0x3B, "CAP11 Series" },
1079 { 0x40, "AT91x40 Series" },
1080 { 0x42, "AT91x42 Series" },
1081 { 0x55, "AT91x55 Series" },
1082 { 0x60, "AT91SAM7Axx Series" },
1083 { 0x61, "AT91SAM7AQxx Series" },
1084 { 0x63, "AT91x63 Series" },
1085 { 0x70, "AT91SAM7Sxx Series" },
1086 { 0x71, "AT91SAM7XCxx Series" },
1087 { 0x72, "AT91SAM7SExx Series" },
1088 { 0x73, "AT91SAM7Lxx Series" },
1089 { 0x75, "AT91SAM7Xxx Series" },
1090 { 0x76, "AT91SAM7SLxx Series" },
1091 { 0x80, "ATSAM3UxC Series (100-pin version)" },
1092 { 0x81, "ATSAM3UxE Series (144-pin version)" },
1093 { 0x83, "ATSAM3A/SAM4A xC Series (100-pin version)"},
1094 { 0x84, "ATSAM3X/SAM4X xC Series (100-pin version)"},
1095 { 0x85, "ATSAM3X/SAM4X xE Series (144-pin version)"},
1096 { 0x86, "ATSAM3X/SAM4X xG Series (208/217-pin version)" },
1097 { 0x88, "ATSAM3S/SAM4S xA Series (48-pin version)" },
1098 { 0x89, "ATSAM3S/SAM4S xB Series (64-pin version)" },
1099 { 0x8A, "ATSAM3S/SAM4S xC Series (100-pin version)"},
1100 { 0x92, "AT91x92 Series" },
1101 { 0x93, "ATSAM3NxA Series (48-pin version)" },
1102 { 0x94, "ATSAM3NxB Series (64-pin version)" },
1103 { 0x95, "ATSAM3NxC Series (100-pin version)" },
1104 { 0x98, "ATSAM3SDxA Series (48-pin version)" },
1105 { 0x99, "ATSAM3SDxB Series (64-pin version)" },
1106 { 0x9A, "ATSAM3SDxC Series (100-pin version)" },
1107 { 0xA5, "ATSAM5A" },
1108 { 0xF0, "AT75Cxx Series" },
1109 { -1, NULL },
1112 static const char *const nvptype[] = {
1113 "rom", /* 0 */
1114 "romless or onchip flash", /* 1 */
1115 "embedded flash memory",/* 2 */
1116 "rom(nvpsiz) + embedded flash (nvpsiz2)", /* 3 */
1117 "sram emulating flash", /* 4 */
1118 _unknown, /* 5 */
1119 _unknown, /* 6 */
1120 _unknown, /* 7 */
1123 static const char *_yes_or_no(uint32_t v)
1125 if (v)
1126 return "YES";
1127 else
1128 return "NO";
1131 static const char *const _rc_freq[] = {
1132 "4 MHz", "8 MHz", "12 MHz", "reserved"
1135 static void sam4_explain_ckgr_mor(struct sam4_chip *pChip)
1137 uint32_t v;
1138 uint32_t rcen;
1140 v = sam4_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
1141 LOG_USER("(main xtal enabled: %s)", _yes_or_no(v));
1142 v = sam4_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
1143 LOG_USER("(main osc bypass: %s)", _yes_or_no(v));
1144 rcen = sam4_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 3, 1);
1145 LOG_USER("(onchip RC-OSC enabled: %s)", _yes_or_no(rcen));
1146 v = sam4_reg_fieldname(pChip, "MOSCRCF", pChip->cfg.CKGR_MOR, 4, 3);
1147 LOG_USER("(onchip RC-OSC freq: %s)", _rc_freq[v]);
1149 pChip->cfg.rc_freq = 0;
1150 if (rcen) {
1151 switch (v) {
1152 default:
1153 pChip->cfg.rc_freq = 0;
1154 break;
1155 case 0:
1156 pChip->cfg.rc_freq = 4 * 1000 * 1000;
1157 break;
1158 case 1:
1159 pChip->cfg.rc_freq = 8 * 1000 * 1000;
1160 break;
1161 case 2:
1162 pChip->cfg.rc_freq = 12 * 1000 * 1000;
1163 break;
1167 v = sam4_reg_fieldname(pChip, "MOSCXTST", pChip->cfg.CKGR_MOR, 8, 8);
1168 LOG_USER("(startup clks, time= %f uSecs)",
1169 ((float)(v * 1000000)) / ((float)(pChip->cfg.slow_freq)));
1170 v = sam4_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
1171 LOG_USER("(mainosc source: %s)",
1172 v ? "external xtal" : "internal RC");
1174 v = sam4_reg_fieldname(pChip, "CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
1175 LOG_USER("(clock failure enabled: %s)",
1176 _yes_or_no(v));
1179 static void sam4_explain_chipid_cidr(struct sam4_chip *pChip)
1181 int x;
1182 uint32_t v;
1183 const char *cp;
1185 sam4_reg_fieldname(pChip, "Version", pChip->cfg.CHIPID_CIDR, 0, 5);
1186 LOG_USER_N("\n");
1188 v = sam4_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
1189 LOG_USER("%s", eproc_names[v]);
1191 v = sam4_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
1192 LOG_USER("%s", nvpsize[v]);
1194 v = sam4_reg_fieldname(pChip, "NVPSIZE2", pChip->cfg.CHIPID_CIDR, 12, 4);
1195 LOG_USER("%s", nvpsize2[v]);
1197 v = sam4_reg_fieldname(pChip, "SRAMSIZE", pChip->cfg.CHIPID_CIDR, 16, 4);
1198 LOG_USER("%s", sramsize[v]);
1200 v = sam4_reg_fieldname(pChip, "ARCH", pChip->cfg.CHIPID_CIDR, 20, 8);
1201 cp = _unknown;
1202 for (x = 0; archnames[x].name; x++) {
1203 if (v == archnames[x].value) {
1204 cp = archnames[x].name;
1205 break;
1209 LOG_USER("%s", cp);
1211 v = sam4_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
1212 LOG_USER("%s", nvptype[v]);
1214 v = sam4_reg_fieldname(pChip, "EXTID", pChip->cfg.CHIPID_CIDR, 31, 1);
1215 LOG_USER("(exists: %s)", _yes_or_no(v));
1218 static void sam4_explain_ckgr_mcfr(struct sam4_chip *pChip)
1220 uint32_t v;
1222 v = sam4_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
1223 LOG_USER("(main ready: %s)", _yes_or_no(v));
1225 v = sam4_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
1227 v = (v * pChip->cfg.slow_freq) / 16;
1228 pChip->cfg.mainosc_freq = v;
1230 LOG_USER("(%3.03f Mhz (%d.%03dkhz slowclk)",
1231 _tomhz(v),
1232 pChip->cfg.slow_freq / 1000,
1233 pChip->cfg.slow_freq % 1000);
1236 static void sam4_explain_ckgr_plla(struct sam4_chip *pChip)
1238 uint32_t mula, diva;
1240 diva = sam4_reg_fieldname(pChip, "DIVA", pChip->cfg.CKGR_PLLAR, 0, 8);
1241 LOG_USER_N("\n");
1242 mula = sam4_reg_fieldname(pChip, "MULA", pChip->cfg.CKGR_PLLAR, 16, 11);
1243 LOG_USER_N("\n");
1244 pChip->cfg.plla_freq = 0;
1245 if (mula == 0)
1246 LOG_USER("\tPLLA Freq: (Disabled,mula = 0)");
1247 else if (diva == 0)
1248 LOG_USER("\tPLLA Freq: (Disabled,diva = 0)");
1249 else if (diva == 1) {
1250 pChip->cfg.plla_freq = (pChip->cfg.mainosc_freq * (mula + 1));
1251 LOG_USER("\tPLLA Freq: %3.03f MHz",
1252 _tomhz(pChip->cfg.plla_freq));
1256 static void sam4_explain_mckr(struct sam4_chip *pChip)
1258 uint32_t css, pres, fin = 0;
1259 int pdiv = 0;
1260 const char *cp = NULL;
1262 css = sam4_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
1263 switch (css & 3) {
1264 case 0:
1265 fin = pChip->cfg.slow_freq;
1266 cp = "slowclk";
1267 break;
1268 case 1:
1269 fin = pChip->cfg.mainosc_freq;
1270 cp = "mainosc";
1271 break;
1272 case 2:
1273 fin = pChip->cfg.plla_freq;
1274 cp = "plla";
1275 break;
1276 case 3:
1277 if (pChip->cfg.CKGR_UCKR & (1 << 16)) {
1278 fin = 480 * 1000 * 1000;
1279 cp = "upll";
1280 } else {
1281 fin = 0;
1282 cp = "upll (*ERROR* UPLL is disabled)";
1284 break;
1285 default:
1286 assert(0);
1287 break;
1290 LOG_USER("%s (%3.03f Mhz)",
1292 _tomhz(fin));
1293 pres = sam4_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
1294 switch (pres & 0x07) {
1295 case 0:
1296 pdiv = 1;
1297 cp = "selected clock";
1298 break;
1299 case 1:
1300 pdiv = 2;
1301 cp = "clock/2";
1302 break;
1303 case 2:
1304 pdiv = 4;
1305 cp = "clock/4";
1306 break;
1307 case 3:
1308 pdiv = 8;
1309 cp = "clock/8";
1310 break;
1311 case 4:
1312 pdiv = 16;
1313 cp = "clock/16";
1314 break;
1315 case 5:
1316 pdiv = 32;
1317 cp = "clock/32";
1318 break;
1319 case 6:
1320 pdiv = 64;
1321 cp = "clock/64";
1322 break;
1323 case 7:
1324 pdiv = 6;
1325 cp = "clock/6";
1326 break;
1327 default:
1328 assert(0);
1329 break;
1331 LOG_USER("(%s)", cp);
1332 fin = fin / pdiv;
1333 /* sam4 has a *SINGLE* clock - */
1334 /* other at91 series parts have divisors for these. */
1335 pChip->cfg.cpu_freq = fin;
1336 pChip->cfg.mclk_freq = fin;
1337 pChip->cfg.fclk_freq = fin;
1338 LOG_USER("\t\tResult CPU Freq: %3.03f",
1339 _tomhz(fin));
1342 #if 0
1343 static struct sam4_chip *target2sam4(struct target *pTarget)
1345 struct sam4_chip *pChip;
1347 if (pTarget == NULL)
1348 return NULL;
1350 pChip = all_sam4_chips;
1351 while (pChip) {
1352 if (pChip->target == pTarget)
1353 break; /* return below */
1354 else
1355 pChip = pChip->next;
1357 return pChip;
1359 #endif
1361 static uint32_t *sam4_get_reg_ptr(struct sam4_cfg *pCfg, const struct sam4_reg_list *pList)
1363 /* this function exists to help */
1364 /* keep funky offsetof() errors */
1365 /* and casting from causing bugs */
1367 /* By using prototypes - we can detect what would */
1368 /* be casting errors. */
1370 return (uint32_t *)(void *)(((char *)(pCfg)) + pList->struct_offset);
1374 #define SAM4_ENTRY(NAME, FUNC) { .address = SAM4_ ## NAME, .struct_offset = offsetof( \
1375 struct sam4_cfg, \
1376 NAME), # NAME, FUNC }
1377 static const struct sam4_reg_list sam4_all_regs[] = {
1378 SAM4_ENTRY(CKGR_MOR, sam4_explain_ckgr_mor),
1379 SAM4_ENTRY(CKGR_MCFR, sam4_explain_ckgr_mcfr),
1380 SAM4_ENTRY(CKGR_PLLAR, sam4_explain_ckgr_plla),
1381 SAM4_ENTRY(CKGR_UCKR, NULL),
1382 SAM4_ENTRY(PMC_FSMR, NULL),
1383 SAM4_ENTRY(PMC_FSPR, NULL),
1384 SAM4_ENTRY(PMC_IMR, NULL),
1385 SAM4_ENTRY(PMC_MCKR, sam4_explain_mckr),
1386 SAM4_ENTRY(PMC_PCK0, NULL),
1387 SAM4_ENTRY(PMC_PCK1, NULL),
1388 SAM4_ENTRY(PMC_PCK2, NULL),
1389 SAM4_ENTRY(PMC_PCSR, NULL),
1390 SAM4_ENTRY(PMC_SCSR, NULL),
1391 SAM4_ENTRY(PMC_SR, NULL),
1392 SAM4_ENTRY(CHIPID_CIDR, sam4_explain_chipid_cidr),
1393 SAM4_ENTRY(CHIPID_EXID, NULL),
1394 /* TERMINATE THE LIST */
1395 { .name = NULL }
1397 #undef SAM4_ENTRY
1399 static struct sam4_bank_private *get_sam4_bank_private(struct flash_bank *bank)
1401 return (struct sam4_bank_private *)(bank->driver_priv);
1405 * Given a pointer to where it goes in the structure,
1406 * determine the register name, address from the all registers table.
1408 static const struct sam4_reg_list *sam4_GetReg(struct sam4_chip *pChip, uint32_t *goes_here)
1410 const struct sam4_reg_list *pReg;
1412 pReg = &(sam4_all_regs[0]);
1413 while (pReg->name) {
1414 uint32_t *pPossible;
1416 /* calculate where this one go.. */
1417 /* it is "possibly" this register. */
1419 pPossible = ((uint32_t *)(void *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
1421 /* well? Is it this register */
1422 if (pPossible == goes_here) {
1423 /* Jump for joy! */
1424 return pReg;
1427 /* next... */
1428 pReg++;
1430 /* This is *TOTAL*PANIC* - we are totally screwed. */
1431 LOG_ERROR("INVALID SAM4 REGISTER");
1432 return NULL;
1435 static int sam4_ReadThisReg(struct sam4_chip *pChip, uint32_t *goes_here)
1437 const struct sam4_reg_list *pReg;
1438 int r;
1440 pReg = sam4_GetReg(pChip, goes_here);
1441 if (!pReg)
1442 return ERROR_FAIL;
1444 r = target_read_u32(pChip->target, pReg->address, goes_here);
1445 if (r != ERROR_OK) {
1446 LOG_ERROR("Cannot read SAM4 register: %s @ 0x%08x, Err: %d",
1447 pReg->name, (unsigned)(pReg->address), r);
1449 return r;
1452 static int sam4_ReadAllRegs(struct sam4_chip *pChip)
1454 int r;
1455 const struct sam4_reg_list *pReg;
1457 pReg = &(sam4_all_regs[0]);
1458 while (pReg->name) {
1459 r = sam4_ReadThisReg(pChip,
1460 sam4_get_reg_ptr(&(pChip->cfg), pReg));
1461 if (r != ERROR_OK) {
1462 LOG_ERROR("Cannot read SAM4 register: %s @ 0x%08x, Error: %d",
1463 pReg->name, ((unsigned)(pReg->address)), r);
1464 return r;
1466 pReg++;
1469 return ERROR_OK;
1472 static int sam4_GetInfo(struct sam4_chip *pChip)
1474 const struct sam4_reg_list *pReg;
1475 uint32_t regval;
1477 pReg = &(sam4_all_regs[0]);
1478 while (pReg->name) {
1479 /* display all regs */
1480 LOG_DEBUG("Start: %s", pReg->name);
1481 regval = *sam4_get_reg_ptr(&(pChip->cfg), pReg);
1482 LOG_USER("%*s: [0x%08x] -> 0x%08x",
1483 REG_NAME_WIDTH,
1484 pReg->name,
1485 pReg->address,
1486 regval);
1487 if (pReg->explain_func)
1488 (*(pReg->explain_func))(pChip);
1489 LOG_DEBUG("End: %s", pReg->name);
1490 pReg++;
1492 LOG_USER(" rc-osc: %3.03f MHz", _tomhz(pChip->cfg.rc_freq));
1493 LOG_USER(" mainosc: %3.03f MHz", _tomhz(pChip->cfg.mainosc_freq));
1494 LOG_USER(" plla: %3.03f MHz", _tomhz(pChip->cfg.plla_freq));
1495 LOG_USER(" cpu-freq: %3.03f MHz", _tomhz(pChip->cfg.cpu_freq));
1496 LOG_USER("mclk-freq: %3.03f MHz", _tomhz(pChip->cfg.mclk_freq));
1498 LOG_USER(" UniqueId: 0x%08x 0x%08x 0x%08x 0x%08x",
1499 pChip->cfg.unique_id[0],
1500 pChip->cfg.unique_id[1],
1501 pChip->cfg.unique_id[2],
1502 pChip->cfg.unique_id[3]);
1504 return ERROR_OK;
1507 static int sam4_protect_check(struct flash_bank *bank)
1509 int r;
1510 uint32_t v[4] = {0};
1511 unsigned x;
1512 struct sam4_bank_private *pPrivate;
1514 LOG_DEBUG("Begin");
1515 if (bank->target->state != TARGET_HALTED) {
1516 LOG_ERROR("Target not halted");
1517 return ERROR_TARGET_NOT_HALTED;
1520 pPrivate = get_sam4_bank_private(bank);
1521 if (!pPrivate) {
1522 LOG_ERROR("no private for this bank?");
1523 return ERROR_FAIL;
1525 if (!(pPrivate->probed))
1526 return ERROR_FLASH_BANK_NOT_PROBED;
1528 r = FLASHD_GetLockBits(pPrivate, v);
1529 if (r != ERROR_OK) {
1530 LOG_DEBUG("Failed: %d", r);
1531 return r;
1534 for (x = 0; x < pPrivate->nsectors; x++)
1535 bank->sectors[x].is_protected = (!!(v[x >> 5] & (1 << (x % 32))));
1536 LOG_DEBUG("Done");
1537 return ERROR_OK;
1540 FLASH_BANK_COMMAND_HANDLER(sam4_flash_bank_command)
1542 struct sam4_chip *pChip;
1544 pChip = all_sam4_chips;
1546 /* is this an existing chip? */
1547 while (pChip) {
1548 if (pChip->target == bank->target)
1549 break;
1550 pChip = pChip->next;
1553 if (!pChip) {
1554 /* this is a *NEW* chip */
1555 pChip = calloc(1, sizeof(struct sam4_chip));
1556 if (!pChip) {
1557 LOG_ERROR("NO RAM!");
1558 return ERROR_FAIL;
1560 pChip->target = bank->target;
1561 /* insert at head */
1562 pChip->next = all_sam4_chips;
1563 all_sam4_chips = pChip;
1564 pChip->target = bank->target;
1565 /* assumption is this runs at 32khz */
1566 pChip->cfg.slow_freq = 32768;
1567 pChip->probed = 0;
1570 switch (bank->base) {
1571 default:
1572 LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x"
1573 "[at91sam4s series] )",
1574 ((unsigned int)(bank->base)),
1575 ((unsigned int)(FLASH_BANK_BASE_S)));
1576 return ERROR_FAIL;
1577 break;
1579 /* at91sam4s series only has bank 0*/
1580 /* at91sam4sd series has the same address for bank 0 (FLASH_BANK0_BASE_SD)*/
1581 case FLASH_BANK_BASE_S:
1582 bank->driver_priv = &(pChip->details.bank[0]);
1583 bank->bank_number = 0;
1584 pChip->details.bank[0].pChip = pChip;
1585 pChip->details.bank[0].pBank = bank;
1586 break;
1588 /* Bank 1 of at91sam4sd series */
1589 case FLASH_BANK1_BASE_1024K_SD:
1590 case FLASH_BANK1_BASE_2048K_SD:
1591 bank->driver_priv = &(pChip->details.bank[1]);
1592 bank->bank_number = 1;
1593 pChip->details.bank[1].pChip = pChip;
1594 pChip->details.bank[1].pBank = bank;
1595 break;
1598 /* we initialize after probing. */
1599 return ERROR_OK;
1602 static int sam4_GetDetails(struct sam4_bank_private *pPrivate)
1604 const struct sam4_chip_details *pDetails;
1605 struct sam4_chip *pChip;
1606 struct flash_bank *saved_banks[SAM4_MAX_FLASH_BANKS];
1607 unsigned x;
1609 LOG_DEBUG("Begin");
1610 pDetails = all_sam4_details;
1611 while (pDetails->name) {
1612 /* Compare cidr without version bits */
1613 if (pDetails->chipid_cidr == (pPrivate->pChip->cfg.CHIPID_CIDR & 0xFFFFFFE0))
1614 break;
1615 else
1616 pDetails++;
1618 if (pDetails->name == NULL) {
1619 LOG_ERROR("SAM4 ChipID 0x%08x not found in table (perhaps you can ID this chip?)",
1620 (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
1621 /* Help the victim, print details about the chip */
1622 LOG_INFO("SAM4 CHIPID_CIDR: 0x%08x decodes as follows",
1623 pPrivate->pChip->cfg.CHIPID_CIDR);
1624 sam4_explain_chipid_cidr(pPrivate->pChip);
1625 return ERROR_FAIL;
1628 /* DANGER: THERE ARE DRAGONS HERE */
1630 /* get our pChip - it is going */
1631 /* to be over-written shortly */
1632 pChip = pPrivate->pChip;
1634 /* Note that, in reality: */
1635 /* */
1636 /* pPrivate = &(pChip->details.bank[0]) */
1637 /* or pPrivate = &(pChip->details.bank[1]) */
1638 /* */
1640 /* save the "bank" pointers */
1641 for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++)
1642 saved_banks[x] = pChip->details.bank[x].pBank;
1644 /* Overwrite the "details" structure. */
1645 memcpy(&(pPrivate->pChip->details),
1646 pDetails,
1647 sizeof(pPrivate->pChip->details));
1649 /* now fix the ghosted pointers */
1650 for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
1651 pChip->details.bank[x].pChip = pChip;
1652 pChip->details.bank[x].pBank = saved_banks[x];
1655 /* update the *BANK*SIZE* */
1657 LOG_DEBUG("End");
1658 return ERROR_OK;
1661 static int _sam4_probe(struct flash_bank *bank, int noise)
1663 unsigned x;
1664 int r;
1665 struct sam4_bank_private *pPrivate;
1668 LOG_DEBUG("Begin: Bank: %d, Noise: %d", bank->bank_number, noise);
1669 if (bank->target->state != TARGET_HALTED) {
1670 LOG_ERROR("Target not halted");
1671 return ERROR_TARGET_NOT_HALTED;
1674 pPrivate = get_sam4_bank_private(bank);
1675 if (!pPrivate) {
1676 LOG_ERROR("Invalid/unknown bank number");
1677 return ERROR_FAIL;
1680 r = sam4_ReadAllRegs(pPrivate->pChip);
1681 if (r != ERROR_OK)
1682 return r;
1684 LOG_DEBUG("Here");
1685 if (pPrivate->pChip->probed)
1686 r = sam4_GetInfo(pPrivate->pChip);
1687 else
1688 r = sam4_GetDetails(pPrivate);
1689 if (r != ERROR_OK)
1690 return r;
1692 /* update the flash bank size */
1693 for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
1694 if (bank->base == pPrivate->pChip->details.bank[x].base_address) {
1695 bank->size = pPrivate->pChip->details.bank[x].size_bytes;
1696 break;
1700 if (bank->sectors == NULL) {
1701 bank->sectors = calloc(pPrivate->nsectors, (sizeof((bank->sectors)[0])));
1702 if (bank->sectors == NULL) {
1703 LOG_ERROR("No memory!");
1704 return ERROR_FAIL;
1706 bank->num_sectors = pPrivate->nsectors;
1708 for (x = 0; ((int)(x)) < bank->num_sectors; x++) {
1709 bank->sectors[x].size = pPrivate->sector_size;
1710 bank->sectors[x].offset = x * (pPrivate->sector_size);
1711 /* mark as unknown */
1712 bank->sectors[x].is_erased = -1;
1713 bank->sectors[x].is_protected = -1;
1717 pPrivate->probed = 1;
1719 r = sam4_protect_check(bank);
1720 if (r != ERROR_OK)
1721 return r;
1723 LOG_DEBUG("Bank = %d, nbanks = %d",
1724 pPrivate->bank_number, pPrivate->pChip->details.n_banks);
1725 if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
1726 /* read unique id, */
1727 /* it appears to be associated with the *last* flash bank. */
1728 FLASHD_ReadUniqueID(pPrivate);
1731 return r;
1734 static int sam4_probe(struct flash_bank *bank)
1736 return _sam4_probe(bank, 1);
1739 static int sam4_auto_probe(struct flash_bank *bank)
1741 return _sam4_probe(bank, 0);
1744 static int sam4_erase(struct flash_bank *bank, int first, int last)
1746 struct sam4_bank_private *pPrivate;
1747 int r;
1748 int i;
1749 int pageCount;
1750 /*16 pages equals 8KB - Same size as a lock region*/
1751 pageCount = 16;
1752 uint32_t status;
1754 LOG_DEBUG("Here");
1755 if (bank->target->state != TARGET_HALTED) {
1756 LOG_ERROR("Target not halted");
1757 return ERROR_TARGET_NOT_HALTED;
1760 r = sam4_auto_probe(bank);
1761 if (r != ERROR_OK) {
1762 LOG_DEBUG("Here,r=%d", r);
1763 return r;
1766 pPrivate = get_sam4_bank_private(bank);
1767 if (!(pPrivate->probed))
1768 return ERROR_FLASH_BANK_NOT_PROBED;
1770 if ((first == 0) && ((last + 1) == ((int)(pPrivate->nsectors)))) {
1771 /* whole chip */
1772 LOG_DEBUG("Here");
1773 return FLASHD_EraseEntireBank(pPrivate);
1775 LOG_INFO("sam4 does not auto-erase while programming (Erasing relevant sectors)");
1776 LOG_INFO("sam4 First: 0x%08x Last: 0x%08x", (unsigned int)(first), (unsigned int)(last));
1777 for (i = first; i <= last; i++) {
1778 /*16 pages equals 8KB - Same size as a lock region*/
1779 r = FLASHD_ErasePages(pPrivate, (i * pageCount), pageCount, &status);
1780 LOG_INFO("Erasing sector: 0x%08x", (unsigned int)(i));
1781 if (r != ERROR_OK)
1782 LOG_ERROR("SAM4: Error performing Erase page @ lock region number %d",
1783 (unsigned int)(i));
1784 if (status & (1 << 2)) {
1785 LOG_ERROR("SAM4: Lock Region %d is locked", (unsigned int)(i));
1786 return ERROR_FAIL;
1788 if (status & (1 << 1)) {
1789 LOG_ERROR("SAM4: Flash Command error @lock region %d", (unsigned int)(i));
1790 return ERROR_FAIL;
1794 return ERROR_OK;
1797 static int sam4_protect(struct flash_bank *bank, int set, int first, int last)
1799 struct sam4_bank_private *pPrivate;
1800 int r;
1802 LOG_DEBUG("Here");
1803 if (bank->target->state != TARGET_HALTED) {
1804 LOG_ERROR("Target not halted");
1805 return ERROR_TARGET_NOT_HALTED;
1808 pPrivate = get_sam4_bank_private(bank);
1809 if (!(pPrivate->probed))
1810 return ERROR_FLASH_BANK_NOT_PROBED;
1812 if (set)
1813 r = FLASHD_Lock(pPrivate, (unsigned)(first), (unsigned)(last));
1814 else
1815 r = FLASHD_Unlock(pPrivate, (unsigned)(first), (unsigned)(last));
1816 LOG_DEBUG("End: r=%d", r);
1818 return r;
1822 static int sam4_info(struct flash_bank *bank, char *buf, int buf_size)
1824 if (bank->target->state != TARGET_HALTED) {
1825 LOG_ERROR("Target not halted");
1826 return ERROR_TARGET_NOT_HALTED;
1828 buf[0] = 0;
1829 return ERROR_OK;
1832 static int sam4_page_read(struct sam4_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
1834 uint32_t adr;
1835 int r;
1837 adr = pagenum * pPrivate->page_size;
1838 adr = adr + pPrivate->base_address;
1840 r = target_read_memory(pPrivate->pChip->target,
1841 adr,
1842 4, /* THIS*MUST*BE* in 32bit values */
1843 pPrivate->page_size / 4,
1844 buf);
1845 if (r != ERROR_OK)
1846 LOG_ERROR("SAM4: Flash program failed to read page phys address: 0x%08x",
1847 (unsigned int)(adr));
1848 return r;
1851 /* The code below is basically this: */
1852 /* compiled with */
1853 /* arm-none-eabi-gcc -mthumb -mcpu = cortex-m3 -O9 -S ./foobar.c -o foobar.s */
1854 /* */
1855 /* Only the *CPU* can write to the flash buffer. */
1856 /* the DAP cannot... so - we download this 28byte thing */
1857 /* Run the algorithm - (below) */
1858 /* to program the device */
1859 /* */
1860 /* ======================================== */
1861 /* #include <stdint.h> */
1862 /* */
1863 /* struct foo { */
1864 /* uint32_t *dst; */
1865 /* const uint32_t *src; */
1866 /* int n; */
1867 /* volatile uint32_t *base; */
1868 /* uint32_t cmd; */
1869 /* }; */
1870 /* */
1871 /* */
1872 /* uint32_t sam4_function(struct foo *p) */
1873 /* { */
1874 /* volatile uint32_t *v; */
1875 /* uint32_t *d; */
1876 /* const uint32_t *s; */
1877 /* int n; */
1878 /* uint32_t r; */
1879 /* */
1880 /* d = p->dst; */
1881 /* s = p->src; */
1882 /* n = p->n; */
1883 /* */
1884 /* do { */
1885 /* *d++ = *s++; */
1886 /* } while (--n) */
1887 /* ; */
1888 /* */
1889 /* v = p->base; */
1890 /* */
1891 /* v[ 1 ] = p->cmd; */
1892 /* do { */
1893 /* r = v[8/4]; */
1894 /* } while (!(r&1)) */
1895 /* ; */
1896 /* return r; */
1897 /* } */
1898 /* ======================================== */
1900 static const uint8_t
1901 sam4_page_write_opcodes[] = {
1902 /* 24 0000 0446 mov r4, r0 */
1903 0x04, 0x46,
1904 /* 25 0002 6168 ldr r1, [r4, #4] */
1905 0x61, 0x68,
1906 /* 26 0004 0068 ldr r0, [r0, #0] */
1907 0x00, 0x68,
1908 /* 27 0006 A268 ldr r2, [r4, #8] */
1909 0xa2, 0x68,
1910 /* 28 @ lr needed for prologue */
1911 /* 29 .L2: */
1912 /* 30 0008 51F8043B ldr r3, [r1], #4 */
1913 0x51, 0xf8, 0x04, 0x3b,
1914 /* 31 000c 12F1FF32 adds r2, r2, #-1 */
1915 0x12, 0xf1, 0xff, 0x32,
1916 /* 32 0010 40F8043B str r3, [r0], #4 */
1917 0x40, 0xf8, 0x04, 0x3b,
1918 /* 33 0014 F8D1 bne .L2 */
1919 0xf8, 0xd1,
1920 /* 34 0016 E268 ldr r2, [r4, #12] */
1921 0xe2, 0x68,
1922 /* 35 0018 2369 ldr r3, [r4, #16] */
1923 0x23, 0x69,
1924 /* 36 001a 5360 str r3, [r2, #4] */
1925 0x53, 0x60,
1926 /* 37 001c 0832 adds r2, r2, #8 */
1927 0x08, 0x32,
1928 /* 38 .L4: */
1929 /* 39 001e 1068 ldr r0, [r2, #0] */
1930 0x10, 0x68,
1931 /* 40 0020 10F0010F tst r0, #1 */
1932 0x10, 0xf0, 0x01, 0x0f,
1933 /* 41 0024 FBD0 beq .L4 */
1934 0xfb, 0xd0,
1935 0x00, 0xBE /* bkpt #0 */
1938 static int sam4_page_write(struct sam4_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
1940 uint32_t adr;
1941 uint32_t status;
1942 uint32_t fmr; /* EEFC Flash Mode Register */
1943 int r;
1945 adr = pagenum * pPrivate->page_size;
1946 adr = (adr + pPrivate->base_address);
1948 /* Get flash mode register value */
1949 r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address, &fmr);
1950 if (r != ERROR_OK)
1951 LOG_DEBUG("Error Read failed: read flash mode register");
1953 /* Clear flash wait state field */
1954 fmr &= 0xfffff0ff;
1956 /* set FWS (flash wait states) field in the FMR (flash mode register) */
1957 fmr |= (pPrivate->flash_wait_states << 8);
1959 LOG_DEBUG("Flash Mode: 0x%08x", ((unsigned int)(fmr)));
1960 r = target_write_u32(pPrivate->pBank->target, pPrivate->controller_address, fmr);
1961 if (r != ERROR_OK)
1962 LOG_DEBUG("Error Write failed: set flash mode register");
1964 /* 1st sector 8kBytes - page 0 - 15*/
1965 /* 2nd sector 8kBytes - page 16 - 30*/
1966 /* 3rd sector 48kBytes - page 31 - 127*/
1967 LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
1968 r = target_write_memory(pPrivate->pChip->target,
1969 adr,
1970 4, /* THIS*MUST*BE* in 32bit values */
1971 pPrivate->page_size / 4,
1972 buf);
1973 if (r != ERROR_OK) {
1974 LOG_ERROR("SAM4: Failed to write (buffer) page at phys address 0x%08x",
1975 (unsigned int)(adr));
1976 return r;
1979 r = EFC_PerformCommand(pPrivate,
1980 /* send Erase & Write Page */
1981 AT91C_EFC_FCMD_WP, /*AT91C_EFC_FCMD_EWP only works on first two 8kb sectors*/
1982 pagenum,
1983 &status);
1985 if (r != ERROR_OK)
1986 LOG_ERROR("SAM4: Error performing Write page @ phys address 0x%08x",
1987 (unsigned int)(adr));
1988 if (status & (1 << 2)) {
1989 LOG_ERROR("SAM4: Page @ Phys address 0x%08x is locked", (unsigned int)(adr));
1990 return ERROR_FAIL;
1992 if (status & (1 << 1)) {
1993 LOG_ERROR("SAM4: Flash Command error @phys address 0x%08x", (unsigned int)(adr));
1994 return ERROR_FAIL;
1996 return ERROR_OK;
1999 static int sam4_write(struct flash_bank *bank,
2000 uint8_t *buffer,
2001 uint32_t offset,
2002 uint32_t count)
2004 int n;
2005 unsigned page_cur;
2006 unsigned page_end;
2007 int r;
2008 unsigned page_offset;
2009 struct sam4_bank_private *pPrivate;
2010 uint8_t *pagebuffer;
2012 /* incase we bail further below, set this to null */
2013 pagebuffer = NULL;
2015 /* ignore dumb requests */
2016 if (count == 0) {
2017 r = ERROR_OK;
2018 goto done;
2021 if (bank->target->state != TARGET_HALTED) {
2022 LOG_ERROR("Target not halted");
2023 r = ERROR_TARGET_NOT_HALTED;
2024 goto done;
2027 pPrivate = get_sam4_bank_private(bank);
2028 if (!(pPrivate->probed)) {
2029 r = ERROR_FLASH_BANK_NOT_PROBED;
2030 goto done;
2033 if ((offset + count) > pPrivate->size_bytes) {
2034 LOG_ERROR("Flash write error - past end of bank");
2035 LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
2036 (unsigned int)(offset),
2037 (unsigned int)(count),
2038 (unsigned int)(pPrivate->size_bytes));
2039 r = ERROR_FAIL;
2040 goto done;
2043 pagebuffer = malloc(pPrivate->page_size);
2044 if (!pagebuffer) {
2045 LOG_ERROR("No memory for %d Byte page buffer", (int)(pPrivate->page_size));
2046 r = ERROR_FAIL;
2047 goto done;
2050 /* what page do we start & end in? */
2051 page_cur = offset / pPrivate->page_size;
2052 page_end = (offset + count - 1) / pPrivate->page_size;
2054 LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
2055 LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
2057 /* Special case: all one page */
2058 /* */
2059 /* Otherwise: */
2060 /* (1) non-aligned start */
2061 /* (2) body pages */
2062 /* (3) non-aligned end. */
2064 /* Handle special case - all one page. */
2065 if (page_cur == page_end) {
2066 LOG_DEBUG("Special case, all in one page");
2067 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2068 if (r != ERROR_OK)
2069 goto done;
2071 page_offset = (offset & (pPrivate->page_size-1));
2072 memcpy(pagebuffer + page_offset,
2073 buffer,
2074 count);
2076 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2077 if (r != ERROR_OK)
2078 goto done;
2079 r = ERROR_OK;
2080 goto done;
2083 /* non-aligned start */
2084 page_offset = offset & (pPrivate->page_size - 1);
2085 if (page_offset) {
2086 LOG_DEBUG("Not-Aligned start");
2087 /* read the partial */
2088 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2089 if (r != ERROR_OK)
2090 goto done;
2092 /* over-write with new data */
2093 n = (pPrivate->page_size - page_offset);
2094 memcpy(pagebuffer + page_offset,
2095 buffer,
2098 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2099 if (r != ERROR_OK)
2100 goto done;
2102 count -= n;
2103 offset += n;
2104 buffer += n;
2105 page_cur++;
2108 /* By checking that offset is correct here, we also
2109 fix a clang warning */
2110 assert(offset % pPrivate->page_size == 0);
2112 /* intermediate large pages */
2113 /* also - the final *terminal* */
2114 /* if that terminal page is a full page */
2115 LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
2116 (int)page_cur, (int)page_end, (unsigned int)(count));
2118 while ((page_cur < page_end) &&
2119 (count >= pPrivate->page_size)) {
2120 r = sam4_page_write(pPrivate, page_cur, buffer);
2121 if (r != ERROR_OK)
2122 goto done;
2123 count -= pPrivate->page_size;
2124 buffer += pPrivate->page_size;
2125 page_cur += 1;
2128 /* terminal partial page? */
2129 if (count) {
2130 LOG_DEBUG("Terminal partial page, count = 0x%08x", (unsigned int)(count));
2131 /* we have a partial page */
2132 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2133 if (r != ERROR_OK)
2134 goto done;
2135 /* data goes at start */
2136 memcpy(pagebuffer, buffer, count);
2137 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2138 if (r != ERROR_OK)
2139 goto done;
2141 LOG_DEBUG("Done!");
2142 r = ERROR_OK;
2143 done:
2144 if (pagebuffer)
2145 free(pagebuffer);
2146 return r;
2149 COMMAND_HANDLER(sam4_handle_info_command)
2151 struct sam4_chip *pChip;
2152 pChip = get_current_sam4(CMD_CTX);
2153 if (!pChip)
2154 return ERROR_OK;
2156 unsigned x;
2157 int r;
2159 /* bank0 must exist before we can do anything */
2160 if (pChip->details.bank[0].pBank == NULL) {
2161 x = 0;
2162 need_define:
2163 command_print(CMD_CTX,
2164 "Please define bank %d via command: flash bank %s ... ",
2166 at91sam4_flash.name);
2167 return ERROR_FAIL;
2170 /* if bank 0 is not probed, then probe it */
2171 if (!(pChip->details.bank[0].probed)) {
2172 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2173 if (r != ERROR_OK)
2174 return ERROR_FAIL;
2176 /* above guarantees the "chip details" structure is valid */
2177 /* and thus, bank private areas are valid */
2178 /* and we have a SAM4 chip, what a concept! */
2180 /* auto-probe other banks, 0 done above */
2181 for (x = 1; x < SAM4_MAX_FLASH_BANKS; x++) {
2182 /* skip banks not present */
2183 if (!(pChip->details.bank[x].present))
2184 continue;
2186 if (pChip->details.bank[x].pBank == NULL)
2187 goto need_define;
2189 if (pChip->details.bank[x].probed)
2190 continue;
2192 r = sam4_auto_probe(pChip->details.bank[x].pBank);
2193 if (r != ERROR_OK)
2194 return r;
2197 r = sam4_GetInfo(pChip);
2198 if (r != ERROR_OK) {
2199 LOG_DEBUG("Sam4Info, Failed %d", r);
2200 return r;
2203 return ERROR_OK;
2206 COMMAND_HANDLER(sam4_handle_gpnvm_command)
2208 unsigned x, v;
2209 int r, who;
2210 struct sam4_chip *pChip;
2212 pChip = get_current_sam4(CMD_CTX);
2213 if (!pChip)
2214 return ERROR_OK;
2216 if (pChip->target->state != TARGET_HALTED) {
2217 LOG_ERROR("sam4 - target not halted");
2218 return ERROR_TARGET_NOT_HALTED;
2221 if (pChip->details.bank[0].pBank == NULL) {
2222 command_print(CMD_CTX, "Bank0 must be defined first via: flash bank %s ...",
2223 at91sam4_flash.name);
2224 return ERROR_FAIL;
2226 if (!pChip->details.bank[0].probed) {
2227 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2228 if (r != ERROR_OK)
2229 return r;
2232 switch (CMD_ARGC) {
2233 default:
2234 return ERROR_COMMAND_SYNTAX_ERROR;
2235 break;
2236 case 0:
2237 goto showall;
2238 break;
2239 case 1:
2240 who = -1;
2241 break;
2242 case 2:
2243 if ((0 == strcmp(CMD_ARGV[0], "show")) && (0 == strcmp(CMD_ARGV[1], "all")))
2244 who = -1;
2245 else {
2246 uint32_t v32;
2247 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], v32);
2248 who = v32;
2250 break;
2253 if (0 == strcmp("show", CMD_ARGV[0])) {
2254 if (who == -1) {
2255 showall:
2256 r = ERROR_OK;
2257 for (x = 0; x < pChip->details.n_gpnvms; x++) {
2258 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
2259 if (r != ERROR_OK)
2260 break;
2261 command_print(CMD_CTX, "sam4-gpnvm%u: %u", x, v);
2263 return r;
2265 if ((who >= 0) && (((unsigned)(who)) < pChip->details.n_gpnvms)) {
2266 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), who, &v);
2267 command_print(CMD_CTX, "sam4-gpnvm%u: %u", who, v);
2268 return r;
2269 } else {
2270 command_print(CMD_CTX, "sam4-gpnvm invalid GPNVM: %u", who);
2271 return ERROR_COMMAND_SYNTAX_ERROR;
2275 if (who == -1) {
2276 command_print(CMD_CTX, "Missing GPNVM number");
2277 return ERROR_COMMAND_SYNTAX_ERROR;
2280 if (0 == strcmp("set", CMD_ARGV[0]))
2281 r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
2282 else if ((0 == strcmp("clr", CMD_ARGV[0])) ||
2283 (0 == strcmp("clear", CMD_ARGV[0]))) /* quietly accept both */
2284 r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
2285 else {
2286 command_print(CMD_CTX, "Unknown command: %s", CMD_ARGV[0]);
2287 r = ERROR_COMMAND_SYNTAX_ERROR;
2289 return r;
2292 COMMAND_HANDLER(sam4_handle_slowclk_command)
2294 struct sam4_chip *pChip;
2296 pChip = get_current_sam4(CMD_CTX);
2297 if (!pChip)
2298 return ERROR_OK;
2300 switch (CMD_ARGC) {
2301 case 0:
2302 /* show */
2303 break;
2304 case 1:
2306 /* set */
2307 uint32_t v;
2308 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], v);
2309 if (v > 200000) {
2310 /* absurd slow clock of 200Khz? */
2311 command_print(CMD_CTX, "Absurd/illegal slow clock freq: %d\n", (int)(v));
2312 return ERROR_COMMAND_SYNTAX_ERROR;
2314 pChip->cfg.slow_freq = v;
2315 break;
2317 default:
2318 /* error */
2319 command_print(CMD_CTX, "Too many parameters");
2320 return ERROR_COMMAND_SYNTAX_ERROR;
2321 break;
2323 command_print(CMD_CTX, "Slowclk freq: %d.%03dkhz",
2324 (int)(pChip->cfg.slow_freq / 1000),
2325 (int)(pChip->cfg.slow_freq % 1000));
2326 return ERROR_OK;
2329 static const struct command_registration at91sam4_exec_command_handlers[] = {
2331 .name = "gpnvm",
2332 .handler = sam4_handle_gpnvm_command,
2333 .mode = COMMAND_EXEC,
2334 .usage = "[('clr'|'set'|'show') bitnum]",
2335 .help = "Without arguments, shows all bits in the gpnvm "
2336 "register. Otherwise, clears, sets, or shows one "
2337 "General Purpose Non-Volatile Memory (gpnvm) bit.",
2340 .name = "info",
2341 .handler = sam4_handle_info_command,
2342 .mode = COMMAND_EXEC,
2343 .help = "Print information about the current at91sam4 chip"
2344 "and its flash configuration.",
2347 .name = "slowclk",
2348 .handler = sam4_handle_slowclk_command,
2349 .mode = COMMAND_EXEC,
2350 .usage = "[clock_hz]",
2351 .help = "Display or set the slowclock frequency "
2352 "(default 32768 Hz).",
2354 COMMAND_REGISTRATION_DONE
2356 static const struct command_registration at91sam4_command_handlers[] = {
2358 .name = "at91sam4",
2359 .mode = COMMAND_ANY,
2360 .help = "at91sam4 flash command group",
2361 .usage = "",
2362 .chain = at91sam4_exec_command_handlers,
2364 COMMAND_REGISTRATION_DONE
2367 struct flash_driver at91sam4_flash = {
2368 .name = "at91sam4",
2369 .commands = at91sam4_command_handlers,
2370 .flash_bank_command = sam4_flash_bank_command,
2371 .erase = sam4_erase,
2372 .protect = sam4_protect,
2373 .write = sam4_write,
2374 .read = default_flash_read,
2375 .probe = sam4_probe,
2376 .auto_probe = sam4_auto_probe,
2377 .erase_check = default_flash_blank_check,
2378 .protect_check = sam4_protect_check,
2379 .info = sam4_info,