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