fd98b7f0da850370e77d91add82cb5ce4d0e78f4
[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         return EFC_PerformCommand(pPrivate,
726                 /* send Erase Page */
727                 AT91C_EFC_FCMD_EPA,
728                 (firstPage << 2) | erasePages,
729                 status);
730 }
731
732 /**
733  * Gets current GPNVM state.
734  * @param pPrivate - info about the bank.
735  * @param gpnvm    -  GPNVM bit index.
736  * @param puthere  - result stored here.
737  */
738 /* ------------------------------------------------------------------------------ */
739 static int FLASHD_GetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm, unsigned *puthere)
740 {
741         uint32_t v;
742         int r;
743
744         LOG_DEBUG("Here");
745         if (pPrivate->bank_number != 0) {
746                 LOG_ERROR("GPNVM only works with Bank0");
747                 return ERROR_FAIL;
748         }
749
750         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
751                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
752                         gpnvm, pPrivate->pChip->details.n_gpnvms);
753                 return ERROR_FAIL;
754         }
755
756         /* Get GPNVMs status */
757         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GFB, 0, NULL);
758         if (r != ERROR_OK) {
759                 LOG_ERROR("Failed");
760                 return r;
761         }
762
763         r = EFC_GetResult(pPrivate, &v);
764
765         if (puthere) {
766                 /* Check if GPNVM is set */
767                 /* get the bit and make it a 0/1 */
768                 *puthere = (v >> gpnvm) & 1;
769         }
770
771         return r;
772 }
773
774 /**
775  * Clears the selected GPNVM bit.
776  * @param pPrivate info about the bank
777  * @param gpnvm GPNVM index.
778  * @returns 0 if successful; otherwise returns an error code.
779  */
780 static int FLASHD_ClrGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
781 {
782         int r;
783         unsigned v;
784
785         LOG_DEBUG("Here");
786         if (pPrivate->bank_number != 0) {
787                 LOG_ERROR("GPNVM only works with Bank0");
788                 return ERROR_FAIL;
789         }
790
791         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
792                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
793                         gpnvm, pPrivate->pChip->details.n_gpnvms);
794                 return ERROR_FAIL;
795         }
796
797         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
798         if (r != ERROR_OK) {
799                 LOG_DEBUG("Failed: %d", r);
800                 return r;
801         }
802         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CFB, gpnvm, NULL);
803         LOG_DEBUG("End: %d", r);
804         return r;
805 }
806
807 /**
808  * Sets the selected GPNVM bit.
809  * @param pPrivate info about the bank
810  * @param gpnvm GPNVM index.
811  */
812 static int FLASHD_SetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
813 {
814         int r;
815         unsigned v;
816
817         if (pPrivate->bank_number != 0) {
818                 LOG_ERROR("GPNVM only works with Bank0");
819                 return ERROR_FAIL;
820         }
821
822         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
823                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
824                         gpnvm, pPrivate->pChip->details.n_gpnvms);
825                 return ERROR_FAIL;
826         }
827
828         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
829         if (r != ERROR_OK)
830                 return r;
831         if (v) {
832                 /* already set */
833                 r = ERROR_OK;
834         } else {
835                 /* set it */
836                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SFB, gpnvm, NULL);
837         }
838         return r;
839 }
840
841 /**
842  * Returns a bit field (at most 64) of locked regions within a page.
843  * @param pPrivate info about the bank
844  * @param v where to store locked bits
845  */
846 static int FLASHD_GetLockBits(struct sam4_bank_private *pPrivate, uint32_t *v)
847 {
848         int r;
849         LOG_DEBUG("Here");
850         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GLB, 0, NULL);
851         if (r == ERROR_OK)      {
852                 EFC_GetResult(pPrivate, v);
853                 EFC_GetResult(pPrivate, v);
854                 EFC_GetResult(pPrivate, v);
855                 r = EFC_GetResult(pPrivate, v);
856         }
857         LOG_DEBUG("End: %d", r);
858         return r;
859 }
860
861 /**
862  * Unlocks all the regions in the given address range.
863  * @param pPrivate info about the bank
864  * @param start_sector first sector to unlock
865  * @param end_sector last (inclusive) to unlock
866  */
867
868 static int FLASHD_Unlock(struct sam4_bank_private *pPrivate,
869         unsigned start_sector,
870         unsigned end_sector)
871 {
872         int r;
873         uint32_t status;
874         uint32_t pg;
875         uint32_t pages_per_sector;
876
877         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
878
879         /* Unlock all pages */
880         while (start_sector <= end_sector) {
881                 pg = start_sector * pages_per_sector;
882
883                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CLB, pg, &status);
884                 if (r != ERROR_OK)
885                         return r;
886                 start_sector++;
887         }
888
889         return ERROR_OK;
890 }
891
892 /**
893  * Locks regions
894  * @param pPrivate - info about the bank
895  * @param start_sector - first sector to lock
896  * @param end_sector   - last sector (inclusive) to lock
897  */
898 static int FLASHD_Lock(struct sam4_bank_private *pPrivate,
899         unsigned start_sector,
900         unsigned end_sector)
901 {
902         uint32_t status;
903         uint32_t pg;
904         uint32_t pages_per_sector;
905         int r;
906
907         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
908
909         /* Lock all pages */
910         while (start_sector <= end_sector) {
911                 pg = start_sector * pages_per_sector;
912
913                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SLB, pg, &status);
914                 if (r != ERROR_OK)
915                         return r;
916                 start_sector++;
917         }
918         return ERROR_OK;
919 }
920
921 /****** END SAM4 CODE ********/
922
923 /* begin helpful debug code */
924 /* print the fieldname, the field value, in dec & hex, and return field value */
925 static uint32_t sam4_reg_fieldname(struct sam4_chip *pChip,
926         const char *regname,
927         uint32_t value,
928         unsigned shift,
929         unsigned width)
930 {
931         uint32_t v;
932         int hwidth, dwidth;
933
934
935         /* extract the field */
936         v = value >> shift;
937         v = v & ((1 << width)-1);
938         if (width <= 16) {
939                 hwidth = 4;
940                 dwidth = 5;
941         } else {
942                 hwidth = 8;
943                 dwidth = 12;
944         }
945
946         /* show the basics */
947         LOG_USER_N("\t%*s: %*d [0x%0*x] ",
948                 REG_NAME_WIDTH, regname,
949                 dwidth, v,
950                 hwidth, v);
951         return v;
952 }
953
954 static const char _unknown[] = "unknown";
955 static const char *const eproc_names[] = {
956         _unknown,                                       /* 0 */
957         "arm946es",                                     /* 1 */
958         "arm7tdmi",                                     /* 2 */
959         "cortex-m3",                            /* 3 */
960         "arm920t",                                      /* 4 */
961         "arm926ejs",                            /* 5 */
962         "cortex-a5",                            /* 6 */
963         "cortex-m4",                            /* 7 */
964         _unknown,                                       /* 8 */
965         _unknown,                                       /* 9 */
966         _unknown,                                       /* 10 */
967         _unknown,                                       /* 11 */
968         _unknown,                                       /* 12 */
969         _unknown,                                       /* 13 */
970         _unknown,                                       /* 14 */
971         _unknown,                                       /* 15 */
972 };
973
974 #define nvpsize2 nvpsize                /* these two tables are identical */
975 static const char *const nvpsize[] = {
976         "none",                                         /*  0 */
977         "8K bytes",                                     /*  1 */
978         "16K bytes",                            /*  2 */
979         "32K bytes",                            /*  3 */
980         _unknown,                                       /*  4 */
981         "64K bytes",                            /*  5 */
982         _unknown,                                       /*  6 */
983         "128K bytes",                           /*  7 */
984         _unknown,                                       /*  8 */
985         "256K bytes",                           /*  9 */
986         "512K bytes",                           /* 10 */
987         _unknown,                                       /* 11 */
988         "1024K bytes",                          /* 12 */
989         _unknown,                                       /* 13 */
990         "2048K bytes",                          /* 14 */
991         _unknown,                                       /* 15 */
992 };
993
994 static const char *const sramsize[] = {
995         "48K Bytes",                            /*  0 */
996         "1K Bytes",                                     /*  1 */
997         "2K Bytes",                                     /*  2 */
998         "6K Bytes",                                     /*  3 */
999         "112K Bytes",                           /*  4 */
1000         "4K Bytes",                                     /*  5 */
1001         "80K Bytes",                            /*  6 */
1002         "160K Bytes",                           /*  7 */
1003         "8K Bytes",                                     /*  8 */
1004         "16K Bytes",                            /*  9 */
1005         "32K Bytes",                            /* 10 */
1006         "64K Bytes",                            /* 11 */
1007         "128K Bytes",                           /* 12 */
1008         "256K Bytes",                           /* 13 */
1009         "96K Bytes",                            /* 14 */
1010         "512K Bytes",                           /* 15 */
1011
1012 };
1013
1014 static const struct archnames { unsigned value; const char *name; } archnames[] = {
1015         { 0x19,  "AT91SAM9xx Series"                                            },
1016         { 0x29,  "AT91SAM9XExx Series"                                          },
1017         { 0x34,  "AT91x34 Series"                                                       },
1018         { 0x37,  "CAP7 Series"                                                          },
1019         { 0x39,  "CAP9 Series"                                                          },
1020         { 0x3B,  "CAP11 Series"                                                         },
1021         { 0x40,  "AT91x40 Series"                                                       },
1022         { 0x42,  "AT91x42 Series"                                                       },
1023         { 0x55,  "AT91x55 Series"                                                       },
1024         { 0x60,  "AT91SAM7Axx Series"                                           },
1025         { 0x61,  "AT91SAM7AQxx Series"                                          },
1026         { 0x63,  "AT91x63 Series"                                                       },
1027         { 0x70,  "AT91SAM7Sxx Series"                                           },
1028         { 0x71,  "AT91SAM7XCxx Series"                                          },
1029         { 0x72,  "AT91SAM7SExx Series"                                          },
1030         { 0x73,  "AT91SAM7Lxx Series"                                           },
1031         { 0x75,  "AT91SAM7Xxx Series"                                           },
1032         { 0x76,  "AT91SAM7SLxx Series"                                          },
1033         { 0x80,  "ATSAM3UxC Series (100-pin version)"           },
1034         { 0x81,  "ATSAM3UxE Series (144-pin version)"           },
1035         { 0x83,  "ATSAM3A/SAM4A xC Series (100-pin version)"},
1036         { 0x84,  "ATSAM3X/SAM4X xC Series (100-pin version)"},
1037         { 0x85,  "ATSAM3X/SAM4X xE Series (144-pin version)"},
1038         { 0x86,  "ATSAM3X/SAM4X xG Series (208/217-pin version)"        },
1039         { 0x88,  "ATSAM3S/SAM4S xA Series (48-pin version)"     },
1040         { 0x89,  "ATSAM3S/SAM4S xB Series (64-pin version)"     },
1041         { 0x8A,  "ATSAM3S/SAM4S xC Series (100-pin version)"},
1042         { 0x92,  "AT91x92 Series"                                                       },
1043         { 0x93,  "ATSAM3NxA Series (48-pin version)"            },
1044         { 0x94,  "ATSAM3NxB Series (64-pin version)"            },
1045         { 0x95,  "ATSAM3NxC Series (100-pin version)"           },
1046         { 0x98,  "ATSAM3SDxA Series (48-pin version)"           },
1047         { 0x99,  "ATSAM3SDxB Series (64-pin version)"           },
1048         { 0x9A,  "ATSAM3SDxC Series (100-pin version)"          },
1049         { 0xA5,  "ATSAM5A"                                                              },
1050         { 0xF0,  "AT75Cxx Series"                                                       },
1051         { -1, NULL },
1052 };
1053
1054 static const char *const nvptype[] = {
1055         "rom",  /* 0 */
1056         "romless or onchip flash",      /* 1 */
1057         "embedded flash memory",/* 2 */
1058         "rom(nvpsiz) + embedded flash (nvpsiz2)",       /* 3 */
1059         "sram emulating flash", /* 4 */
1060         _unknown,       /* 5 */
1061         _unknown,       /* 6 */
1062         _unknown,       /* 7 */
1063 };
1064
1065 static const char *_yes_or_no(uint32_t v)
1066 {
1067         if (v)
1068                 return "YES";
1069         else
1070                 return "NO";
1071 }
1072
1073 static const char *const _rc_freq[] = {
1074         "4 MHz", "8 MHz", "12 MHz", "reserved"
1075 };
1076
1077 static void sam4_explain_ckgr_mor(struct sam4_chip *pChip)
1078 {
1079         uint32_t v;
1080         uint32_t rcen;
1081
1082         v = sam4_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
1083         LOG_USER("(main xtal enabled: %s)", _yes_or_no(v));
1084         v = sam4_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
1085         LOG_USER("(main osc bypass: %s)", _yes_or_no(v));
1086         rcen = sam4_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 3, 1);
1087         LOG_USER("(onchip RC-OSC enabled: %s)", _yes_or_no(rcen));
1088         v = sam4_reg_fieldname(pChip, "MOSCRCF", pChip->cfg.CKGR_MOR, 4, 3);
1089         LOG_USER("(onchip RC-OSC freq: %s)", _rc_freq[v]);
1090
1091         pChip->cfg.rc_freq = 0;
1092         if (rcen) {
1093                 switch (v) {
1094                         default:
1095                                 pChip->cfg.rc_freq = 0;
1096                                 break;
1097                         case 0:
1098                                 pChip->cfg.rc_freq = 4 * 1000 * 1000;
1099                                 break;
1100                         case 1:
1101                                 pChip->cfg.rc_freq = 8 * 1000 * 1000;
1102                                 break;
1103                         case 2:
1104                                 pChip->cfg.rc_freq = 12 * 1000 * 1000;
1105                                 break;
1106                 }
1107         }
1108
1109         v = sam4_reg_fieldname(pChip, "MOSCXTST", pChip->cfg.CKGR_MOR, 8, 8);
1110         LOG_USER("(startup clks, time= %f uSecs)",
1111                 ((float)(v * 1000000)) / ((float)(pChip->cfg.slow_freq)));
1112         v = sam4_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
1113         LOG_USER("(mainosc source: %s)",
1114                 v ? "external xtal" : "internal RC");
1115
1116         v = sam4_reg_fieldname(pChip, "CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
1117         LOG_USER("(clock failure enabled: %s)",
1118                 _yes_or_no(v));
1119 }
1120
1121 static void sam4_explain_chipid_cidr(struct sam4_chip *pChip)
1122 {
1123         int x;
1124         uint32_t v;
1125         const char *cp;
1126
1127         sam4_reg_fieldname(pChip, "Version", pChip->cfg.CHIPID_CIDR, 0, 5);
1128         LOG_USER_N("\n");
1129
1130         v = sam4_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
1131         LOG_USER("%s", eproc_names[v]);
1132
1133         v = sam4_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
1134         LOG_USER("%s", nvpsize[v]);
1135
1136         v = sam4_reg_fieldname(pChip, "NVPSIZE2", pChip->cfg.CHIPID_CIDR, 12, 4);
1137         LOG_USER("%s", nvpsize2[v]);
1138
1139         v = sam4_reg_fieldname(pChip, "SRAMSIZE", pChip->cfg.CHIPID_CIDR, 16, 4);
1140         LOG_USER("%s", sramsize[v]);
1141
1142         v = sam4_reg_fieldname(pChip, "ARCH", pChip->cfg.CHIPID_CIDR, 20, 8);
1143         cp = _unknown;
1144         for (x = 0; archnames[x].name; x++) {
1145                 if (v == archnames[x].value) {
1146                         cp = archnames[x].name;
1147                         break;
1148                 }
1149         }
1150
1151         LOG_USER("%s", cp);
1152
1153         v = sam4_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
1154         LOG_USER("%s", nvptype[v]);
1155
1156         v = sam4_reg_fieldname(pChip, "EXTID", pChip->cfg.CHIPID_CIDR, 31, 1);
1157         LOG_USER("(exists: %s)", _yes_or_no(v));
1158 }
1159
1160 static void sam4_explain_ckgr_mcfr(struct sam4_chip *pChip)
1161 {
1162         uint32_t v;
1163
1164         v = sam4_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
1165         LOG_USER("(main ready: %s)", _yes_or_no(v));
1166
1167         v = sam4_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
1168
1169         v = (v * pChip->cfg.slow_freq) / 16;
1170         pChip->cfg.mainosc_freq = v;
1171
1172         LOG_USER("(%3.03f Mhz (%d.%03dkhz slowclk)",
1173                 _tomhz(v),
1174                 pChip->cfg.slow_freq / 1000,
1175                 pChip->cfg.slow_freq % 1000);
1176 }
1177
1178 static void sam4_explain_ckgr_plla(struct sam4_chip *pChip)
1179 {
1180         uint32_t mula, diva;
1181
1182         diva = sam4_reg_fieldname(pChip, "DIVA", pChip->cfg.CKGR_PLLAR, 0, 8);
1183         LOG_USER_N("\n");
1184         mula = sam4_reg_fieldname(pChip, "MULA", pChip->cfg.CKGR_PLLAR, 16, 11);
1185         LOG_USER_N("\n");
1186         pChip->cfg.plla_freq = 0;
1187         if (mula == 0)
1188                 LOG_USER("\tPLLA Freq: (Disabled,mula = 0)");
1189         else if (diva == 0)
1190                 LOG_USER("\tPLLA Freq: (Disabled,diva = 0)");
1191         else if (diva == 1) {
1192                 pChip->cfg.plla_freq = (pChip->cfg.mainosc_freq * (mula + 1));
1193                 LOG_USER("\tPLLA Freq: %3.03f MHz",
1194                         _tomhz(pChip->cfg.plla_freq));
1195         }
1196 }
1197
1198 static void sam4_explain_mckr(struct sam4_chip *pChip)
1199 {
1200         uint32_t css, pres, fin = 0;
1201         int pdiv = 0;
1202         const char *cp = NULL;
1203
1204         css = sam4_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
1205         switch (css & 3) {
1206                 case 0:
1207                         fin = pChip->cfg.slow_freq;
1208                         cp = "slowclk";
1209                         break;
1210                 case 1:
1211                         fin = pChip->cfg.mainosc_freq;
1212                         cp  = "mainosc";
1213                         break;
1214                 case 2:
1215                         fin = pChip->cfg.plla_freq;
1216                         cp  = "plla";
1217                         break;
1218                 case 3:
1219                         if (pChip->cfg.CKGR_UCKR & (1 << 16)) {
1220                                 fin = 480 * 1000 * 1000;
1221                                 cp = "upll";
1222                         } else {
1223                                 fin = 0;
1224                                 cp  = "upll (*ERROR* UPLL is disabled)";
1225                         }
1226                         break;
1227                 default:
1228                         assert(0);
1229                         break;
1230         }
1231
1232         LOG_USER("%s (%3.03f Mhz)",
1233                 cp,
1234                 _tomhz(fin));
1235         pres = sam4_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
1236         switch (pres & 0x07) {
1237                 case 0:
1238                         pdiv = 1;
1239                         cp = "selected clock";
1240                         break;
1241                 case 1:
1242                         pdiv = 2;
1243                         cp = "clock/2";
1244                         break;
1245                 case 2:
1246                         pdiv = 4;
1247                         cp = "clock/4";
1248                         break;
1249                 case 3:
1250                         pdiv = 8;
1251                         cp = "clock/8";
1252                         break;
1253                 case 4:
1254                         pdiv = 16;
1255                         cp = "clock/16";
1256                         break;
1257                 case 5:
1258                         pdiv = 32;
1259                         cp = "clock/32";
1260                         break;
1261                 case 6:
1262                         pdiv = 64;
1263                         cp = "clock/64";
1264                         break;
1265                 case 7:
1266                         pdiv = 6;
1267                         cp = "clock/6";
1268                         break;
1269                 default:
1270                         assert(0);
1271                         break;
1272         }
1273         LOG_USER("(%s)", cp);
1274         fin = fin / pdiv;
1275         /* sam4 has a *SINGLE* clock - */
1276         /* other at91 series parts have divisors for these. */
1277         pChip->cfg.cpu_freq = fin;
1278         pChip->cfg.mclk_freq = fin;
1279         pChip->cfg.fclk_freq = fin;
1280         LOG_USER("\t\tResult CPU Freq: %3.03f",
1281                 _tomhz(fin));
1282 }
1283
1284 #if 0
1285 static struct sam4_chip *target2sam4(struct target *pTarget)
1286 {
1287         struct sam4_chip *pChip;
1288
1289         if (pTarget == NULL)
1290                 return NULL;
1291
1292         pChip = all_sam4_chips;
1293         while (pChip) {
1294                 if (pChip->target == pTarget)
1295                         break;  /* return below */
1296                 else
1297                         pChip = pChip->next;
1298         }
1299         return pChip;
1300 }
1301 #endif
1302
1303 static uint32_t *sam4_get_reg_ptr(struct sam4_cfg *pCfg, const struct sam4_reg_list *pList)
1304 {
1305         /* this function exists to help */
1306         /* keep funky offsetof() errors */
1307         /* and casting from causing bugs */
1308
1309         /* By using prototypes - we can detect what would */
1310         /* be casting errors. */
1311
1312         return (uint32_t *)(void *)(((char *)(pCfg)) + pList->struct_offset);
1313 }
1314
1315
1316 #define SAM4_ENTRY(NAME, FUNC)  { .address = SAM4_ ## NAME, .struct_offset = offsetof( \
1317                                                   struct sam4_cfg, \
1318                                                   NAME), # NAME, FUNC }
1319 static const struct sam4_reg_list sam4_all_regs[] = {
1320         SAM4_ENTRY(CKGR_MOR, sam4_explain_ckgr_mor),
1321         SAM4_ENTRY(CKGR_MCFR, sam4_explain_ckgr_mcfr),
1322         SAM4_ENTRY(CKGR_PLLAR, sam4_explain_ckgr_plla),
1323         SAM4_ENTRY(CKGR_UCKR, NULL),
1324         SAM4_ENTRY(PMC_FSMR, NULL),
1325         SAM4_ENTRY(PMC_FSPR, NULL),
1326         SAM4_ENTRY(PMC_IMR, NULL),
1327         SAM4_ENTRY(PMC_MCKR, sam4_explain_mckr),
1328         SAM4_ENTRY(PMC_PCK0, NULL),
1329         SAM4_ENTRY(PMC_PCK1, NULL),
1330         SAM4_ENTRY(PMC_PCK2, NULL),
1331         SAM4_ENTRY(PMC_PCSR, NULL),
1332         SAM4_ENTRY(PMC_SCSR, NULL),
1333         SAM4_ENTRY(PMC_SR, NULL),
1334         SAM4_ENTRY(CHIPID_CIDR, sam4_explain_chipid_cidr),
1335         SAM4_ENTRY(CHIPID_EXID, NULL),
1336         /* TERMINATE THE LIST */
1337         { .name = NULL }
1338 };
1339 #undef SAM4_ENTRY
1340
1341 static struct sam4_bank_private *get_sam4_bank_private(struct flash_bank *bank)
1342 {
1343         return (struct sam4_bank_private *)(bank->driver_priv);
1344 }
1345
1346 /**
1347  * Given a pointer to where it goes in the structure,
1348  * determine the register name, address from the all registers table.
1349  */
1350 static const struct sam4_reg_list *sam4_GetReg(struct sam4_chip *pChip, uint32_t *goes_here)
1351 {
1352         const struct sam4_reg_list *pReg;
1353
1354         pReg = &(sam4_all_regs[0]);
1355         while (pReg->name) {
1356                 uint32_t *pPossible;
1357
1358                 /* calculate where this one go.. */
1359                 /* it is "possibly" this register. */
1360
1361                 pPossible = ((uint32_t *)(void *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
1362
1363                 /* well? Is it this register */
1364                 if (pPossible == goes_here) {
1365                         /* Jump for joy! */
1366                         return pReg;
1367                 }
1368
1369                 /* next... */
1370                 pReg++;
1371         }
1372         /* This is *TOTAL*PANIC* - we are totally screwed. */
1373         LOG_ERROR("INVALID SAM4 REGISTER");
1374         return NULL;
1375 }
1376
1377 static int sam4_ReadThisReg(struct sam4_chip *pChip, uint32_t *goes_here)
1378 {
1379         const struct sam4_reg_list *pReg;
1380         int r;
1381
1382         pReg = sam4_GetReg(pChip, goes_here);
1383         if (!pReg)
1384                 return ERROR_FAIL;
1385
1386         r = target_read_u32(pChip->target, pReg->address, goes_here);
1387         if (r != ERROR_OK) {
1388                 LOG_ERROR("Cannot read SAM4 register: %s @ 0x%08x, Err: %d",
1389                         pReg->name, (unsigned)(pReg->address), r);
1390         }
1391         return r;
1392 }
1393
1394 static int sam4_ReadAllRegs(struct sam4_chip *pChip)
1395 {
1396         int r;
1397         const struct sam4_reg_list *pReg;
1398
1399         pReg = &(sam4_all_regs[0]);
1400         while (pReg->name) {
1401                 r = sam4_ReadThisReg(pChip,
1402                                 sam4_get_reg_ptr(&(pChip->cfg), pReg));
1403                 if (r != ERROR_OK) {
1404                         LOG_ERROR("Cannot read SAM4 registere: %s @ 0x%08x, Error: %d",
1405                                 pReg->name, ((unsigned)(pReg->address)), r);
1406                         return r;
1407                 }
1408                 pReg++;
1409         }
1410
1411         return ERROR_OK;
1412 }
1413
1414 static int sam4_GetInfo(struct sam4_chip *pChip)
1415 {
1416         const struct sam4_reg_list *pReg;
1417         uint32_t regval;
1418
1419         pReg = &(sam4_all_regs[0]);
1420         while (pReg->name) {
1421                 /* display all regs */
1422                 LOG_DEBUG("Start: %s", pReg->name);
1423                 regval = *sam4_get_reg_ptr(&(pChip->cfg), pReg);
1424                 LOG_USER("%*s: [0x%08x] -> 0x%08x",
1425                         REG_NAME_WIDTH,
1426                         pReg->name,
1427                         pReg->address,
1428                         regval);
1429                 if (pReg->explain_func)
1430                         (*(pReg->explain_func))(pChip);
1431                 LOG_DEBUG("End: %s", pReg->name);
1432                 pReg++;
1433         }
1434         LOG_USER("   rc-osc: %3.03f MHz", _tomhz(pChip->cfg.rc_freq));
1435         LOG_USER("  mainosc: %3.03f MHz", _tomhz(pChip->cfg.mainosc_freq));
1436         LOG_USER("     plla: %3.03f MHz", _tomhz(pChip->cfg.plla_freq));
1437         LOG_USER(" cpu-freq: %3.03f MHz", _tomhz(pChip->cfg.cpu_freq));
1438         LOG_USER("mclk-freq: %3.03f MHz", _tomhz(pChip->cfg.mclk_freq));
1439
1440         LOG_USER(" UniqueId: 0x%08x 0x%08x 0x%08x 0x%08x",
1441                 pChip->cfg.unique_id[0],
1442                 pChip->cfg.unique_id[1],
1443                 pChip->cfg.unique_id[2],
1444                 pChip->cfg.unique_id[3]);
1445
1446         return ERROR_OK;
1447 }
1448
1449 static int sam4_protect_check(struct flash_bank *bank)
1450 {
1451         int r;
1452         uint32_t v[4] = {0};
1453         unsigned x;
1454         struct sam4_bank_private *pPrivate;
1455
1456         LOG_DEBUG("Begin");
1457         if (bank->target->state != TARGET_HALTED) {
1458                 LOG_ERROR("Target not halted");
1459                 return ERROR_TARGET_NOT_HALTED;
1460         }
1461
1462         pPrivate = get_sam4_bank_private(bank);
1463         if (!pPrivate) {
1464                 LOG_ERROR("no private for this bank?");
1465                 return ERROR_FAIL;
1466         }
1467         if (!(pPrivate->probed))
1468                 return ERROR_FLASH_BANK_NOT_PROBED;
1469
1470         r = FLASHD_GetLockBits(pPrivate, v);
1471         if (r != ERROR_OK) {
1472                 LOG_DEBUG("Failed: %d", r);
1473                 return r;
1474         }
1475
1476         for (x = 0; x < pPrivate->nsectors; x++)
1477                 bank->sectors[x].is_protected = (!!(v[x >> 5] & (1 << (x % 32))));
1478         LOG_DEBUG("Done");
1479         return ERROR_OK;
1480 }
1481
1482 FLASH_BANK_COMMAND_HANDLER(sam4_flash_bank_command)
1483 {
1484         struct sam4_chip *pChip;
1485
1486         pChip = all_sam4_chips;
1487
1488         /* is this an existing chip? */
1489         while (pChip) {
1490                 if (pChip->target == bank->target)
1491                         break;
1492                 pChip = pChip->next;
1493         }
1494
1495         if (!pChip) {
1496                 /* this is a *NEW* chip */
1497                 pChip = calloc(1, sizeof(struct sam4_chip));
1498                 if (!pChip) {
1499                         LOG_ERROR("NO RAM!");
1500                         return ERROR_FAIL;
1501                 }
1502                 pChip->target = bank->target;
1503                 /* insert at head */
1504                 pChip->next = all_sam4_chips;
1505                 all_sam4_chips = pChip;
1506                 pChip->target = bank->target;
1507                 /* assumption is this runs at 32khz */
1508                 pChip->cfg.slow_freq = 32768;
1509                 pChip->probed = 0;
1510         }
1511
1512         switch (bank->base) {
1513                 default:
1514                         LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x"
1515                         "[at91sam4s series] )",
1516                         ((unsigned int)(bank->base)),
1517                         ((unsigned int)(FLASH_BANK_BASE_S)));
1518                         return ERROR_FAIL;
1519                         break;
1520
1521                 /* at91sam4s series only has bank 0*/
1522                 case FLASH_BANK_BASE_S:
1523                         bank->driver_priv = &(pChip->details.bank[0]);
1524                         bank->bank_number = 0;
1525                         pChip->details.bank[0].pChip = pChip;
1526                         pChip->details.bank[0].pBank = bank;
1527                         break;
1528         }
1529
1530         /* we initialize after probing. */
1531         return ERROR_OK;
1532 }
1533
1534 static int sam4_GetDetails(struct sam4_bank_private *pPrivate)
1535 {
1536         const struct sam4_chip_details *pDetails;
1537         struct sam4_chip *pChip;
1538         struct flash_bank *saved_banks[SAM4_MAX_FLASH_BANKS];
1539         unsigned x;
1540
1541         LOG_DEBUG("Begin");
1542         pDetails = all_sam4_details;
1543         while (pDetails->name) {
1544                 /* Compare cidr without version bits */
1545                 if (pDetails->chipid_cidr == (pPrivate->pChip->cfg.CHIPID_CIDR & 0xFFFFFFE0))
1546                         break;
1547                 else
1548                         pDetails++;
1549         }
1550         if (pDetails->name == NULL) {
1551                 LOG_ERROR("SAM4 ChipID 0x%08x not found in table (perhaps you can ID this chip?)",
1552                         (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
1553                 /* Help the victim, print details about the chip */
1554                 LOG_INFO("SAM4 CHIPID_CIDR: 0x%08x decodes as follows",
1555                         pPrivate->pChip->cfg.CHIPID_CIDR);
1556                 sam4_explain_chipid_cidr(pPrivate->pChip);
1557                 return ERROR_FAIL;
1558         }
1559
1560         /* DANGER: THERE ARE DRAGONS HERE */
1561
1562         /* get our pChip - it is going */
1563         /* to be over-written shortly */
1564         pChip = pPrivate->pChip;
1565
1566         /* Note that, in reality: */
1567         /*  */
1568         /*     pPrivate = &(pChip->details.bank[0]) */
1569         /* or  pPrivate = &(pChip->details.bank[1]) */
1570         /*  */
1571
1572         /* save the "bank" pointers */
1573         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++)
1574                 saved_banks[x] = pChip->details.bank[x].pBank;
1575
1576         /* Overwrite the "details" structure. */
1577         memcpy(&(pPrivate->pChip->details),
1578                 pDetails,
1579                 sizeof(pPrivate->pChip->details));
1580
1581         /* now fix the ghosted pointers */
1582         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
1583                 pChip->details.bank[x].pChip = pChip;
1584                 pChip->details.bank[x].pBank = saved_banks[x];
1585         }
1586
1587         /* update the *BANK*SIZE* */
1588
1589         LOG_DEBUG("End");
1590         return ERROR_OK;
1591 }
1592
1593 static int _sam4_probe(struct flash_bank *bank, int noise)
1594 {
1595         unsigned x;
1596         int r;
1597         struct sam4_bank_private *pPrivate;
1598
1599
1600         LOG_DEBUG("Begin: Bank: %d, Noise: %d", bank->bank_number, noise);
1601         if (bank->target->state != TARGET_HALTED) {
1602                 LOG_ERROR("Target not halted");
1603                 return ERROR_TARGET_NOT_HALTED;
1604         }
1605
1606         pPrivate = get_sam4_bank_private(bank);
1607         if (!pPrivate) {
1608                 LOG_ERROR("Invalid/unknown bank number");
1609                 return ERROR_FAIL;
1610         }
1611
1612         r = sam4_ReadAllRegs(pPrivate->pChip);
1613         if (r != ERROR_OK)
1614                 return r;
1615
1616         LOG_DEBUG("Here");
1617         if (pPrivate->pChip->probed)
1618                 r = sam4_GetInfo(pPrivate->pChip);
1619         else
1620                 r = sam4_GetDetails(pPrivate);
1621         if (r != ERROR_OK)
1622                 return r;
1623
1624         /* update the flash bank size */
1625         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
1626                 if (bank->base == pPrivate->pChip->details.bank[x].base_address) {
1627                         bank->size = pPrivate->pChip->details.bank[x].size_bytes;
1628                         break;
1629                 }
1630         }
1631
1632         if (bank->sectors == NULL) {
1633                 bank->sectors = calloc(pPrivate->nsectors, (sizeof((bank->sectors)[0])));
1634                 if (bank->sectors == NULL) {
1635                         LOG_ERROR("No memory!");
1636                         return ERROR_FAIL;
1637                 }
1638                 bank->num_sectors = pPrivate->nsectors;
1639
1640                 for (x = 0; ((int)(x)) < bank->num_sectors; x++) {
1641                         bank->sectors[x].size = pPrivate->sector_size;
1642                         bank->sectors[x].offset = x * (pPrivate->sector_size);
1643                         /* mark as unknown */
1644                         bank->sectors[x].is_erased = -1;
1645                         bank->sectors[x].is_protected = -1;
1646                 }
1647         }
1648
1649         pPrivate->probed = 1;
1650
1651         r = sam4_protect_check(bank);
1652         if (r != ERROR_OK)
1653                 return r;
1654
1655         LOG_DEBUG("Bank = %d, nbanks = %d",
1656                 pPrivate->bank_number, pPrivate->pChip->details.n_banks);
1657         if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
1658                 /* read unique id, */
1659                 /* it appears to be associated with the *last* flash bank. */
1660                 FLASHD_ReadUniqueID(pPrivate);
1661         }
1662
1663         return r;
1664 }
1665
1666 static int sam4_probe(struct flash_bank *bank)
1667 {
1668         return _sam4_probe(bank, 1);
1669 }
1670
1671 static int sam4_auto_probe(struct flash_bank *bank)
1672 {
1673         return _sam4_probe(bank, 0);
1674 }
1675
1676 static int sam4_erase(struct flash_bank *bank, int first, int last)
1677 {
1678         struct sam4_bank_private *pPrivate;
1679         int r;
1680         int i;
1681         int pageCount;
1682         /*16 pages equals 8KB - Same size as a lock region*/
1683         pageCount = 16;
1684         uint32_t status;
1685
1686         LOG_DEBUG("Here");
1687         if (bank->target->state != TARGET_HALTED) {
1688                 LOG_ERROR("Target not halted");
1689                 return ERROR_TARGET_NOT_HALTED;
1690         }
1691
1692         r = sam4_auto_probe(bank);
1693         if (r != ERROR_OK) {
1694                 LOG_DEBUG("Here,r=%d", r);
1695                 return r;
1696         }
1697
1698         pPrivate = get_sam4_bank_private(bank);
1699         if (!(pPrivate->probed))
1700                 return ERROR_FLASH_BANK_NOT_PROBED;
1701
1702         if ((first == 0) && ((last + 1) == ((int)(pPrivate->nsectors)))) {
1703                 /* whole chip */
1704                 LOG_DEBUG("Here");
1705                 return FLASHD_EraseEntireBank(pPrivate);
1706         }
1707         LOG_INFO("sam4 does not auto-erase while programing (Erasing relevant sectors)");
1708         LOG_INFO("sam4 First: 0x%08x Last: 0x%08x", (unsigned int)(first), (unsigned int)(last));
1709         for (i = first; i <= last; i++) {
1710                 /*16 pages equals 8KB - Same size as a lock region*/
1711                 r = FLASHD_ErasePages(pPrivate, (i * pageCount), pageCount, &status);
1712                 LOG_INFO("Erasing sector: 0x%08x", (unsigned int)(i));
1713                 if (r != ERROR_OK)
1714                         LOG_ERROR("SAM4: Error performing Erase page @ lock region number %d",
1715                                 (unsigned int)(i));
1716                 if (status & (1 << 2)) {
1717                         LOG_ERROR("SAM4: Lock Reqion %d is locked", (unsigned int)(i));
1718                         return ERROR_FAIL;
1719                 }
1720                 if (status & (1 << 1)) {
1721                         LOG_ERROR("SAM4: Flash Command error @lock region %d", (unsigned int)(i));
1722                         return ERROR_FAIL;
1723                 }
1724         }
1725
1726         return ERROR_OK;
1727 }
1728
1729 static int sam4_protect(struct flash_bank *bank, int set, int first, int last)
1730 {
1731         struct sam4_bank_private *pPrivate;
1732         int r;
1733
1734         LOG_DEBUG("Here");
1735         if (bank->target->state != TARGET_HALTED) {
1736                 LOG_ERROR("Target not halted");
1737                 return ERROR_TARGET_NOT_HALTED;
1738         }
1739
1740         pPrivate = get_sam4_bank_private(bank);
1741         if (!(pPrivate->probed))
1742                 return ERROR_FLASH_BANK_NOT_PROBED;
1743
1744         if (set)
1745                 r = FLASHD_Lock(pPrivate, (unsigned)(first), (unsigned)(last));
1746         else
1747                 r = FLASHD_Unlock(pPrivate, (unsigned)(first), (unsigned)(last));
1748         LOG_DEBUG("End: r=%d", r);
1749
1750         return r;
1751
1752 }
1753
1754 static int sam4_info(struct flash_bank *bank, char *buf, int buf_size)
1755 {
1756         if (bank->target->state != TARGET_HALTED) {
1757                 LOG_ERROR("Target not halted");
1758                 return ERROR_TARGET_NOT_HALTED;
1759         }
1760         buf[0] = 0;
1761         return ERROR_OK;
1762 }
1763
1764 static int sam4_page_read(struct sam4_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
1765 {
1766         uint32_t adr;
1767         int r;
1768
1769         adr = pagenum * pPrivate->page_size;
1770         adr = adr + pPrivate->base_address;
1771
1772         r = target_read_memory(pPrivate->pChip->target,
1773                         adr,
1774                         4,                                      /* THIS*MUST*BE* in 32bit values */
1775                         pPrivate->page_size / 4,
1776                         buf);
1777         if (r != ERROR_OK)
1778                 LOG_ERROR("SAM4: Flash program failed to read page phys address: 0x%08x",
1779                         (unsigned int)(adr));
1780         return r;
1781 }
1782
1783 /* The code below is basically this: */
1784 /* compiled with */
1785 /* arm-none-eabi-gcc -mthumb -mcpu = cortex-m3 -O9 -S ./foobar.c -o foobar.s */
1786 /*  */
1787 /* Only the *CPU* can write to the flash buffer. */
1788 /* the DAP cannot... so - we download this 28byte thing */
1789 /* Run the algorithm - (below) */
1790 /* to program the device */
1791 /*  */
1792 /* ======================================== */
1793 /* #include <stdint.h> */
1794 /*  */
1795 /* struct foo { */
1796 /*   uint32_t *dst; */
1797 /*   const uint32_t *src; */
1798 /*   int   n; */
1799 /*   volatile uint32_t *base; */
1800 /*   uint32_t   cmd; */
1801 /* }; */
1802 /*  */
1803 /*  */
1804 /* uint32_t sam4_function(struct foo *p) */
1805 /* { */
1806 /*   volatile uint32_t *v; */
1807 /*   uint32_t *d; */
1808 /*   const uint32_t *s; */
1809 /*   int   n; */
1810 /*   uint32_t r; */
1811 /*  */
1812 /*   d = p->dst; */
1813 /*   s = p->src; */
1814 /*   n = p->n; */
1815 /*  */
1816 /*   do { */
1817 /*     *d++ = *s++; */
1818 /*   } while (--n) */
1819 /*     ; */
1820 /*  */
1821 /*   v = p->base; */
1822 /*  */
1823 /*   v[ 1 ] = p->cmd; */
1824 /*   do { */
1825 /*     r = v[8/4]; */
1826 /*   } while (!(r&1)) */
1827 /*     ; */
1828 /*   return r; */
1829 /* } */
1830 /* ======================================== */
1831
1832 static const uint8_t
1833         sam4_page_write_opcodes[] = {
1834         /*  24 0000 0446                mov     r4, r0 */
1835         0x04, 0x46,
1836         /*  25 0002 6168                ldr     r1, [r4, #4] */
1837         0x61, 0x68,
1838         /*  26 0004 0068                ldr     r0, [r0, #0] */
1839         0x00, 0x68,
1840         /*  27 0006 A268                ldr     r2, [r4, #8] */
1841         0xa2, 0x68,
1842         /*  28                          @ lr needed for prologue */
1843         /*  29                  .L2: */
1844         /*  30 0008 51F8043B            ldr     r3, [r1], #4 */
1845         0x51, 0xf8, 0x04, 0x3b,
1846         /*  31 000c 12F1FF32            adds    r2, r2, #-1 */
1847         0x12, 0xf1, 0xff, 0x32,
1848         /*  32 0010 40F8043B            str     r3, [r0], #4 */
1849         0x40, 0xf8, 0x04, 0x3b,
1850         /*  33 0014 F8D1                bne     .L2 */
1851         0xf8, 0xd1,
1852         /*  34 0016 E268                ldr     r2, [r4, #12] */
1853         0xe2, 0x68,
1854         /*  35 0018 2369                ldr     r3, [r4, #16] */
1855         0x23, 0x69,
1856         /*  36 001a 5360                str     r3, [r2, #4] */
1857         0x53, 0x60,
1858         /*  37 001c 0832                adds    r2, r2, #8 */
1859         0x08, 0x32,
1860         /*  38                  .L4: */
1861         /*  39 001e 1068                ldr     r0, [r2, #0] */
1862         0x10, 0x68,
1863         /*  40 0020 10F0010F            tst     r0, #1 */
1864         0x10, 0xf0, 0x01, 0x0f,
1865         /*  41 0024 FBD0                beq     .L4 */
1866         0xfb, 0xd0,
1867         0x00, 0xBE                              /* bkpt #0 */
1868 };
1869
1870 static int sam4_page_write(struct sam4_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
1871 {
1872         uint32_t adr;
1873         uint32_t status;
1874         uint32_t fmr;   /* EEFC Flash Mode Register */
1875         int r;
1876
1877         adr = pagenum * pPrivate->page_size;
1878         adr = (adr + pPrivate->base_address);
1879
1880         /* Get flash mode register value */
1881         r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address, &fmr);
1882         if (r != ERROR_OK)
1883                 LOG_DEBUG("Error Read failed: read flash mode register");
1884
1885         /* Clear flash wait state field */
1886         fmr &= 0xfffff0ff;
1887
1888         /* set FWS (flash wait states) field in the FMR (flash mode register) */
1889         fmr |= (pPrivate->flash_wait_states << 8);
1890
1891         LOG_DEBUG("Flash Mode: 0x%08x", ((unsigned int)(fmr)));
1892         r = target_write_u32(pPrivate->pBank->target, pPrivate->controller_address, fmr);
1893         if (r != ERROR_OK)
1894                 LOG_DEBUG("Error Write failed: set flash mode register");
1895
1896         /* 1st sector 8kBytes - page 0 - 15*/
1897         /* 2nd sector 8kBytes - page 16 - 30*/
1898         /* 3rd sector 48kBytes - page 31 - 127*/
1899         LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
1900         r = target_write_memory(pPrivate->pChip->target,
1901                         adr,
1902                         4,                                      /* THIS*MUST*BE* in 32bit values */
1903                         pPrivate->page_size / 4,
1904                         buf);
1905         if (r != ERROR_OK) {
1906                 LOG_ERROR("SAM4: Failed to write (buffer) page at phys address 0x%08x",
1907                         (unsigned int)(adr));
1908                 return r;
1909         }
1910
1911         r = EFC_PerformCommand(pPrivate,
1912                         /* send Erase & Write Page */
1913                         AT91C_EFC_FCMD_WP,      /*AT91C_EFC_FCMD_EWP only works on first two 8kb sectors*/
1914                         pagenum,
1915                         &status);
1916
1917         if (r != ERROR_OK)
1918                 LOG_ERROR("SAM4: Error performing Write page @ phys address 0x%08x",
1919                         (unsigned int)(adr));
1920         if (status & (1 << 2)) {
1921                 LOG_ERROR("SAM4: Page @ Phys address 0x%08x is locked", (unsigned int)(adr));
1922                 return ERROR_FAIL;
1923         }
1924         if (status & (1 << 1)) {
1925                 LOG_ERROR("SAM4: Flash Command error @phys address 0x%08x", (unsigned int)(adr));
1926                 return ERROR_FAIL;
1927         }
1928         return ERROR_OK;
1929 }
1930
1931 static int sam4_write(struct flash_bank *bank,
1932         uint8_t *buffer,
1933         uint32_t offset,
1934         uint32_t count)
1935 {
1936         int n;
1937         unsigned page_cur;
1938         unsigned page_end;
1939         int r;
1940         unsigned page_offset;
1941         struct sam4_bank_private *pPrivate;
1942         uint8_t *pagebuffer;
1943
1944         /* incase we bail further below, set this to null */
1945         pagebuffer = NULL;
1946
1947         /* ignore dumb requests */
1948         if (count == 0) {
1949                 r = ERROR_OK;
1950                 goto done;
1951         }
1952
1953         if (bank->target->state != TARGET_HALTED) {
1954                 LOG_ERROR("Target not halted");
1955                 r = ERROR_TARGET_NOT_HALTED;
1956                 goto done;
1957         }
1958
1959         pPrivate = get_sam4_bank_private(bank);
1960         if (!(pPrivate->probed)) {
1961                 r = ERROR_FLASH_BANK_NOT_PROBED;
1962                 goto done;
1963         }
1964
1965         if ((offset + count) > pPrivate->size_bytes) {
1966                 LOG_ERROR("Flash write error - past end of bank");
1967                 LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
1968                         (unsigned int)(offset),
1969                         (unsigned int)(count),
1970                         (unsigned int)(pPrivate->size_bytes));
1971                 r = ERROR_FAIL;
1972                 goto done;
1973         }
1974
1975         pagebuffer = malloc(pPrivate->page_size);
1976         if (!pagebuffer) {
1977                 LOG_ERROR("No memory for %d Byte page buffer", (int)(pPrivate->page_size));
1978                 r = ERROR_FAIL;
1979                 goto done;
1980         }
1981
1982         /* what page do we start & end in? */
1983         page_cur = offset / pPrivate->page_size;
1984         page_end = (offset + count - 1) / pPrivate->page_size;
1985
1986         LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
1987         LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
1988
1989         /* Special case: all one page */
1990         /*  */
1991         /* Otherwise: */
1992         /*    (1) non-aligned start */
1993         /*    (2) body pages */
1994         /*    (3) non-aligned end. */
1995
1996         /* Handle special case - all one page. */
1997         if (page_cur == page_end) {
1998                 LOG_DEBUG("Special case, all in one page");
1999                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2000                 if (r != ERROR_OK)
2001                         goto done;
2002
2003                 page_offset = (offset & (pPrivate->page_size-1));
2004                 memcpy(pagebuffer + page_offset,
2005                         buffer,
2006                         count);
2007
2008                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2009                 if (r != ERROR_OK)
2010                         goto done;
2011                 r = ERROR_OK;
2012                 goto done;
2013         }
2014
2015         /* non-aligned start */
2016         page_offset = offset & (pPrivate->page_size - 1);
2017         if (page_offset) {
2018                 LOG_DEBUG("Not-Aligned start");
2019                 /* read the partial */
2020                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2021                 if (r != ERROR_OK)
2022                         goto done;
2023
2024                 /* over-write with new data */
2025                 n = (pPrivate->page_size - page_offset);
2026                 memcpy(pagebuffer + page_offset,
2027                         buffer,
2028                         n);
2029
2030                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2031                 if (r != ERROR_OK)
2032                         goto done;
2033
2034                 count  -= n;
2035                 offset += n;
2036                 buffer += n;
2037                 page_cur++;
2038         }
2039
2040         /* By checking that offset is correct here, we also
2041         fix a clang warning */
2042         assert(offset % pPrivate->page_size == 0);
2043
2044         /* intermediate large pages */
2045         /* also - the final *terminal* */
2046         /* if that terminal page is a full page */
2047         LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
2048                 (int)page_cur, (int)page_end, (unsigned int)(count));
2049
2050         while ((page_cur < page_end) &&
2051                         (count >= pPrivate->page_size)) {
2052                 r = sam4_page_write(pPrivate, page_cur, buffer);
2053                 if (r != ERROR_OK)
2054                         goto done;
2055                 count -= pPrivate->page_size;
2056                 buffer += pPrivate->page_size;
2057                 page_cur += 1;
2058         }
2059
2060         /* terminal partial page? */
2061         if (count) {
2062                 LOG_DEBUG("Terminal partial page, count = 0x%08x", (unsigned int)(count));
2063                 /* we have a partial page */
2064                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2065                 if (r != ERROR_OK)
2066                         goto done;
2067                                         /* data goes at start */
2068                 memcpy(pagebuffer, buffer, count);
2069                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2070                 if (r != ERROR_OK)
2071                         goto done;
2072         }
2073         LOG_DEBUG("Done!");
2074         r = ERROR_OK;
2075 done:
2076         if (pagebuffer)
2077                 free(pagebuffer);
2078         return r;
2079 }
2080
2081 COMMAND_HANDLER(sam4_handle_info_command)
2082 {
2083         struct sam4_chip *pChip;
2084         pChip = get_current_sam4(CMD_CTX);
2085         if (!pChip)
2086                 return ERROR_OK;
2087
2088         unsigned x;
2089         int r;
2090
2091         /* bank0 must exist before we can do anything */
2092         if (pChip->details.bank[0].pBank == NULL) {
2093                 x = 0;
2094 need_define:
2095                 command_print(CMD_CTX,
2096                         "Please define bank %d via command: flash bank %s ... ",
2097                         x,
2098                         at91sam4_flash.name);
2099                 return ERROR_FAIL;
2100         }
2101
2102         /* if bank 0 is not probed, then probe it */
2103         if (!(pChip->details.bank[0].probed)) {
2104                 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2105                 if (r != ERROR_OK)
2106                         return ERROR_FAIL;
2107         }
2108         /* above guarantees the "chip details" structure is valid */
2109         /* and thus, bank private areas are valid */
2110         /* and we have a SAM4 chip, what a concept! */
2111
2112         /* auto-probe other banks, 0 done above */
2113         for (x = 1; x < SAM4_MAX_FLASH_BANKS; x++) {
2114                 /* skip banks not present */
2115                 if (!(pChip->details.bank[x].present))
2116                         continue;
2117
2118                 if (pChip->details.bank[x].pBank == NULL)
2119                         goto need_define;
2120
2121                 if (pChip->details.bank[x].probed)
2122                         continue;
2123
2124                 r = sam4_auto_probe(pChip->details.bank[x].pBank);
2125                 if (r != ERROR_OK)
2126                         return r;
2127         }
2128
2129         r = sam4_GetInfo(pChip);
2130         if (r != ERROR_OK) {
2131                 LOG_DEBUG("Sam4Info, Failed %d", r);
2132                 return r;
2133         }
2134
2135         return ERROR_OK;
2136 }
2137
2138 COMMAND_HANDLER(sam4_handle_gpnvm_command)
2139 {
2140         unsigned x, v;
2141         int r, who;
2142         struct sam4_chip *pChip;
2143
2144         pChip = get_current_sam4(CMD_CTX);
2145         if (!pChip)
2146                 return ERROR_OK;
2147
2148         if (pChip->target->state != TARGET_HALTED) {
2149                 LOG_ERROR("sam4 - target not halted");
2150                 return ERROR_TARGET_NOT_HALTED;
2151         }
2152
2153         if (pChip->details.bank[0].pBank == NULL) {
2154                 command_print(CMD_CTX, "Bank0 must be defined first via: flash bank %s ...",
2155                         at91sam4_flash.name);
2156                 return ERROR_FAIL;
2157         }
2158         if (!pChip->details.bank[0].probed) {
2159                 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2160                 if (r != ERROR_OK)
2161                         return r;
2162         }
2163
2164         switch (CMD_ARGC) {
2165                 default:
2166                         return ERROR_COMMAND_SYNTAX_ERROR;
2167                         break;
2168                 case 0:
2169                         goto showall;
2170                         break;
2171                 case 1:
2172                         who = -1;
2173                         break;
2174                 case 2:
2175                         if ((0 == strcmp(CMD_ARGV[0], "show")) && (0 == strcmp(CMD_ARGV[1], "all")))
2176                                 who = -1;
2177                         else {
2178                                 uint32_t v32;
2179                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], v32);
2180                                 who = v32;
2181                         }
2182                         break;
2183         }
2184
2185         if (0 == strcmp("show", CMD_ARGV[0])) {
2186                 if (who == -1) {
2187 showall:
2188                         r = ERROR_OK;
2189                         for (x = 0; x < pChip->details.n_gpnvms; x++) {
2190                                 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
2191                                 if (r != ERROR_OK)
2192                                         break;
2193                                 command_print(CMD_CTX, "sam4-gpnvm%u: %u", x, v);
2194                         }
2195                         return r;
2196                 }
2197                 if ((who >= 0) && (((unsigned)(who)) < pChip->details.n_gpnvms)) {
2198                         r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), who, &v);
2199                         command_print(CMD_CTX, "sam4-gpnvm%u: %u", who, v);
2200                         return r;
2201                 } else {
2202                         command_print(CMD_CTX, "sam4-gpnvm invalid GPNVM: %u", who);
2203                         return ERROR_COMMAND_SYNTAX_ERROR;
2204                 }
2205         }
2206
2207         if (who == -1) {
2208                 command_print(CMD_CTX, "Missing GPNVM number");
2209                 return ERROR_COMMAND_SYNTAX_ERROR;
2210         }
2211
2212         if (0 == strcmp("set", CMD_ARGV[0]))
2213                 r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
2214         else if ((0 == strcmp("clr", CMD_ARGV[0])) ||
2215                  (0 == strcmp("clear", CMD_ARGV[0])))                   /* quietly accept both */
2216                 r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
2217         else {
2218                 command_print(CMD_CTX, "Unknown command: %s", CMD_ARGV[0]);
2219                 r = ERROR_COMMAND_SYNTAX_ERROR;
2220         }
2221         return r;
2222 }
2223
2224 COMMAND_HANDLER(sam4_handle_slowclk_command)
2225 {
2226         struct sam4_chip *pChip;
2227
2228         pChip = get_current_sam4(CMD_CTX);
2229         if (!pChip)
2230                 return ERROR_OK;
2231
2232         switch (CMD_ARGC) {
2233                 case 0:
2234                         /* show */
2235                         break;
2236                 case 1:
2237                 {
2238                         /* set */
2239                         uint32_t v;
2240                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], v);
2241                         if (v > 200000) {
2242                                 /* absurd slow clock of 200Khz? */
2243                                 command_print(CMD_CTX, "Absurd/illegal slow clock freq: %d\n", (int)(v));
2244                                 return ERROR_COMMAND_SYNTAX_ERROR;
2245                         }
2246                         pChip->cfg.slow_freq = v;
2247                         break;
2248                 }
2249                 default:
2250                         /* error */
2251                         command_print(CMD_CTX, "Too many parameters");
2252                         return ERROR_COMMAND_SYNTAX_ERROR;
2253                         break;
2254         }
2255         command_print(CMD_CTX, "Slowclk freq: %d.%03dkhz",
2256                 (int)(pChip->cfg.slow_freq / 1000),
2257                 (int)(pChip->cfg.slow_freq % 1000));
2258         return ERROR_OK;
2259 }
2260
2261 static const struct command_registration at91sam4_exec_command_handlers[] = {
2262         {
2263                 .name = "gpnvm",
2264                 .handler = sam4_handle_gpnvm_command,
2265                 .mode = COMMAND_EXEC,
2266                 .usage = "[('clr'|'set'|'show') bitnum]",
2267                 .help = "Without arguments, shows all bits in the gpnvm "
2268                         "register.  Otherwise, clears, sets, or shows one "
2269                         "General Purpose Non-Volatile Memory (gpnvm) bit.",
2270         },
2271         {
2272                 .name = "info",
2273                 .handler = sam4_handle_info_command,
2274                 .mode = COMMAND_EXEC,
2275                 .help = "Print information about the current at91sam4 chip"
2276                         "and its flash configuration.",
2277         },
2278         {
2279                 .name = "slowclk",
2280                 .handler = sam4_handle_slowclk_command,
2281                 .mode = COMMAND_EXEC,
2282                 .usage = "[clock_hz]",
2283                 .help = "Display or set the slowclock frequency "
2284                         "(default 32768 Hz).",
2285         },
2286         COMMAND_REGISTRATION_DONE
2287 };
2288 static const struct command_registration at91sam4_command_handlers[] = {
2289         {
2290                 .name = "at91sam4",
2291                 .mode = COMMAND_ANY,
2292                 .help = "at91sam4 flash command group",
2293                 .usage = "",
2294                 .chain = at91sam4_exec_command_handlers,
2295         },
2296         COMMAND_REGISTRATION_DONE
2297 };
2298
2299 struct flash_driver at91sam4_flash = {
2300         .name = "at91sam4",
2301         .commands = at91sam4_command_handlers,
2302         .flash_bank_command = sam4_flash_bank_command,
2303         .erase = sam4_erase,
2304         .protect = sam4_protect,
2305         .write = sam4_write,
2306         .read = default_flash_read,
2307         .probe = sam4_probe,
2308         .auto_probe = sam4_auto_probe,
2309         .erase_check = default_flash_blank_check,
2310         .protect_check = sam4_protect_check,
2311         .info = sam4_info,
2312 };