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