Modified Sector Erase for AT91SAM4S
[fw/openocd] / src / flash / nor / at91sam4.c
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  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
25 ****************************************************************************/
26
27 /* Some of the the lower level code was based on code supplied by
28  * ATMEL under this copyright. */
29
30 /* BEGIN ATMEL COPYRIGHT */
31 /* ----------------------------------------------------------------------------
32  *         ATMEL Microcontroller Software Support
33  * ----------------------------------------------------------------------------
34  * Copyright (c) 2009, Atmel Corporation
35  *
36  * All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions are met:
40  *
41  * - Redistributions of source code must retain the above copyright notice,
42  * this list of conditions and the disclaimer below.
43  *
44  * Atmel's name may not be used to endorse or promote products derived from
45  * this software without specific prior written permission.
46  *
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  * ----------------------------------------------------------------------------
58  */
59 /* END ATMEL COPYRIGHT */
60
61 #ifdef HAVE_CONFIG_H
62 #include "config.h"
63 #endif
64
65 #include "imp.h"
66 #include <helper/time_support.h>
67
68 #define REG_NAME_WIDTH  (12)
69
70 /* at91sam4s series (has always one flash bank)*/
71 #define FLASH_BANK_BASE_S   0x00400000
72
73 #define         AT91C_EFC_FCMD_GETD                 (0x0)       /* (EFC) Get Flash Descriptor */
74 #define         AT91C_EFC_FCMD_WP                   (0x1)       /* (EFC) Write Page */
75 #define         AT91C_EFC_FCMD_WPL                  (0x2)       /* (EFC) Write Page and Lock */
76 #define         AT91C_EFC_FCMD_EWP                  (0x3)       /* (EFC) Erase Page and Write Page */
77 #define         AT91C_EFC_FCMD_EWPL                 (0x4)       /* (EFC) Erase Page and Write Page
78                                                                  * then Lock */
79 #define         AT91C_EFC_FCMD_EA                   (0x5)       /* (EFC) Erase All */
80 /* cmd6 is not present int he at91sam4u4/2/1 data sheet table 19-2 */
81 /* #define      AT91C_EFC_FCMD_EPL                  (0x6) // (EFC) Erase plane? */
82 #define                 AT91C_EFC_FCMD_EPA                  (0x7)     /* (EFC) Erase pages */
83 #define         AT91C_EFC_FCMD_SLB                  (0x8)       /* (EFC) Set Lock Bit */
84 #define         AT91C_EFC_FCMD_CLB                  (0x9)       /* (EFC) Clear Lock Bit */
85 #define         AT91C_EFC_FCMD_GLB                  (0xA)       /* (EFC) Get Lock Bit */
86 #define         AT91C_EFC_FCMD_SFB                  (0xB)       /* (EFC) Set Fuse Bit */
87 #define         AT91C_EFC_FCMD_CFB                  (0xC)       /* (EFC) Clear Fuse Bit */
88 #define         AT91C_EFC_FCMD_GFB                  (0xD)       /* (EFC) Get Fuse Bit */
89 #define         AT91C_EFC_FCMD_STUI                 (0xE)       /* (EFC) Start Read Unique ID */
90 #define         AT91C_EFC_FCMD_SPUI                 (0xF)       /* (EFC) Stop Read Unique ID */
91
92 #define  offset_EFC_FMR   0
93 #define  offset_EFC_FCR   4
94 #define  offset_EFC_FSR   8
95 #define  offset_EFC_FRR   12
96
97 extern struct flash_driver at91sam4_flash;
98
99 static float _tomhz(uint32_t freq_hz)
100 {
101         float f;
102
103         f = ((float)(freq_hz)) / 1000000.0;
104         return f;
105 }
106
107 /* How the chip is configured. */
108 struct sam4_cfg {
109         uint32_t unique_id[4];
110
111         uint32_t slow_freq;
112         uint32_t rc_freq;
113         uint32_t mainosc_freq;
114         uint32_t plla_freq;
115         uint32_t mclk_freq;
116         uint32_t cpu_freq;
117         uint32_t fclk_freq;
118         uint32_t pclk0_freq;
119         uint32_t pclk1_freq;
120         uint32_t pclk2_freq;
121
122
123 #define SAM4_CHIPID_CIDR          (0x400E0740)
124         uint32_t CHIPID_CIDR;
125 #define SAM4_CHIPID_EXID          (0x400E0744)
126         uint32_t CHIPID_EXID;
127
128 #define SAM4_PMC_BASE             (0x400E0400)
129 #define SAM4_PMC_SCSR             (SAM4_PMC_BASE + 0x0008)
130         uint32_t PMC_SCSR;
131 #define SAM4_PMC_PCSR             (SAM4_PMC_BASE + 0x0018)
132         uint32_t PMC_PCSR;
133 #define SAM4_CKGR_UCKR            (SAM4_PMC_BASE + 0x001c)
134         uint32_t CKGR_UCKR;
135 #define SAM4_CKGR_MOR             (SAM4_PMC_BASE + 0x0020)
136         uint32_t CKGR_MOR;
137 #define SAM4_CKGR_MCFR            (SAM4_PMC_BASE + 0x0024)
138         uint32_t CKGR_MCFR;
139 #define SAM4_CKGR_PLLAR           (SAM4_PMC_BASE + 0x0028)
140         uint32_t CKGR_PLLAR;
141 #define SAM4_PMC_MCKR             (SAM4_PMC_BASE + 0x0030)
142         uint32_t PMC_MCKR;
143 #define SAM4_PMC_PCK0             (SAM4_PMC_BASE + 0x0040)
144         uint32_t PMC_PCK0;
145 #define SAM4_PMC_PCK1             (SAM4_PMC_BASE + 0x0044)
146         uint32_t PMC_PCK1;
147 #define SAM4_PMC_PCK2             (SAM4_PMC_BASE + 0x0048)
148         uint32_t PMC_PCK2;
149 #define SAM4_PMC_SR               (SAM4_PMC_BASE + 0x0068)
150         uint32_t PMC_SR;
151 #define SAM4_PMC_IMR              (SAM4_PMC_BASE + 0x006c)
152         uint32_t PMC_IMR;
153 #define SAM4_PMC_FSMR             (SAM4_PMC_BASE + 0x0070)
154         uint32_t PMC_FSMR;
155 #define SAM4_PMC_FSPR             (SAM4_PMC_BASE + 0x0074)
156         uint32_t PMC_FSPR;
157 };
158
159 struct sam4_bank_private {
160         int probed;
161         /* DANGER: THERE ARE DRAGONS HERE.. */
162         /* NOTE: If you add more 'ghost' pointers */
163         /* be aware that you must *manually* update */
164         /* these pointers in the function sam4_GetDetails() */
165         /* See the comment "Here there be dragons" */
166
167         /* so we can find the chip we belong to */
168         struct sam4_chip *pChip;
169         /* so we can find the orginal bank pointer */
170         struct flash_bank *pBank;
171         unsigned bank_number;
172         uint32_t controller_address;
173         uint32_t base_address;
174         uint32_t flash_wait_states;
175         bool present;
176         unsigned size_bytes;
177         unsigned nsectors;
178         unsigned sector_size;
179         unsigned page_size;
180 };
181
182 struct sam4_chip_details {
183         /* THERE ARE DRAGONS HERE.. */
184         /* note: If you add pointers here */
185         /* becareful about them as they */
186         /* may need to be updated inside */
187         /* the function: "sam4_GetDetails() */
188         /* which copy/overwrites the */
189         /* 'runtime' copy of this structure */
190         uint32_t chipid_cidr;
191         const char *name;
192
193         unsigned n_gpnvms;
194 #define SAM4_N_NVM_BITS 3
195         unsigned gpnvm[SAM4_N_NVM_BITS];
196         unsigned total_flash_size;
197         unsigned total_sram_size;
198         unsigned n_banks;
199 #define SAM4_MAX_FLASH_BANKS 2
200         /* these are "initialized" from the global const data */
201         struct sam4_bank_private bank[SAM4_MAX_FLASH_BANKS];
202 };
203
204 struct sam4_chip {
205         struct sam4_chip *next;
206         int probed;
207
208         /* this is "initialized" from the global const structure */
209         struct sam4_chip_details details;
210         struct target *target;
211         struct sam4_cfg cfg;
212 };
213
214
215 struct sam4_reg_list {
216         uint32_t address;  size_t struct_offset; const char *name;
217         void (*explain_func)(struct sam4_chip *pInfo);
218 };
219
220 static struct sam4_chip *all_sam4_chips;
221
222 static struct sam4_chip *get_current_sam4(struct command_context *cmd_ctx)
223 {
224         struct target *t;
225         static struct sam4_chip *p;
226
227         t = get_current_target(cmd_ctx);
228         if (!t) {
229                 command_print(cmd_ctx, "No current target?");
230                 return NULL;
231         }
232
233         p = all_sam4_chips;
234         if (!p) {
235                 /* this should not happen */
236                 /* the command is not registered until the chip is created? */
237                 command_print(cmd_ctx, "No SAM4 chips exist?");
238                 return NULL;
239         }
240
241         while (p) {
242                 if (p->target == t)
243                         return p;
244                 p = p->next;
245         }
246         command_print(cmd_ctx, "Cannot find SAM4 chip?");
247         return NULL;
248 }
249
250 /*The actual sector size of the SAM4S flash memory is 65536 bytes. 16 sectors for a 1024KB device*/
251 /*The lockregions are 8KB per lock reqion, with a 1024KB device having 128 lock reqions. */
252 /*For the best results, nsectors are thus set to the amount of lock regions, and the sector_size*/
253 /*set to the lock region size.  Page erases are used to erase 8KB sections when programming*/
254
255 /* these are used to *initialize* the "pChip->details" structure. */
256 static const struct sam4_chip_details all_sam4_details[] = {
257         /* Start at91sam4s* series */
258         /*atsam4s16c - LQFP100/BGA100*/
259         {
260                 .chipid_cidr    = 0x28AC0CE0,
261                 .name           = "at91sam4s16c",
262                 .total_flash_size     = 1024 * 1024,
263                 .total_sram_size      = 128 * 1024,
264                 .n_gpnvms       = 2,
265                 .n_banks        = 1,
266                 {
267 /*              .bank[0] = {*/
268                   {
269                         .probed = 0,
270                         .pChip  = NULL,
271                         .pBank  = NULL,
272                         .bank_number = 0,
273                         .base_address = FLASH_BANK_BASE_S,
274                         .controller_address = 0x400e0a00,
275                         .flash_wait_states = 6, /* workaround silicon bug */
276                         .present = 1,
277                         .size_bytes =  1024 * 1024,
278                         .nsectors   =  128,
279                         .sector_size = 8192,
280                         .page_size   = 512,
281                   },
282 /*              .bank[1] = {*/
283                   {
284                         .present = 0,
285                         .probed = 0,
286                         .bank_number = 1,
287
288                   },
289                 },
290         },
291         /*atsam4s16b - LQFP64/QFN64*/
292         {
293                 .chipid_cidr    = 0x289C0CE0,
294                 .name           = "at91sam4s16b",
295                 .total_flash_size     = 1024 * 1024,
296                 .total_sram_size      = 128 * 1024,
297                 .n_gpnvms       = 2,
298                 .n_banks        = 1,
299                 {
300 /*              .bank[0] = {*/
301                   {
302                         .probed = 0,
303                         .pChip  = NULL,
304                         .pBank  = NULL,
305                         .bank_number = 0,
306                         .base_address = FLASH_BANK_BASE_S,
307                         .controller_address = 0x400e0a00,
308                         .flash_wait_states = 6, /* workaround silicon bug */
309                         .present = 1,
310                         .size_bytes =  1024 * 1024,
311                         .nsectors   =  128,
312                         .sector_size = 8192,
313                         .page_size   = 512,
314                   },
315 /*              .bank[1] = {*/
316                   {
317                         .present = 0,
318                         .probed = 0,
319                         .bank_number = 1,
320
321                   },
322                 },
323         },
324         /*atsam4s16a - LQFP48/QFN48*/
325         {
326                 .chipid_cidr    = 0x288C0CE0,
327                 .name           = "at91sam4s16a",
328                 .total_flash_size     = 1024 * 1024,
329                 .total_sram_size      = 128 * 1024,
330                 .n_gpnvms       = 2,
331                 .n_banks        = 1,
332                 {
333 /*              .bank[0] = {*/
334                   {
335                         .probed = 0,
336                         .pChip  = NULL,
337                         .pBank  = NULL,
338                         .bank_number = 0,
339                         .base_address = FLASH_BANK_BASE_S,
340                         .controller_address = 0x400e0a00,
341                         .flash_wait_states = 6, /* workaround silicon bug */
342                         .present = 1,
343                         .size_bytes =  1024 * 1024,
344                         .nsectors   =  128,
345                         .sector_size = 8192,
346                         .page_size   = 512,
347                   },
348 /*              .bank[1] = {*/
349                   {
350                         .present = 0,
351                         .probed = 0,
352                         .bank_number = 1,
353
354                   },
355                 },
356         },
357         /*atsam4s8c - LQFP100/BGA100*/
358         {
359                 .chipid_cidr    = 0x28AC0AE0,
360                 .name           = "at91sam4s8c",
361                 .total_flash_size     = 512 * 1024,
362                 .total_sram_size      = 128 * 1024,
363                 .n_gpnvms       = 2,
364                 .n_banks        = 1,
365                 {
366 /*              .bank[0] = {*/
367                   {
368                         .probed = 0,
369                         .pChip  = NULL,
370                         .pBank  = NULL,
371                         .bank_number = 0,
372                         .base_address = FLASH_BANK_BASE_S,
373                         .controller_address = 0x400e0a00,
374                         .flash_wait_states = 6, /* workaround silicon bug */
375                         .present = 1,
376                         .size_bytes =  512 * 1024,
377                         .nsectors   =  64,
378                         .sector_size = 8192,
379                         .page_size   = 512,
380                   },
381 /*              .bank[1] = {*/
382                   {
383                         .present = 0,
384                         .probed = 0,
385                         .bank_number = 1,
386
387                   },
388                 },
389         },
390         /*atsam4s8b - LQFP64/BGA64*/
391         {
392                 .chipid_cidr    = 0x289C0AE0,
393                 .name           = "at91sam4s8b",
394                 .total_flash_size     = 512 * 1024,
395                 .total_sram_size      = 128 * 1024,
396                 .n_gpnvms       = 2,
397                 .n_banks        = 1,
398                 {
399 /*              .bank[0] = {*/
400                   {
401                         .probed = 0,
402                         .pChip  = NULL,
403                         .pBank  = NULL,
404                         .bank_number = 0,
405                         .base_address = FLASH_BANK_BASE_S,
406                         .controller_address = 0x400e0a00,
407                         .flash_wait_states = 6, /* workaround silicon bug */
408                         .present = 1,
409                         .size_bytes =  512 * 1024,
410                         .nsectors   =  64,
411                         .sector_size = 8192,
412                         .page_size   = 512,
413                   },
414 /*              .bank[1] = {*/
415                   {
416                         .present = 0,
417                         .probed = 0,
418                         .bank_number = 1,
419
420                   },
421                 },
422         },
423         /*atsam4s8a - LQFP48/BGA48*/
424         {
425                 .chipid_cidr    = 0x288C0AE0,
426                 .name           = "at91sam4s8a",
427                 .total_flash_size     = 512 * 1024,
428                 .total_sram_size      = 128 * 1024,
429                 .n_gpnvms       = 2,
430                 .n_banks        = 1,
431                 {
432 /*              .bank[0] = {*/
433                   {
434                         .probed = 0,
435                         .pChip  = NULL,
436                         .pBank  = NULL,
437                         .bank_number = 0,
438                         .base_address = FLASH_BANK_BASE_S,
439                         .controller_address = 0x400e0a00,
440                         .flash_wait_states = 6, /* workaround silicon bug */
441                         .present = 1,
442                         .size_bytes =  512 * 1024,
443                         .nsectors   =  64,
444                         .sector_size = 8192,
445                         .page_size   = 512,
446                   },
447 /*              .bank[1] = {*/
448                   {
449                         .present = 0,
450                         .probed = 0,
451                         .bank_number = 1,
452
453                   },
454                 },
455         },
456         /* terminate */
457         {
458                 .chipid_cidr    = 0,
459                 .name                   = NULL,
460         }
461 };
462
463 /* Globals above */
464 /***********************************************************************
465  **********************************************************************
466  **********************************************************************
467  **********************************************************************
468  **********************************************************************
469  **********************************************************************/
470 /* *ATMEL* style code - from the SAM4 driver code */
471
472 /**
473  * Get the current status of the EEFC and
474  * the value of some status bits (LOCKE, PROGE).
475  * @param pPrivate - info about the bank
476  * @param v        - result goes here
477  */
478 static int EFC_GetStatus(struct sam4_bank_private *pPrivate, uint32_t *v)
479 {
480         int r;
481         r = target_read_u32(pPrivate->pChip->target,
482                         pPrivate->controller_address + offset_EFC_FSR,
483                         v);
484         LOG_DEBUG("Status: 0x%08x (lockerror: %d, cmderror: %d, ready: %d)",
485                 (unsigned int)(*v),
486                 ((unsigned int)((*v >> 2) & 1)),
487                 ((unsigned int)((*v >> 1) & 1)),
488                 ((unsigned int)((*v >> 0) & 1)));
489
490         return r;
491 }
492
493 /**
494  * Get the result of the last executed command.
495  * @param pPrivate - info about the bank
496  * @param v        - result goes here
497  */
498 static int EFC_GetResult(struct sam4_bank_private *pPrivate, uint32_t *v)
499 {
500         int r;
501         uint32_t rv;
502         r = target_read_u32(pPrivate->pChip->target,
503                         pPrivate->controller_address + offset_EFC_FRR,
504                         &rv);
505         if (v)
506                 *v = rv;
507         LOG_DEBUG("Result: 0x%08x", ((unsigned int)(rv)));
508         return r;
509 }
510
511 static int EFC_StartCommand(struct sam4_bank_private *pPrivate,
512         unsigned command, unsigned argument)
513 {
514         uint32_t n, v;
515         int r;
516         int retry;
517
518         retry = 0;
519 do_retry:
520
521         /* Check command & argument */
522         switch (command) {
523
524                 case AT91C_EFC_FCMD_WP:
525                 case AT91C_EFC_FCMD_WPL:
526                 case AT91C_EFC_FCMD_EWP:
527                 case AT91C_EFC_FCMD_EWPL:
528                 /* case AT91C_EFC_FCMD_EPL: */
529                 case AT91C_EFC_FCMD_EPA:
530                 case AT91C_EFC_FCMD_SLB:
531                 case AT91C_EFC_FCMD_CLB:
532                         n = (pPrivate->size_bytes / pPrivate->page_size);
533                         if (argument >= n)
534                                 LOG_ERROR("*BUG*: Embedded flash has only %u pages", (unsigned)(n));
535                         break;
536
537                 case AT91C_EFC_FCMD_SFB:
538                 case AT91C_EFC_FCMD_CFB:
539                         if (argument >= pPrivate->pChip->details.n_gpnvms) {
540                                 LOG_ERROR("*BUG*: Embedded flash has only %d GPNVMs",
541                                                 pPrivate->pChip->details.n_gpnvms);
542                         }
543                         break;
544
545                 case AT91C_EFC_FCMD_GETD:
546                 case AT91C_EFC_FCMD_EA:
547                 case AT91C_EFC_FCMD_GLB:
548                 case AT91C_EFC_FCMD_GFB:
549                 case AT91C_EFC_FCMD_STUI:
550                 case AT91C_EFC_FCMD_SPUI:
551                         if (argument != 0)
552                                 LOG_ERROR("Argument is meaningless for cmd: %d", command);
553                         break;
554                 default:
555                         LOG_ERROR("Unknown command %d", command);
556                         break;
557         }
558
559         if (command == AT91C_EFC_FCMD_SPUI) {
560                 /* this is a very special situation. */
561                 /* Situation (1) - error/retry - see below */
562                 /*      And we are being called recursively */
563                 /* Situation (2) - normal, finished reading unique id */
564         } else {
565                 /* it should be "ready" */
566                 EFC_GetStatus(pPrivate, &v);
567                 if (v & 1) {
568                         /* then it is ready */
569                         /* we go on */
570                 } else {
571                         if (retry) {
572                                 /* we have done this before */
573                                 /* the controller is not responding. */
574                                 LOG_ERROR("flash controller(%d) is not ready! Error",
575                                         pPrivate->bank_number);
576                                 return ERROR_FAIL;
577                         } else {
578                                 retry++;
579                                 LOG_ERROR("Flash controller(%d) is not ready, attempting reset",
580                                         pPrivate->bank_number);
581                                 /* we do that by issuing the *STOP* command */
582                                 EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0);
583                                 /* above is recursive, and further recursion is blocked by */
584                                 /* if (command == AT91C_EFC_FCMD_SPUI) above */
585                                 goto do_retry;
586                         }
587                 }
588         }
589
590         v = (0x5A << 24) | (argument << 8) | command;
591         LOG_DEBUG("Command: 0x%08x", ((unsigned int)(v)));
592         r = target_write_u32(pPrivate->pBank->target,
593                         pPrivate->controller_address + offset_EFC_FCR, v);
594         if (r != ERROR_OK)
595                 LOG_DEBUG("Error Write failed");
596         return r;
597 }
598
599 /**
600  * Performs the given command and wait until its completion (or an error).
601  * @param pPrivate - info about the bank
602  * @param command  - Command to perform.
603  * @param argument - Optional command argument.
604  * @param status   - put command status bits here
605  */
606 static int EFC_PerformCommand(struct sam4_bank_private *pPrivate,
607         unsigned command,
608         unsigned argument,
609         uint32_t *status)
610 {
611
612         int r;
613         uint32_t v;
614         long long ms_now, ms_end;
615
616         /* default */
617         if (status)
618                 *status = 0;
619
620         r = EFC_StartCommand(pPrivate, command, argument);
621         if (r != ERROR_OK)
622                 return r;
623
624         ms_end = 10000 + timeval_ms();
625
626         do {
627                 r = EFC_GetStatus(pPrivate, &v);
628                 if (r != ERROR_OK)
629                         return r;
630                 ms_now = timeval_ms();
631                 if (ms_now > ms_end) {
632                         /* error */
633                         LOG_ERROR("Command timeout");
634                         return ERROR_FAIL;
635                 }
636         } while ((v & 1) == 0);
637
638         /* error bits.. */
639         if (status)
640                 *status = (v & 0x6);
641         return ERROR_OK;
642
643 }
644
645 /**
646  * Read the unique ID.
647  * @param pPrivate - info about the bank
648  * The unique ID is stored in the 'pPrivate' structure.
649  */
650 static int FLASHD_ReadUniqueID(struct sam4_bank_private *pPrivate)
651 {
652         int r;
653         uint32_t v;
654         int x;
655         /* assume 0 */
656         pPrivate->pChip->cfg.unique_id[0] = 0;
657         pPrivate->pChip->cfg.unique_id[1] = 0;
658         pPrivate->pChip->cfg.unique_id[2] = 0;
659         pPrivate->pChip->cfg.unique_id[3] = 0;
660
661         LOG_DEBUG("Begin");
662         r = EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_STUI, 0);
663         if (r < 0)
664                 return r;
665
666         for (x = 0; x < 4; x++) {
667                 r = target_read_u32(pPrivate->pChip->target,
668                                 pPrivate->pBank->base + (x * 4),
669                                 &v);
670                 if (r < 0)
671                         return r;
672                 pPrivate->pChip->cfg.unique_id[x] = v;
673         }
674
675         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0, NULL);
676         LOG_DEBUG("End: R=%d, id = 0x%08x, 0x%08x, 0x%08x, 0x%08x",
677                 r,
678                 (unsigned int)(pPrivate->pChip->cfg.unique_id[0]),
679                 (unsigned int)(pPrivate->pChip->cfg.unique_id[1]),
680                 (unsigned int)(pPrivate->pChip->cfg.unique_id[2]),
681                 (unsigned int)(pPrivate->pChip->cfg.unique_id[3]));
682         return r;
683
684 }
685
686 /**
687  * Erases the entire flash.
688  * @param pPrivate - the info about the bank.
689  */
690 static int FLASHD_EraseEntireBank(struct sam4_bank_private *pPrivate)
691 {
692         LOG_DEBUG("Here");
693         return EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_EA, 0, NULL);
694 }
695
696 /**
697  * Erases the entire flash.
698  * @param pPrivate - the info about the bank.
699  */
700 static int FLASHD_ErasePages(struct sam4_bank_private *pPrivate,
701                                                          int firstPage,
702                                                          int numPages,
703                                                          uint32_t *status)
704 {
705         LOG_DEBUG("Here");
706         uint8_t erasePages;
707         switch (numPages)       {
708                 case 4:
709                         erasePages = 0x00;
710                         break;
711                 case 8:
712                         erasePages = 0x01;
713                         break;
714                 case 16:
715                         erasePages = 0x02;
716                         break;
717                 case 32:
718                         erasePages = 0x03;
719                         break;
720                 default:
721                         erasePages = 0x00;
722                         break;
723         }
724
725         /* AT91C_EFC_FCMD_EPA
726          * According to the datasheet FARG[15:2] defines the page from which
727          * the erase will start.This page must be modulo 4, 8, 16 or 32
728          * according to the number of pages to erase. FARG[1:0] defines the
729          * number of pages to be erased. Previously (firstpage << 2) was used
730          * to conform to this, seems it should not be shifted...
731          */
732         return EFC_PerformCommand(pPrivate,
733                 /* send Erase Page */
734                 AT91C_EFC_FCMD_EPA,
735                 (firstPage) | erasePages,
736                 status);
737 }
738
739 /**
740  * Gets current GPNVM state.
741  * @param pPrivate - info about the bank.
742  * @param gpnvm    -  GPNVM bit index.
743  * @param puthere  - result stored here.
744  */
745 /* ------------------------------------------------------------------------------ */
746 static int FLASHD_GetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm, unsigned *puthere)
747 {
748         uint32_t v;
749         int r;
750
751         LOG_DEBUG("Here");
752         if (pPrivate->bank_number != 0) {
753                 LOG_ERROR("GPNVM only works with Bank0");
754                 return ERROR_FAIL;
755         }
756
757         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
758                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
759                         gpnvm, pPrivate->pChip->details.n_gpnvms);
760                 return ERROR_FAIL;
761         }
762
763         /* Get GPNVMs status */
764         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GFB, 0, NULL);
765         if (r != ERROR_OK) {
766                 LOG_ERROR("Failed");
767                 return r;
768         }
769
770         r = EFC_GetResult(pPrivate, &v);
771
772         if (puthere) {
773                 /* Check if GPNVM is set */
774                 /* get the bit and make it a 0/1 */
775                 *puthere = (v >> gpnvm) & 1;
776         }
777
778         return r;
779 }
780
781 /**
782  * Clears the selected GPNVM bit.
783  * @param pPrivate info about the bank
784  * @param gpnvm GPNVM index.
785  * @returns 0 if successful; otherwise returns an error code.
786  */
787 static int FLASHD_ClrGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
788 {
789         int r;
790         unsigned v;
791
792         LOG_DEBUG("Here");
793         if (pPrivate->bank_number != 0) {
794                 LOG_ERROR("GPNVM only works with Bank0");
795                 return ERROR_FAIL;
796         }
797
798         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
799                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
800                         gpnvm, pPrivate->pChip->details.n_gpnvms);
801                 return ERROR_FAIL;
802         }
803
804         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
805         if (r != ERROR_OK) {
806                 LOG_DEBUG("Failed: %d", r);
807                 return r;
808         }
809         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CFB, gpnvm, NULL);
810         LOG_DEBUG("End: %d", r);
811         return r;
812 }
813
814 /**
815  * Sets the selected GPNVM bit.
816  * @param pPrivate info about the bank
817  * @param gpnvm GPNVM index.
818  */
819 static int FLASHD_SetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
820 {
821         int r;
822         unsigned v;
823
824         if (pPrivate->bank_number != 0) {
825                 LOG_ERROR("GPNVM only works with Bank0");
826                 return ERROR_FAIL;
827         }
828
829         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
830                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
831                         gpnvm, pPrivate->pChip->details.n_gpnvms);
832                 return ERROR_FAIL;
833         }
834
835         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
836         if (r != ERROR_OK)
837                 return r;
838         if (v) {
839                 /* already set */
840                 r = ERROR_OK;
841         } else {
842                 /* set it */
843                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SFB, gpnvm, NULL);
844         }
845         return r;
846 }
847
848 /**
849  * Returns a bit field (at most 64) of locked regions within a page.
850  * @param pPrivate info about the bank
851  * @param v where to store locked bits
852  */
853 static int FLASHD_GetLockBits(struct sam4_bank_private *pPrivate, uint32_t *v)
854 {
855         int r;
856         LOG_DEBUG("Here");
857         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GLB, 0, NULL);
858         if (r == ERROR_OK)      {
859                 EFC_GetResult(pPrivate, v);
860                 EFC_GetResult(pPrivate, v);
861                 EFC_GetResult(pPrivate, v);
862                 r = EFC_GetResult(pPrivate, v);
863         }
864         LOG_DEBUG("End: %d", r);
865         return r;
866 }
867
868 /**
869  * Unlocks all the regions in the given address range.
870  * @param pPrivate info about the bank
871  * @param start_sector first sector to unlock
872  * @param end_sector last (inclusive) to unlock
873  */
874
875 static int FLASHD_Unlock(struct sam4_bank_private *pPrivate,
876         unsigned start_sector,
877         unsigned end_sector)
878 {
879         int r;
880         uint32_t status;
881         uint32_t pg;
882         uint32_t pages_per_sector;
883
884         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
885
886         /* Unlock all pages */
887         while (start_sector <= end_sector) {
888                 pg = start_sector * pages_per_sector;
889
890                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CLB, pg, &status);
891                 if (r != ERROR_OK)
892                         return r;
893                 start_sector++;
894         }
895
896         return ERROR_OK;
897 }
898
899 /**
900  * Locks regions
901  * @param pPrivate - info about the bank
902  * @param start_sector - first sector to lock
903  * @param end_sector   - last sector (inclusive) to lock
904  */
905 static int FLASHD_Lock(struct sam4_bank_private *pPrivate,
906         unsigned start_sector,
907         unsigned end_sector)
908 {
909         uint32_t status;
910         uint32_t pg;
911         uint32_t pages_per_sector;
912         int r;
913
914         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
915
916         /* Lock all pages */
917         while (start_sector <= end_sector) {
918                 pg = start_sector * pages_per_sector;
919
920                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SLB, pg, &status);
921                 if (r != ERROR_OK)
922                         return r;
923                 start_sector++;
924         }
925         return ERROR_OK;
926 }
927
928 /****** END SAM4 CODE ********/
929
930 /* begin helpful debug code */
931 /* print the fieldname, the field value, in dec & hex, and return field value */
932 static uint32_t sam4_reg_fieldname(struct sam4_chip *pChip,
933         const char *regname,
934         uint32_t value,
935         unsigned shift,
936         unsigned width)
937 {
938         uint32_t v;
939         int hwidth, dwidth;
940
941
942         /* extract the field */
943         v = value >> shift;
944         v = v & ((1 << width)-1);
945         if (width <= 16) {
946                 hwidth = 4;
947                 dwidth = 5;
948         } else {
949                 hwidth = 8;
950                 dwidth = 12;
951         }
952
953         /* show the basics */
954         LOG_USER_N("\t%*s: %*d [0x%0*x] ",
955                 REG_NAME_WIDTH, regname,
956                 dwidth, v,
957                 hwidth, v);
958         return v;
959 }
960
961 static const char _unknown[] = "unknown";
962 static const char *const eproc_names[] = {
963         _unknown,                                       /* 0 */
964         "arm946es",                                     /* 1 */
965         "arm7tdmi",                                     /* 2 */
966         "cortex-m3",                            /* 3 */
967         "arm920t",                                      /* 4 */
968         "arm926ejs",                            /* 5 */
969         "cortex-a5",                            /* 6 */
970         "cortex-m4",                            /* 7 */
971         _unknown,                                       /* 8 */
972         _unknown,                                       /* 9 */
973         _unknown,                                       /* 10 */
974         _unknown,                                       /* 11 */
975         _unknown,                                       /* 12 */
976         _unknown,                                       /* 13 */
977         _unknown,                                       /* 14 */
978         _unknown,                                       /* 15 */
979 };
980
981 #define nvpsize2 nvpsize                /* these two tables are identical */
982 static const char *const nvpsize[] = {
983         "none",                                         /*  0 */
984         "8K bytes",                                     /*  1 */
985         "16K bytes",                            /*  2 */
986         "32K bytes",                            /*  3 */
987         _unknown,                                       /*  4 */
988         "64K bytes",                            /*  5 */
989         _unknown,                                       /*  6 */
990         "128K bytes",                           /*  7 */
991         _unknown,                                       /*  8 */
992         "256K bytes",                           /*  9 */
993         "512K bytes",                           /* 10 */
994         _unknown,                                       /* 11 */
995         "1024K bytes",                          /* 12 */
996         _unknown,                                       /* 13 */
997         "2048K bytes",                          /* 14 */
998         _unknown,                                       /* 15 */
999 };
1000
1001 static const char *const sramsize[] = {
1002         "48K Bytes",                            /*  0 */
1003         "1K Bytes",                                     /*  1 */
1004         "2K Bytes",                                     /*  2 */
1005         "6K Bytes",                                     /*  3 */
1006         "112K Bytes",                           /*  4 */
1007         "4K Bytes",                                     /*  5 */
1008         "80K Bytes",                            /*  6 */
1009         "160K Bytes",                           /*  7 */
1010         "8K Bytes",                                     /*  8 */
1011         "16K Bytes",                            /*  9 */
1012         "32K Bytes",                            /* 10 */
1013         "64K Bytes",                            /* 11 */
1014         "128K Bytes",                           /* 12 */
1015         "256K Bytes",                           /* 13 */
1016         "96K Bytes",                            /* 14 */
1017         "512K Bytes",                           /* 15 */
1018
1019 };
1020
1021 static const struct archnames { unsigned value; const char *name; } archnames[] = {
1022         { 0x19,  "AT91SAM9xx Series"                                            },
1023         { 0x29,  "AT91SAM9XExx Series"                                          },
1024         { 0x34,  "AT91x34 Series"                                                       },
1025         { 0x37,  "CAP7 Series"                                                          },
1026         { 0x39,  "CAP9 Series"                                                          },
1027         { 0x3B,  "CAP11 Series"                                                         },
1028         { 0x40,  "AT91x40 Series"                                                       },
1029         { 0x42,  "AT91x42 Series"                                                       },
1030         { 0x55,  "AT91x55 Series"                                                       },
1031         { 0x60,  "AT91SAM7Axx Series"                                           },
1032         { 0x61,  "AT91SAM7AQxx Series"                                          },
1033         { 0x63,  "AT91x63 Series"                                                       },
1034         { 0x70,  "AT91SAM7Sxx Series"                                           },
1035         { 0x71,  "AT91SAM7XCxx Series"                                          },
1036         { 0x72,  "AT91SAM7SExx Series"                                          },
1037         { 0x73,  "AT91SAM7Lxx Series"                                           },
1038         { 0x75,  "AT91SAM7Xxx Series"                                           },
1039         { 0x76,  "AT91SAM7SLxx Series"                                          },
1040         { 0x80,  "ATSAM3UxC Series (100-pin version)"           },
1041         { 0x81,  "ATSAM3UxE Series (144-pin version)"           },
1042         { 0x83,  "ATSAM3A/SAM4A xC Series (100-pin version)"},
1043         { 0x84,  "ATSAM3X/SAM4X xC Series (100-pin version)"},
1044         { 0x85,  "ATSAM3X/SAM4X xE Series (144-pin version)"},
1045         { 0x86,  "ATSAM3X/SAM4X xG Series (208/217-pin version)"        },
1046         { 0x88,  "ATSAM3S/SAM4S xA Series (48-pin version)"     },
1047         { 0x89,  "ATSAM3S/SAM4S xB Series (64-pin version)"     },
1048         { 0x8A,  "ATSAM3S/SAM4S xC Series (100-pin version)"},
1049         { 0x92,  "AT91x92 Series"                                                       },
1050         { 0x93,  "ATSAM3NxA Series (48-pin version)"            },
1051         { 0x94,  "ATSAM3NxB Series (64-pin version)"            },
1052         { 0x95,  "ATSAM3NxC Series (100-pin version)"           },
1053         { 0x98,  "ATSAM3SDxA Series (48-pin version)"           },
1054         { 0x99,  "ATSAM3SDxB Series (64-pin version)"           },
1055         { 0x9A,  "ATSAM3SDxC Series (100-pin version)"          },
1056         { 0xA5,  "ATSAM5A"                                                              },
1057         { 0xF0,  "AT75Cxx Series"                                                       },
1058         { -1, NULL },
1059 };
1060
1061 static const char *const nvptype[] = {
1062         "rom",  /* 0 */
1063         "romless or onchip flash",      /* 1 */
1064         "embedded flash memory",/* 2 */
1065         "rom(nvpsiz) + embedded flash (nvpsiz2)",       /* 3 */
1066         "sram emulating flash", /* 4 */
1067         _unknown,       /* 5 */
1068         _unknown,       /* 6 */
1069         _unknown,       /* 7 */
1070 };
1071
1072 static const char *_yes_or_no(uint32_t v)
1073 {
1074         if (v)
1075                 return "YES";
1076         else
1077                 return "NO";
1078 }
1079
1080 static const char *const _rc_freq[] = {
1081         "4 MHz", "8 MHz", "12 MHz", "reserved"
1082 };
1083
1084 static void sam4_explain_ckgr_mor(struct sam4_chip *pChip)
1085 {
1086         uint32_t v;
1087         uint32_t rcen;
1088
1089         v = sam4_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
1090         LOG_USER("(main xtal enabled: %s)", _yes_or_no(v));
1091         v = sam4_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
1092         LOG_USER("(main osc bypass: %s)", _yes_or_no(v));
1093         rcen = sam4_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 3, 1);
1094         LOG_USER("(onchip RC-OSC enabled: %s)", _yes_or_no(rcen));
1095         v = sam4_reg_fieldname(pChip, "MOSCRCF", pChip->cfg.CKGR_MOR, 4, 3);
1096         LOG_USER("(onchip RC-OSC freq: %s)", _rc_freq[v]);
1097
1098         pChip->cfg.rc_freq = 0;
1099         if (rcen) {
1100                 switch (v) {
1101                         default:
1102                                 pChip->cfg.rc_freq = 0;
1103                                 break;
1104                         case 0:
1105                                 pChip->cfg.rc_freq = 4 * 1000 * 1000;
1106                                 break;
1107                         case 1:
1108                                 pChip->cfg.rc_freq = 8 * 1000 * 1000;
1109                                 break;
1110                         case 2:
1111                                 pChip->cfg.rc_freq = 12 * 1000 * 1000;
1112                                 break;
1113                 }
1114         }
1115
1116         v = sam4_reg_fieldname(pChip, "MOSCXTST", pChip->cfg.CKGR_MOR, 8, 8);
1117         LOG_USER("(startup clks, time= %f uSecs)",
1118                 ((float)(v * 1000000)) / ((float)(pChip->cfg.slow_freq)));
1119         v = sam4_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
1120         LOG_USER("(mainosc source: %s)",
1121                 v ? "external xtal" : "internal RC");
1122
1123         v = sam4_reg_fieldname(pChip, "CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
1124         LOG_USER("(clock failure enabled: %s)",
1125                 _yes_or_no(v));
1126 }
1127
1128 static void sam4_explain_chipid_cidr(struct sam4_chip *pChip)
1129 {
1130         int x;
1131         uint32_t v;
1132         const char *cp;
1133
1134         sam4_reg_fieldname(pChip, "Version", pChip->cfg.CHIPID_CIDR, 0, 5);
1135         LOG_USER_N("\n");
1136
1137         v = sam4_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
1138         LOG_USER("%s", eproc_names[v]);
1139
1140         v = sam4_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
1141         LOG_USER("%s", nvpsize[v]);
1142
1143         v = sam4_reg_fieldname(pChip, "NVPSIZE2", pChip->cfg.CHIPID_CIDR, 12, 4);
1144         LOG_USER("%s", nvpsize2[v]);
1145
1146         v = sam4_reg_fieldname(pChip, "SRAMSIZE", pChip->cfg.CHIPID_CIDR, 16, 4);
1147         LOG_USER("%s", sramsize[v]);
1148
1149         v = sam4_reg_fieldname(pChip, "ARCH", pChip->cfg.CHIPID_CIDR, 20, 8);
1150         cp = _unknown;
1151         for (x = 0; archnames[x].name; x++) {
1152                 if (v == archnames[x].value) {
1153                         cp = archnames[x].name;
1154                         break;
1155                 }
1156         }
1157
1158         LOG_USER("%s", cp);
1159
1160         v = sam4_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
1161         LOG_USER("%s", nvptype[v]);
1162
1163         v = sam4_reg_fieldname(pChip, "EXTID", pChip->cfg.CHIPID_CIDR, 31, 1);
1164         LOG_USER("(exists: %s)", _yes_or_no(v));
1165 }
1166
1167 static void sam4_explain_ckgr_mcfr(struct sam4_chip *pChip)
1168 {
1169         uint32_t v;
1170
1171         v = sam4_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
1172         LOG_USER("(main ready: %s)", _yes_or_no(v));
1173
1174         v = sam4_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
1175
1176         v = (v * pChip->cfg.slow_freq) / 16;
1177         pChip->cfg.mainosc_freq = v;
1178
1179         LOG_USER("(%3.03f Mhz (%d.%03dkhz slowclk)",
1180                 _tomhz(v),
1181                 pChip->cfg.slow_freq / 1000,
1182                 pChip->cfg.slow_freq % 1000);
1183 }
1184
1185 static void sam4_explain_ckgr_plla(struct sam4_chip *pChip)
1186 {
1187         uint32_t mula, diva;
1188
1189         diva = sam4_reg_fieldname(pChip, "DIVA", pChip->cfg.CKGR_PLLAR, 0, 8);
1190         LOG_USER_N("\n");
1191         mula = sam4_reg_fieldname(pChip, "MULA", pChip->cfg.CKGR_PLLAR, 16, 11);
1192         LOG_USER_N("\n");
1193         pChip->cfg.plla_freq = 0;
1194         if (mula == 0)
1195                 LOG_USER("\tPLLA Freq: (Disabled,mula = 0)");
1196         else if (diva == 0)
1197                 LOG_USER("\tPLLA Freq: (Disabled,diva = 0)");
1198         else if (diva == 1) {
1199                 pChip->cfg.plla_freq = (pChip->cfg.mainosc_freq * (mula + 1));
1200                 LOG_USER("\tPLLA Freq: %3.03f MHz",
1201                         _tomhz(pChip->cfg.plla_freq));
1202         }
1203 }
1204
1205 static void sam4_explain_mckr(struct sam4_chip *pChip)
1206 {
1207         uint32_t css, pres, fin = 0;
1208         int pdiv = 0;
1209         const char *cp = NULL;
1210
1211         css = sam4_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
1212         switch (css & 3) {
1213                 case 0:
1214                         fin = pChip->cfg.slow_freq;
1215                         cp = "slowclk";
1216                         break;
1217                 case 1:
1218                         fin = pChip->cfg.mainosc_freq;
1219                         cp  = "mainosc";
1220                         break;
1221                 case 2:
1222                         fin = pChip->cfg.plla_freq;
1223                         cp  = "plla";
1224                         break;
1225                 case 3:
1226                         if (pChip->cfg.CKGR_UCKR & (1 << 16)) {
1227                                 fin = 480 * 1000 * 1000;
1228                                 cp = "upll";
1229                         } else {
1230                                 fin = 0;
1231                                 cp  = "upll (*ERROR* UPLL is disabled)";
1232                         }
1233                         break;
1234                 default:
1235                         assert(0);
1236                         break;
1237         }
1238
1239         LOG_USER("%s (%3.03f Mhz)",
1240                 cp,
1241                 _tomhz(fin));
1242         pres = sam4_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
1243         switch (pres & 0x07) {
1244                 case 0:
1245                         pdiv = 1;
1246                         cp = "selected clock";
1247                         break;
1248                 case 1:
1249                         pdiv = 2;
1250                         cp = "clock/2";
1251                         break;
1252                 case 2:
1253                         pdiv = 4;
1254                         cp = "clock/4";
1255                         break;
1256                 case 3:
1257                         pdiv = 8;
1258                         cp = "clock/8";
1259                         break;
1260                 case 4:
1261                         pdiv = 16;
1262                         cp = "clock/16";
1263                         break;
1264                 case 5:
1265                         pdiv = 32;
1266                         cp = "clock/32";
1267                         break;
1268                 case 6:
1269                         pdiv = 64;
1270                         cp = "clock/64";
1271                         break;
1272                 case 7:
1273                         pdiv = 6;
1274                         cp = "clock/6";
1275                         break;
1276                 default:
1277                         assert(0);
1278                         break;
1279         }
1280         LOG_USER("(%s)", cp);
1281         fin = fin / pdiv;
1282         /* sam4 has a *SINGLE* clock - */
1283         /* other at91 series parts have divisors for these. */
1284         pChip->cfg.cpu_freq = fin;
1285         pChip->cfg.mclk_freq = fin;
1286         pChip->cfg.fclk_freq = fin;
1287         LOG_USER("\t\tResult CPU Freq: %3.03f",
1288                 _tomhz(fin));
1289 }
1290
1291 #if 0
1292 static struct sam4_chip *target2sam4(struct target *pTarget)
1293 {
1294         struct sam4_chip *pChip;
1295
1296         if (pTarget == NULL)
1297                 return NULL;
1298
1299         pChip = all_sam4_chips;
1300         while (pChip) {
1301                 if (pChip->target == pTarget)
1302                         break;  /* return below */
1303                 else
1304                         pChip = pChip->next;
1305         }
1306         return pChip;
1307 }
1308 #endif
1309
1310 static uint32_t *sam4_get_reg_ptr(struct sam4_cfg *pCfg, const struct sam4_reg_list *pList)
1311 {
1312         /* this function exists to help */
1313         /* keep funky offsetof() errors */
1314         /* and casting from causing bugs */
1315
1316         /* By using prototypes - we can detect what would */
1317         /* be casting errors. */
1318
1319         return (uint32_t *)(void *)(((char *)(pCfg)) + pList->struct_offset);
1320 }
1321
1322
1323 #define SAM4_ENTRY(NAME, FUNC)  { .address = SAM4_ ## NAME, .struct_offset = offsetof( \
1324                                                   struct sam4_cfg, \
1325                                                   NAME), # NAME, FUNC }
1326 static const struct sam4_reg_list sam4_all_regs[] = {
1327         SAM4_ENTRY(CKGR_MOR, sam4_explain_ckgr_mor),
1328         SAM4_ENTRY(CKGR_MCFR, sam4_explain_ckgr_mcfr),
1329         SAM4_ENTRY(CKGR_PLLAR, sam4_explain_ckgr_plla),
1330         SAM4_ENTRY(CKGR_UCKR, NULL),
1331         SAM4_ENTRY(PMC_FSMR, NULL),
1332         SAM4_ENTRY(PMC_FSPR, NULL),
1333         SAM4_ENTRY(PMC_IMR, NULL),
1334         SAM4_ENTRY(PMC_MCKR, sam4_explain_mckr),
1335         SAM4_ENTRY(PMC_PCK0, NULL),
1336         SAM4_ENTRY(PMC_PCK1, NULL),
1337         SAM4_ENTRY(PMC_PCK2, NULL),
1338         SAM4_ENTRY(PMC_PCSR, NULL),
1339         SAM4_ENTRY(PMC_SCSR, NULL),
1340         SAM4_ENTRY(PMC_SR, NULL),
1341         SAM4_ENTRY(CHIPID_CIDR, sam4_explain_chipid_cidr),
1342         SAM4_ENTRY(CHIPID_EXID, NULL),
1343         /* TERMINATE THE LIST */
1344         { .name = NULL }
1345 };
1346 #undef SAM4_ENTRY
1347
1348 static struct sam4_bank_private *get_sam4_bank_private(struct flash_bank *bank)
1349 {
1350         return (struct sam4_bank_private *)(bank->driver_priv);
1351 }
1352
1353 /**
1354  * Given a pointer to where it goes in the structure,
1355  * determine the register name, address from the all registers table.
1356  */
1357 static const struct sam4_reg_list *sam4_GetReg(struct sam4_chip *pChip, uint32_t *goes_here)
1358 {
1359         const struct sam4_reg_list *pReg;
1360
1361         pReg = &(sam4_all_regs[0]);
1362         while (pReg->name) {
1363                 uint32_t *pPossible;
1364
1365                 /* calculate where this one go.. */
1366                 /* it is "possibly" this register. */
1367
1368                 pPossible = ((uint32_t *)(void *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
1369
1370                 /* well? Is it this register */
1371                 if (pPossible == goes_here) {
1372                         /* Jump for joy! */
1373                         return pReg;
1374                 }
1375
1376                 /* next... */
1377                 pReg++;
1378         }
1379         /* This is *TOTAL*PANIC* - we are totally screwed. */
1380         LOG_ERROR("INVALID SAM4 REGISTER");
1381         return NULL;
1382 }
1383
1384 static int sam4_ReadThisReg(struct sam4_chip *pChip, uint32_t *goes_here)
1385 {
1386         const struct sam4_reg_list *pReg;
1387         int r;
1388
1389         pReg = sam4_GetReg(pChip, goes_here);
1390         if (!pReg)
1391                 return ERROR_FAIL;
1392
1393         r = target_read_u32(pChip->target, pReg->address, goes_here);
1394         if (r != ERROR_OK) {
1395                 LOG_ERROR("Cannot read SAM4 register: %s @ 0x%08x, Err: %d",
1396                         pReg->name, (unsigned)(pReg->address), r);
1397         }
1398         return r;
1399 }
1400
1401 static int sam4_ReadAllRegs(struct sam4_chip *pChip)
1402 {
1403         int r;
1404         const struct sam4_reg_list *pReg;
1405
1406         pReg = &(sam4_all_regs[0]);
1407         while (pReg->name) {
1408                 r = sam4_ReadThisReg(pChip,
1409                                 sam4_get_reg_ptr(&(pChip->cfg), pReg));
1410                 if (r != ERROR_OK) {
1411                         LOG_ERROR("Cannot read SAM4 registere: %s @ 0x%08x, Error: %d",
1412                                 pReg->name, ((unsigned)(pReg->address)), r);
1413                         return r;
1414                 }
1415                 pReg++;
1416         }
1417
1418         return ERROR_OK;
1419 }
1420
1421 static int sam4_GetInfo(struct sam4_chip *pChip)
1422 {
1423         const struct sam4_reg_list *pReg;
1424         uint32_t regval;
1425
1426         pReg = &(sam4_all_regs[0]);
1427         while (pReg->name) {
1428                 /* display all regs */
1429                 LOG_DEBUG("Start: %s", pReg->name);
1430                 regval = *sam4_get_reg_ptr(&(pChip->cfg), pReg);
1431                 LOG_USER("%*s: [0x%08x] -> 0x%08x",
1432                         REG_NAME_WIDTH,
1433                         pReg->name,
1434                         pReg->address,
1435                         regval);
1436                 if (pReg->explain_func)
1437                         (*(pReg->explain_func))(pChip);
1438                 LOG_DEBUG("End: %s", pReg->name);
1439                 pReg++;
1440         }
1441         LOG_USER("   rc-osc: %3.03f MHz", _tomhz(pChip->cfg.rc_freq));
1442         LOG_USER("  mainosc: %3.03f MHz", _tomhz(pChip->cfg.mainosc_freq));
1443         LOG_USER("     plla: %3.03f MHz", _tomhz(pChip->cfg.plla_freq));
1444         LOG_USER(" cpu-freq: %3.03f MHz", _tomhz(pChip->cfg.cpu_freq));
1445         LOG_USER("mclk-freq: %3.03f MHz", _tomhz(pChip->cfg.mclk_freq));
1446
1447         LOG_USER(" UniqueId: 0x%08x 0x%08x 0x%08x 0x%08x",
1448                 pChip->cfg.unique_id[0],
1449                 pChip->cfg.unique_id[1],
1450                 pChip->cfg.unique_id[2],
1451                 pChip->cfg.unique_id[3]);
1452
1453         return ERROR_OK;
1454 }
1455
1456 static int sam4_protect_check(struct flash_bank *bank)
1457 {
1458         int r;
1459         uint32_t v[4] = {0};
1460         unsigned x;
1461         struct sam4_bank_private *pPrivate;
1462
1463         LOG_DEBUG("Begin");
1464         if (bank->target->state != TARGET_HALTED) {
1465                 LOG_ERROR("Target not halted");
1466                 return ERROR_TARGET_NOT_HALTED;
1467         }
1468
1469         pPrivate = get_sam4_bank_private(bank);
1470         if (!pPrivate) {
1471                 LOG_ERROR("no private for this bank?");
1472                 return ERROR_FAIL;
1473         }
1474         if (!(pPrivate->probed))
1475                 return ERROR_FLASH_BANK_NOT_PROBED;
1476
1477         r = FLASHD_GetLockBits(pPrivate, v);
1478         if (r != ERROR_OK) {
1479                 LOG_DEBUG("Failed: %d", r);
1480                 return r;
1481         }
1482
1483         for (x = 0; x < pPrivate->nsectors; x++)
1484                 bank->sectors[x].is_protected = (!!(v[x >> 5] & (1 << (x % 32))));
1485         LOG_DEBUG("Done");
1486         return ERROR_OK;
1487 }
1488
1489 FLASH_BANK_COMMAND_HANDLER(sam4_flash_bank_command)
1490 {
1491         struct sam4_chip *pChip;
1492
1493         pChip = all_sam4_chips;
1494
1495         /* is this an existing chip? */
1496         while (pChip) {
1497                 if (pChip->target == bank->target)
1498                         break;
1499                 pChip = pChip->next;
1500         }
1501
1502         if (!pChip) {
1503                 /* this is a *NEW* chip */
1504                 pChip = calloc(1, sizeof(struct sam4_chip));
1505                 if (!pChip) {
1506                         LOG_ERROR("NO RAM!");
1507                         return ERROR_FAIL;
1508                 }
1509                 pChip->target = bank->target;
1510                 /* insert at head */
1511                 pChip->next = all_sam4_chips;
1512                 all_sam4_chips = pChip;
1513                 pChip->target = bank->target;
1514                 /* assumption is this runs at 32khz */
1515                 pChip->cfg.slow_freq = 32768;
1516                 pChip->probed = 0;
1517         }
1518
1519         switch (bank->base) {
1520                 default:
1521                         LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x"
1522                         "[at91sam4s series] )",
1523                         ((unsigned int)(bank->base)),
1524                         ((unsigned int)(FLASH_BANK_BASE_S)));
1525                         return ERROR_FAIL;
1526                         break;
1527
1528                 /* at91sam4s series only has bank 0*/
1529                 case FLASH_BANK_BASE_S:
1530                         bank->driver_priv = &(pChip->details.bank[0]);
1531                         bank->bank_number = 0;
1532                         pChip->details.bank[0].pChip = pChip;
1533                         pChip->details.bank[0].pBank = bank;
1534                         break;
1535         }
1536
1537         /* we initialize after probing. */
1538         return ERROR_OK;
1539 }
1540
1541 static int sam4_GetDetails(struct sam4_bank_private *pPrivate)
1542 {
1543         const struct sam4_chip_details *pDetails;
1544         struct sam4_chip *pChip;
1545         struct flash_bank *saved_banks[SAM4_MAX_FLASH_BANKS];
1546         unsigned x;
1547
1548         LOG_DEBUG("Begin");
1549         pDetails = all_sam4_details;
1550         while (pDetails->name) {
1551                 /* Compare cidr without version bits */
1552                 if (pDetails->chipid_cidr == (pPrivate->pChip->cfg.CHIPID_CIDR & 0xFFFFFFE0))
1553                         break;
1554                 else
1555                         pDetails++;
1556         }
1557         if (pDetails->name == NULL) {
1558                 LOG_ERROR("SAM4 ChipID 0x%08x not found in table (perhaps you can ID this chip?)",
1559                         (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
1560                 /* Help the victim, print details about the chip */
1561                 LOG_INFO("SAM4 CHIPID_CIDR: 0x%08x decodes as follows",
1562                         pPrivate->pChip->cfg.CHIPID_CIDR);
1563                 sam4_explain_chipid_cidr(pPrivate->pChip);
1564                 return ERROR_FAIL;
1565         }
1566
1567         /* DANGER: THERE ARE DRAGONS HERE */
1568
1569         /* get our pChip - it is going */
1570         /* to be over-written shortly */
1571         pChip = pPrivate->pChip;
1572
1573         /* Note that, in reality: */
1574         /*  */
1575         /*     pPrivate = &(pChip->details.bank[0]) */
1576         /* or  pPrivate = &(pChip->details.bank[1]) */
1577         /*  */
1578
1579         /* save the "bank" pointers */
1580         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++)
1581                 saved_banks[x] = pChip->details.bank[x].pBank;
1582
1583         /* Overwrite the "details" structure. */
1584         memcpy(&(pPrivate->pChip->details),
1585                 pDetails,
1586                 sizeof(pPrivate->pChip->details));
1587
1588         /* now fix the ghosted pointers */
1589         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
1590                 pChip->details.bank[x].pChip = pChip;
1591                 pChip->details.bank[x].pBank = saved_banks[x];
1592         }
1593
1594         /* update the *BANK*SIZE* */
1595
1596         LOG_DEBUG("End");
1597         return ERROR_OK;
1598 }
1599
1600 static int _sam4_probe(struct flash_bank *bank, int noise)
1601 {
1602         unsigned x;
1603         int r;
1604         struct sam4_bank_private *pPrivate;
1605
1606
1607         LOG_DEBUG("Begin: Bank: %d, Noise: %d", bank->bank_number, noise);
1608         if (bank->target->state != TARGET_HALTED) {
1609                 LOG_ERROR("Target not halted");
1610                 return ERROR_TARGET_NOT_HALTED;
1611         }
1612
1613         pPrivate = get_sam4_bank_private(bank);
1614         if (!pPrivate) {
1615                 LOG_ERROR("Invalid/unknown bank number");
1616                 return ERROR_FAIL;
1617         }
1618
1619         r = sam4_ReadAllRegs(pPrivate->pChip);
1620         if (r != ERROR_OK)
1621                 return r;
1622
1623         LOG_DEBUG("Here");
1624         if (pPrivate->pChip->probed)
1625                 r = sam4_GetInfo(pPrivate->pChip);
1626         else
1627                 r = sam4_GetDetails(pPrivate);
1628         if (r != ERROR_OK)
1629                 return r;
1630
1631         /* update the flash bank size */
1632         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
1633                 if (bank->base == pPrivate->pChip->details.bank[x].base_address) {
1634                         bank->size = pPrivate->pChip->details.bank[x].size_bytes;
1635                         break;
1636                 }
1637         }
1638
1639         if (bank->sectors == NULL) {
1640                 bank->sectors = calloc(pPrivate->nsectors, (sizeof((bank->sectors)[0])));
1641                 if (bank->sectors == NULL) {
1642                         LOG_ERROR("No memory!");
1643                         return ERROR_FAIL;
1644                 }
1645                 bank->num_sectors = pPrivate->nsectors;
1646
1647                 for (x = 0; ((int)(x)) < bank->num_sectors; x++) {
1648                         bank->sectors[x].size = pPrivate->sector_size;
1649                         bank->sectors[x].offset = x * (pPrivate->sector_size);
1650                         /* mark as unknown */
1651                         bank->sectors[x].is_erased = -1;
1652                         bank->sectors[x].is_protected = -1;
1653                 }
1654         }
1655
1656         pPrivate->probed = 1;
1657
1658         r = sam4_protect_check(bank);
1659         if (r != ERROR_OK)
1660                 return r;
1661
1662         LOG_DEBUG("Bank = %d, nbanks = %d",
1663                 pPrivate->bank_number, pPrivate->pChip->details.n_banks);
1664         if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
1665                 /* read unique id, */
1666                 /* it appears to be associated with the *last* flash bank. */
1667                 FLASHD_ReadUniqueID(pPrivate);
1668         }
1669
1670         return r;
1671 }
1672
1673 static int sam4_probe(struct flash_bank *bank)
1674 {
1675         return _sam4_probe(bank, 1);
1676 }
1677
1678 static int sam4_auto_probe(struct flash_bank *bank)
1679 {
1680         return _sam4_probe(bank, 0);
1681 }
1682
1683 static int sam4_erase(struct flash_bank *bank, int first, int last)
1684 {
1685         struct sam4_bank_private *pPrivate;
1686         int r;
1687         int i;
1688         int pageCount;
1689         /*16 pages equals 8KB - Same size as a lock region*/
1690         pageCount = 16;
1691         uint32_t status;
1692
1693         LOG_DEBUG("Here");
1694         if (bank->target->state != TARGET_HALTED) {
1695                 LOG_ERROR("Target not halted");
1696                 return ERROR_TARGET_NOT_HALTED;
1697         }
1698
1699         r = sam4_auto_probe(bank);
1700         if (r != ERROR_OK) {
1701                 LOG_DEBUG("Here,r=%d", r);
1702                 return r;
1703         }
1704
1705         pPrivate = get_sam4_bank_private(bank);
1706         if (!(pPrivate->probed))
1707                 return ERROR_FLASH_BANK_NOT_PROBED;
1708
1709         if ((first == 0) && ((last + 1) == ((int)(pPrivate->nsectors)))) {
1710                 /* whole chip */
1711                 LOG_DEBUG("Here");
1712                 return FLASHD_EraseEntireBank(pPrivate);
1713         }
1714         LOG_INFO("sam4 does not auto-erase while programing (Erasing relevant sectors)");
1715         LOG_INFO("sam4 First: 0x%08x Last: 0x%08x", (unsigned int)(first), (unsigned int)(last));
1716         for (i = first; i <= last; i++) {
1717                 /*16 pages equals 8KB - Same size as a lock region*/
1718                 r = FLASHD_ErasePages(pPrivate, (i * pageCount), pageCount, &status);
1719                 LOG_INFO("Erasing sector: 0x%08x", (unsigned int)(i));
1720                 if (r != ERROR_OK)
1721                         LOG_ERROR("SAM4: Error performing Erase page @ lock region number %d",
1722                                 (unsigned int)(i));
1723                 if (status & (1 << 2)) {
1724                         LOG_ERROR("SAM4: Lock Reqion %d is locked", (unsigned int)(i));
1725                         return ERROR_FAIL;
1726                 }
1727                 if (status & (1 << 1)) {
1728                         LOG_ERROR("SAM4: Flash Command error @lock region %d", (unsigned int)(i));
1729                         return ERROR_FAIL;
1730                 }
1731         }
1732
1733         return ERROR_OK;
1734 }
1735
1736 static int sam4_protect(struct flash_bank *bank, int set, int first, int last)
1737 {
1738         struct sam4_bank_private *pPrivate;
1739         int r;
1740
1741         LOG_DEBUG("Here");
1742         if (bank->target->state != TARGET_HALTED) {
1743                 LOG_ERROR("Target not halted");
1744                 return ERROR_TARGET_NOT_HALTED;
1745         }
1746
1747         pPrivate = get_sam4_bank_private(bank);
1748         if (!(pPrivate->probed))
1749                 return ERROR_FLASH_BANK_NOT_PROBED;
1750
1751         if (set)
1752                 r = FLASHD_Lock(pPrivate, (unsigned)(first), (unsigned)(last));
1753         else
1754                 r = FLASHD_Unlock(pPrivate, (unsigned)(first), (unsigned)(last));
1755         LOG_DEBUG("End: r=%d", r);
1756
1757         return r;
1758
1759 }
1760
1761 static int sam4_info(struct flash_bank *bank, char *buf, int buf_size)
1762 {
1763         if (bank->target->state != TARGET_HALTED) {
1764                 LOG_ERROR("Target not halted");
1765                 return ERROR_TARGET_NOT_HALTED;
1766         }
1767         buf[0] = 0;
1768         return ERROR_OK;
1769 }
1770
1771 static int sam4_page_read(struct sam4_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
1772 {
1773         uint32_t adr;
1774         int r;
1775
1776         adr = pagenum * pPrivate->page_size;
1777         adr = adr + pPrivate->base_address;
1778
1779         r = target_read_memory(pPrivate->pChip->target,
1780                         adr,
1781                         4,                                      /* THIS*MUST*BE* in 32bit values */
1782                         pPrivate->page_size / 4,
1783                         buf);
1784         if (r != ERROR_OK)
1785                 LOG_ERROR("SAM4: Flash program failed to read page phys address: 0x%08x",
1786                         (unsigned int)(adr));
1787         return r;
1788 }
1789
1790 /* The code below is basically this: */
1791 /* compiled with */
1792 /* arm-none-eabi-gcc -mthumb -mcpu = cortex-m3 -O9 -S ./foobar.c -o foobar.s */
1793 /*  */
1794 /* Only the *CPU* can write to the flash buffer. */
1795 /* the DAP cannot... so - we download this 28byte thing */
1796 /* Run the algorithm - (below) */
1797 /* to program the device */
1798 /*  */
1799 /* ======================================== */
1800 /* #include <stdint.h> */
1801 /*  */
1802 /* struct foo { */
1803 /*   uint32_t *dst; */
1804 /*   const uint32_t *src; */
1805 /*   int   n; */
1806 /*   volatile uint32_t *base; */
1807 /*   uint32_t   cmd; */
1808 /* }; */
1809 /*  */
1810 /*  */
1811 /* uint32_t sam4_function(struct foo *p) */
1812 /* { */
1813 /*   volatile uint32_t *v; */
1814 /*   uint32_t *d; */
1815 /*   const uint32_t *s; */
1816 /*   int   n; */
1817 /*   uint32_t r; */
1818 /*  */
1819 /*   d = p->dst; */
1820 /*   s = p->src; */
1821 /*   n = p->n; */
1822 /*  */
1823 /*   do { */
1824 /*     *d++ = *s++; */
1825 /*   } while (--n) */
1826 /*     ; */
1827 /*  */
1828 /*   v = p->base; */
1829 /*  */
1830 /*   v[ 1 ] = p->cmd; */
1831 /*   do { */
1832 /*     r = v[8/4]; */
1833 /*   } while (!(r&1)) */
1834 /*     ; */
1835 /*   return r; */
1836 /* } */
1837 /* ======================================== */
1838
1839 static const uint8_t
1840         sam4_page_write_opcodes[] = {
1841         /*  24 0000 0446                mov     r4, r0 */
1842         0x04, 0x46,
1843         /*  25 0002 6168                ldr     r1, [r4, #4] */
1844         0x61, 0x68,
1845         /*  26 0004 0068                ldr     r0, [r0, #0] */
1846         0x00, 0x68,
1847         /*  27 0006 A268                ldr     r2, [r4, #8] */
1848         0xa2, 0x68,
1849         /*  28                          @ lr needed for prologue */
1850         /*  29                  .L2: */
1851         /*  30 0008 51F8043B            ldr     r3, [r1], #4 */
1852         0x51, 0xf8, 0x04, 0x3b,
1853         /*  31 000c 12F1FF32            adds    r2, r2, #-1 */
1854         0x12, 0xf1, 0xff, 0x32,
1855         /*  32 0010 40F8043B            str     r3, [r0], #4 */
1856         0x40, 0xf8, 0x04, 0x3b,
1857         /*  33 0014 F8D1                bne     .L2 */
1858         0xf8, 0xd1,
1859         /*  34 0016 E268                ldr     r2, [r4, #12] */
1860         0xe2, 0x68,
1861         /*  35 0018 2369                ldr     r3, [r4, #16] */
1862         0x23, 0x69,
1863         /*  36 001a 5360                str     r3, [r2, #4] */
1864         0x53, 0x60,
1865         /*  37 001c 0832                adds    r2, r2, #8 */
1866         0x08, 0x32,
1867         /*  38                  .L4: */
1868         /*  39 001e 1068                ldr     r0, [r2, #0] */
1869         0x10, 0x68,
1870         /*  40 0020 10F0010F            tst     r0, #1 */
1871         0x10, 0xf0, 0x01, 0x0f,
1872         /*  41 0024 FBD0                beq     .L4 */
1873         0xfb, 0xd0,
1874         0x00, 0xBE                              /* bkpt #0 */
1875 };
1876
1877 static int sam4_page_write(struct sam4_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
1878 {
1879         uint32_t adr;
1880         uint32_t status;
1881         uint32_t fmr;   /* EEFC Flash Mode Register */
1882         int r;
1883
1884         adr = pagenum * pPrivate->page_size;
1885         adr = (adr + pPrivate->base_address);
1886
1887         /* Get flash mode register value */
1888         r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address, &fmr);
1889         if (r != ERROR_OK)
1890                 LOG_DEBUG("Error Read failed: read flash mode register");
1891
1892         /* Clear flash wait state field */
1893         fmr &= 0xfffff0ff;
1894
1895         /* set FWS (flash wait states) field in the FMR (flash mode register) */
1896         fmr |= (pPrivate->flash_wait_states << 8);
1897
1898         LOG_DEBUG("Flash Mode: 0x%08x", ((unsigned int)(fmr)));
1899         r = target_write_u32(pPrivate->pBank->target, pPrivate->controller_address, fmr);
1900         if (r != ERROR_OK)
1901                 LOG_DEBUG("Error Write failed: set flash mode register");
1902
1903         /* 1st sector 8kBytes - page 0 - 15*/
1904         /* 2nd sector 8kBytes - page 16 - 30*/
1905         /* 3rd sector 48kBytes - page 31 - 127*/
1906         LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
1907         r = target_write_memory(pPrivate->pChip->target,
1908                         adr,
1909                         4,                                      /* THIS*MUST*BE* in 32bit values */
1910                         pPrivate->page_size / 4,
1911                         buf);
1912         if (r != ERROR_OK) {
1913                 LOG_ERROR("SAM4: Failed to write (buffer) page at phys address 0x%08x",
1914                         (unsigned int)(adr));
1915                 return r;
1916         }
1917
1918         r = EFC_PerformCommand(pPrivate,
1919                         /* send Erase & Write Page */
1920                         AT91C_EFC_FCMD_WP,      /*AT91C_EFC_FCMD_EWP only works on first two 8kb sectors*/
1921                         pagenum,
1922                         &status);
1923
1924         if (r != ERROR_OK)
1925                 LOG_ERROR("SAM4: Error performing Write page @ phys address 0x%08x",
1926                         (unsigned int)(adr));
1927         if (status & (1 << 2)) {
1928                 LOG_ERROR("SAM4: Page @ Phys address 0x%08x is locked", (unsigned int)(adr));
1929                 return ERROR_FAIL;
1930         }
1931         if (status & (1 << 1)) {
1932                 LOG_ERROR("SAM4: Flash Command error @phys address 0x%08x", (unsigned int)(adr));
1933                 return ERROR_FAIL;
1934         }
1935         return ERROR_OK;
1936 }
1937
1938 static int sam4_write(struct flash_bank *bank,
1939         uint8_t *buffer,
1940         uint32_t offset,
1941         uint32_t count)
1942 {
1943         int n;
1944         unsigned page_cur;
1945         unsigned page_end;
1946         int r;
1947         unsigned page_offset;
1948         struct sam4_bank_private *pPrivate;
1949         uint8_t *pagebuffer;
1950
1951         /* incase we bail further below, set this to null */
1952         pagebuffer = NULL;
1953
1954         /* ignore dumb requests */
1955         if (count == 0) {
1956                 r = ERROR_OK;
1957                 goto done;
1958         }
1959
1960         if (bank->target->state != TARGET_HALTED) {
1961                 LOG_ERROR("Target not halted");
1962                 r = ERROR_TARGET_NOT_HALTED;
1963                 goto done;
1964         }
1965
1966         pPrivate = get_sam4_bank_private(bank);
1967         if (!(pPrivate->probed)) {
1968                 r = ERROR_FLASH_BANK_NOT_PROBED;
1969                 goto done;
1970         }
1971
1972         if ((offset + count) > pPrivate->size_bytes) {
1973                 LOG_ERROR("Flash write error - past end of bank");
1974                 LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
1975                         (unsigned int)(offset),
1976                         (unsigned int)(count),
1977                         (unsigned int)(pPrivate->size_bytes));
1978                 r = ERROR_FAIL;
1979                 goto done;
1980         }
1981
1982         pagebuffer = malloc(pPrivate->page_size);
1983         if (!pagebuffer) {
1984                 LOG_ERROR("No memory for %d Byte page buffer", (int)(pPrivate->page_size));
1985                 r = ERROR_FAIL;
1986                 goto done;
1987         }
1988
1989         /* what page do we start & end in? */
1990         page_cur = offset / pPrivate->page_size;
1991         page_end = (offset + count - 1) / pPrivate->page_size;
1992
1993         LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
1994         LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
1995
1996         /* Special case: all one page */
1997         /*  */
1998         /* Otherwise: */
1999         /*    (1) non-aligned start */
2000         /*    (2) body pages */
2001         /*    (3) non-aligned end. */
2002
2003         /* Handle special case - all one page. */
2004         if (page_cur == page_end) {
2005                 LOG_DEBUG("Special case, all in one page");
2006                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2007                 if (r != ERROR_OK)
2008                         goto done;
2009
2010                 page_offset = (offset & (pPrivate->page_size-1));
2011                 memcpy(pagebuffer + page_offset,
2012                         buffer,
2013                         count);
2014
2015                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2016                 if (r != ERROR_OK)
2017                         goto done;
2018                 r = ERROR_OK;
2019                 goto done;
2020         }
2021
2022         /* non-aligned start */
2023         page_offset = offset & (pPrivate->page_size - 1);
2024         if (page_offset) {
2025                 LOG_DEBUG("Not-Aligned start");
2026                 /* read the partial */
2027                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2028                 if (r != ERROR_OK)
2029                         goto done;
2030
2031                 /* over-write with new data */
2032                 n = (pPrivate->page_size - page_offset);
2033                 memcpy(pagebuffer + page_offset,
2034                         buffer,
2035                         n);
2036
2037                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2038                 if (r != ERROR_OK)
2039                         goto done;
2040
2041                 count  -= n;
2042                 offset += n;
2043                 buffer += n;
2044                 page_cur++;
2045         }
2046
2047         /* By checking that offset is correct here, we also
2048         fix a clang warning */
2049         assert(offset % pPrivate->page_size == 0);
2050
2051         /* intermediate large pages */
2052         /* also - the final *terminal* */
2053         /* if that terminal page is a full page */
2054         LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
2055                 (int)page_cur, (int)page_end, (unsigned int)(count));
2056
2057         while ((page_cur < page_end) &&
2058                         (count >= pPrivate->page_size)) {
2059                 r = sam4_page_write(pPrivate, page_cur, buffer);
2060                 if (r != ERROR_OK)
2061                         goto done;
2062                 count -= pPrivate->page_size;
2063                 buffer += pPrivate->page_size;
2064                 page_cur += 1;
2065         }
2066
2067         /* terminal partial page? */
2068         if (count) {
2069                 LOG_DEBUG("Terminal partial page, count = 0x%08x", (unsigned int)(count));
2070                 /* we have a partial page */
2071                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2072                 if (r != ERROR_OK)
2073                         goto done;
2074                                         /* data goes at start */
2075                 memcpy(pagebuffer, buffer, count);
2076                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2077                 if (r != ERROR_OK)
2078                         goto done;
2079         }
2080         LOG_DEBUG("Done!");
2081         r = ERROR_OK;
2082 done:
2083         if (pagebuffer)
2084                 free(pagebuffer);
2085         return r;
2086 }
2087
2088 COMMAND_HANDLER(sam4_handle_info_command)
2089 {
2090         struct sam4_chip *pChip;
2091         pChip = get_current_sam4(CMD_CTX);
2092         if (!pChip)
2093                 return ERROR_OK;
2094
2095         unsigned x;
2096         int r;
2097
2098         /* bank0 must exist before we can do anything */
2099         if (pChip->details.bank[0].pBank == NULL) {
2100                 x = 0;
2101 need_define:
2102                 command_print(CMD_CTX,
2103                         "Please define bank %d via command: flash bank %s ... ",
2104                         x,
2105                         at91sam4_flash.name);
2106                 return ERROR_FAIL;
2107         }
2108
2109         /* if bank 0 is not probed, then probe it */
2110         if (!(pChip->details.bank[0].probed)) {
2111                 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2112                 if (r != ERROR_OK)
2113                         return ERROR_FAIL;
2114         }
2115         /* above guarantees the "chip details" structure is valid */
2116         /* and thus, bank private areas are valid */
2117         /* and we have a SAM4 chip, what a concept! */
2118
2119         /* auto-probe other banks, 0 done above */
2120         for (x = 1; x < SAM4_MAX_FLASH_BANKS; x++) {
2121                 /* skip banks not present */
2122                 if (!(pChip->details.bank[x].present))
2123                         continue;
2124
2125                 if (pChip->details.bank[x].pBank == NULL)
2126                         goto need_define;
2127
2128                 if (pChip->details.bank[x].probed)
2129                         continue;
2130
2131                 r = sam4_auto_probe(pChip->details.bank[x].pBank);
2132                 if (r != ERROR_OK)
2133                         return r;
2134         }
2135
2136         r = sam4_GetInfo(pChip);
2137         if (r != ERROR_OK) {
2138                 LOG_DEBUG("Sam4Info, Failed %d", r);
2139                 return r;
2140         }
2141
2142         return ERROR_OK;
2143 }
2144
2145 COMMAND_HANDLER(sam4_handle_gpnvm_command)
2146 {
2147         unsigned x, v;
2148         int r, who;
2149         struct sam4_chip *pChip;
2150
2151         pChip = get_current_sam4(CMD_CTX);
2152         if (!pChip)
2153                 return ERROR_OK;
2154
2155         if (pChip->target->state != TARGET_HALTED) {
2156                 LOG_ERROR("sam4 - target not halted");
2157                 return ERROR_TARGET_NOT_HALTED;
2158         }
2159
2160         if (pChip->details.bank[0].pBank == NULL) {
2161                 command_print(CMD_CTX, "Bank0 must be defined first via: flash bank %s ...",
2162                         at91sam4_flash.name);
2163                 return ERROR_FAIL;
2164         }
2165         if (!pChip->details.bank[0].probed) {
2166                 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2167                 if (r != ERROR_OK)
2168                         return r;
2169         }
2170
2171         switch (CMD_ARGC) {
2172                 default:
2173                         return ERROR_COMMAND_SYNTAX_ERROR;
2174                         break;
2175                 case 0:
2176                         goto showall;
2177                         break;
2178                 case 1:
2179                         who = -1;
2180                         break;
2181                 case 2:
2182                         if ((0 == strcmp(CMD_ARGV[0], "show")) && (0 == strcmp(CMD_ARGV[1], "all")))
2183                                 who = -1;
2184                         else {
2185                                 uint32_t v32;
2186                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], v32);
2187                                 who = v32;
2188                         }
2189                         break;
2190         }
2191
2192         if (0 == strcmp("show", CMD_ARGV[0])) {
2193                 if (who == -1) {
2194 showall:
2195                         r = ERROR_OK;
2196                         for (x = 0; x < pChip->details.n_gpnvms; x++) {
2197                                 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
2198                                 if (r != ERROR_OK)
2199                                         break;
2200                                 command_print(CMD_CTX, "sam4-gpnvm%u: %u", x, v);
2201                         }
2202                         return r;
2203                 }
2204                 if ((who >= 0) && (((unsigned)(who)) < pChip->details.n_gpnvms)) {
2205                         r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), who, &v);
2206                         command_print(CMD_CTX, "sam4-gpnvm%u: %u", who, v);
2207                         return r;
2208                 } else {
2209                         command_print(CMD_CTX, "sam4-gpnvm invalid GPNVM: %u", who);
2210                         return ERROR_COMMAND_SYNTAX_ERROR;
2211                 }
2212         }
2213
2214         if (who == -1) {
2215                 command_print(CMD_CTX, "Missing GPNVM number");
2216                 return ERROR_COMMAND_SYNTAX_ERROR;
2217         }
2218
2219         if (0 == strcmp("set", CMD_ARGV[0]))
2220                 r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
2221         else if ((0 == strcmp("clr", CMD_ARGV[0])) ||
2222                  (0 == strcmp("clear", CMD_ARGV[0])))                   /* quietly accept both */
2223                 r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
2224         else {
2225                 command_print(CMD_CTX, "Unknown command: %s", CMD_ARGV[0]);
2226                 r = ERROR_COMMAND_SYNTAX_ERROR;
2227         }
2228         return r;
2229 }
2230
2231 COMMAND_HANDLER(sam4_handle_slowclk_command)
2232 {
2233         struct sam4_chip *pChip;
2234
2235         pChip = get_current_sam4(CMD_CTX);
2236         if (!pChip)
2237                 return ERROR_OK;
2238
2239         switch (CMD_ARGC) {
2240                 case 0:
2241                         /* show */
2242                         break;
2243                 case 1:
2244                 {
2245                         /* set */
2246                         uint32_t v;
2247                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], v);
2248                         if (v > 200000) {
2249                                 /* absurd slow clock of 200Khz? */
2250                                 command_print(CMD_CTX, "Absurd/illegal slow clock freq: %d\n", (int)(v));
2251                                 return ERROR_COMMAND_SYNTAX_ERROR;
2252                         }
2253                         pChip->cfg.slow_freq = v;
2254                         break;
2255                 }
2256                 default:
2257                         /* error */
2258                         command_print(CMD_CTX, "Too many parameters");
2259                         return ERROR_COMMAND_SYNTAX_ERROR;
2260                         break;
2261         }
2262         command_print(CMD_CTX, "Slowclk freq: %d.%03dkhz",
2263                 (int)(pChip->cfg.slow_freq / 1000),
2264                 (int)(pChip->cfg.slow_freq % 1000));
2265         return ERROR_OK;
2266 }
2267
2268 static const struct command_registration at91sam4_exec_command_handlers[] = {
2269         {
2270                 .name = "gpnvm",
2271                 .handler = sam4_handle_gpnvm_command,
2272                 .mode = COMMAND_EXEC,
2273                 .usage = "[('clr'|'set'|'show') bitnum]",
2274                 .help = "Without arguments, shows all bits in the gpnvm "
2275                         "register.  Otherwise, clears, sets, or shows one "
2276                         "General Purpose Non-Volatile Memory (gpnvm) bit.",
2277         },
2278         {
2279                 .name = "info",
2280                 .handler = sam4_handle_info_command,
2281                 .mode = COMMAND_EXEC,
2282                 .help = "Print information about the current at91sam4 chip"
2283                         "and its flash configuration.",
2284         },
2285         {
2286                 .name = "slowclk",
2287                 .handler = sam4_handle_slowclk_command,
2288                 .mode = COMMAND_EXEC,
2289                 .usage = "[clock_hz]",
2290                 .help = "Display or set the slowclock frequency "
2291                         "(default 32768 Hz).",
2292         },
2293         COMMAND_REGISTRATION_DONE
2294 };
2295 static const struct command_registration at91sam4_command_handlers[] = {
2296         {
2297                 .name = "at91sam4",
2298                 .mode = COMMAND_ANY,
2299                 .help = "at91sam4 flash command group",
2300                 .usage = "",
2301                 .chain = at91sam4_exec_command_handlers,
2302         },
2303         COMMAND_REGISTRATION_DONE
2304 };
2305
2306 struct flash_driver at91sam4_flash = {
2307         .name = "at91sam4",
2308         .commands = at91sam4_command_handlers,
2309         .flash_bank_command = sam4_flash_bank_command,
2310         .erase = sam4_erase,
2311         .protect = sam4_protect,
2312         .write = sam4_write,
2313         .read = default_flash_read,
2314         .probe = sam4_probe,
2315         .auto_probe = sam4_auto_probe,
2316         .erase_check = default_flash_blank_check,
2317         .protect_check = sam4_protect_check,
2318         .info = sam4_info,
2319 };